context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UsingKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsingKeyword()
{
await VerifyAbsenceAsync(@"using $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousUsing()
{
await VerifyKeywordAsync(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeUsing()
{
await VerifyKeywordAsync(
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsingAlias()
{
await VerifyKeywordAsync(
@"using Foo = Bar;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterTypeDeclaration()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedTypeDeclaration()
{
await VerifyAbsenceAsync(@"class A {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsingKeyword_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
using $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousUsing_InsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeUsing_InsideNamespace()
{
await VerifyKeywordAsync(
@"namespace N {
$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMember_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedMember_InsideNamespace()
{
await VerifyAbsenceAsync(@"namespace N {
class A {
class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeExtern()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
extern alias Foo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeExtern_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
extern alias Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true)
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDo()
{
await VerifyKeywordAsync(AddInsideMethod(
@"do
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterWhile()
{
await VerifyKeywordAsync(AddInsideMethod(
@"while (true)
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFor()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for (int i = 0; i < 10; i++)
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterForeach()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach (var v in bar)
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterUsing()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"using $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInClass()
{
await VerifyAbsenceAsync(@"class C
{
$$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBetweenUsings()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using Foo;
$$
using Bar;"));
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class TimerDecoder
{
public const ushort BLOCK_LENGTH = 16;
public const ushort TEMPLATE_ID = 104;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private TimerDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public TimerDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public TimerDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int CorrelationIdId()
{
return 1;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 0;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int DeadlineId()
{
return 2;
}
public static int DeadlineSinceVersion()
{
return 0;
}
public static int DeadlineEncodingOffset()
{
return 8;
}
public static int DeadlineEncodingLength()
{
return 8;
}
public static string DeadlineMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long DeadlineNullValue()
{
return -9223372036854775808L;
}
public static long DeadlineMinValue()
{
return -9223372036854775807L;
}
public static long DeadlineMaxValue()
{
return 9223372036854775807L;
}
public long Deadline()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[Timer](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='deadline', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Deadline=");
builder.Append(Deadline());
Limit(originalLimit);
return builder;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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 TUVienna.CS_CUP
{
using System.Collections;
/** This class represents a non-terminal symbol in the grammar. Each
* non terminal has a textual name, an index, and a string which indicates
* the type of object it will be implemented with at runtime (i.e. the class
* of object that will be pushed on the parse stack to represent it).
*
* @version last updated: 11/25/95
* @author Scott Hudson
* translated to C# 08.09.2003 by Samuel Imriska
*/
public class non_terminal : symbol
{
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Full constructor.
* @param nm the name of the non terminal.
* @param tp the type string for the non terminal.
*/
public non_terminal(string nm, string tp):base(nm,tp)
{
/* super class does most of the work */
/* add to Set of all non terminals and check for duplicates */
try
{
_all.Add(nm,this);
}
catch
{
// can't throw an exception here because these are used in static
// initializers, so we crash instead
// was:
// throw new internal_error("Duplicate non-terminal ("+nm+") created");
(new internal_error("Duplicate non-terminal ("+nm+") created")).crash();
}
/* assign a unique index */
_index = next_index++;
/* add to by_index Set */
_all_by_index.Add(_index, this);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Constructor with default type.
* @param nm the name of the non terminal.
*/
public non_terminal(string nm) :this(nm,null){ }
/*-----------------------------------------------------------*/
/*--- (Access to) Static (Class) Variables ------------------*/
/*-----------------------------------------------------------*/
/** Table of all non-terminals -- elements are stored using name strings
* as the key
*/
protected static Hashtable _all = new Hashtable();
/** Access to all non-terminals. */
public static IEnumerator all() {return _all.Values.GetEnumerator();}
/** lookup a non terminal by name string */
public static non_terminal find(string with_name)
{
if (with_name == null)
return null;
else
return (non_terminal)_all[with_name];
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Table of all non terminals indexed by their index number. */
protected static Hashtable _all_by_index = new Hashtable();
/** Lookup a non terminal by index. */
public static non_terminal find(int indx)
{
int the_indx = indx;
return (non_terminal)_all_by_index[the_indx];
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Total number of non-terminals. */
public static int number() {return _all.Count;}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Static counter to assign unique indexes. */
protected static int next_index = 0;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Static counter for creating unique non-terminal names */
static protected int next_nt = 0;
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** special non-terminal for start symbol */
public static non_terminal START_nt = new non_terminal("$START");
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** flag non-terminals created to embed action productions */
public bool is_embedded_action = false; /* added 24-Mar-1998, CSA */
/*-----------------------------------------------------------*/
/*--- Static Methods ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Method for creating a new uniquely named hidden non-terminal using
* the given string as a base for the name (or "NT$" if null is passed).
* @param prefix base name to construct unique name from.
*/
static non_terminal create_new(string prefix)
{
if (prefix == null) prefix = "NT$";
return new non_terminal(prefix + next_nt++);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** static routine for creating a new uniquely named hidden non-terminal */
public static non_terminal create_new()
{
return create_new(null);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Compute nullability of all non-terminals. */
public static void compute_nullability()
{
bool change = true;
non_terminal nt;
IEnumerator e;
production prod;
/* repeat this process until there is no change */
while (change)
{
/* look for a new change */
change = false;
/* consider each non-terminal */
e=all();
while ( e.MoveNext())
{
nt = (non_terminal)e.Current;
/* only look at things that aren't already marked nullable */
if (!nt.nullable())
{
if (nt.looks_nullable())
{
nt._nullable = true;
change = true;
}
}
}
}
/* do one last pass over the productions to finalize all of them */
e=production.all();
while ( e.MoveNext())
{
prod = (production)e.Current;
prod.set_nullable(prod.check_nullable());
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Compute first sets for all non-terminals. This assumes nullability has
* already computed.
*/
public static void compute_first_sets()
{
bool change = true;
IEnumerator n;
IEnumerator p;
non_terminal nt;
production prod;
terminal_set prod_first;
/* repeat this process until we have no change */
while (change)
{
/* look for a new change */
change = false;
/* consider each non-terminal */
n = all();
while ( n.MoveNext() )
{
nt = (non_terminal)n.Current;
/* consider every production of that non terminal */
p = nt.productions();
while ( p.MoveNext() )
{
prod = (production)p.Current;
/* get the updated first of that production */
prod_first = prod.check_first_set();
/* if this going to add anything, add it */
if (!prod_first.is_subset_of(nt._first_set))
{
change = true;
nt._first_set.add(prod_first);
}
}
}
}
}
/*-----------------------------------------------------------*/
/*--- (Access to) Instance Variables ------------------------*/
/*-----------------------------------------------------------*/
/** Table of all productions with this non terminal on the LHS. */
protected Hashtable _productions = new Hashtable(11);
/** Access to productions with this non terminal on the LHS. */
public IEnumerator productions() {return _productions.Values.GetEnumerator();}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Total number of productions with this non terminal on the LHS. */
public int num_productions() {return _productions.Count;}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Add a production to our Set of productions. */
public void add_production(production prod)
{
/* catch improper productions */
if (prod == null || prod.lhs() == null || prod.lhs().the_symbol() != this)
throw new internal_error(
"Attempt to add invalid production to non terminal production table");
/* add it to the table, keyed with itself */
_productions.Add(prod,prod);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Nullability of this non terminal. */
protected bool _nullable;
/** Nullability of this non terminal. */
public bool nullable() {return _nullable;}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** First Set for this non-terminal. */
protected terminal_set _first_set = new terminal_set();
/** First Set for this non-terminal. */
public terminal_set first_set() {return _first_set;}
/*-----------------------------------------------------------*/
/*--- General Methods ---------------------------------------*/
/*-----------------------------------------------------------*/
/** Indicate that this symbol is a non-terminal. */
public override bool is_non_term()
{
return true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Test to see if this non terminal currently looks nullable. */
protected bool looks_nullable()
{
/* look and see if any of the productions now look nullable */
IEnumerator e = productions();
while ( e.MoveNext() )
/* if the production can go to empty, we are nullable */
if (((production)e.Current).check_nullable())
return true;
/* none of the productions can go to empty, so we are not nullable */
return false;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** convert to string */
public override string ToString()
{
return base.ToString() + "[" + index() + "]" + (nullable() ? "*" : "");
}
/*-----------------------------------------------------------*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : IDisposable
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private static object s_createProcessLock = new object();
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
#if FEATURE_TRACESWITCH
internal static TraceSwitch _processTracing =
#if DEBUG
new TraceSwitch("processTracing", "Controls debug output from Process component");
#else
null;
#endif
#endif
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Process))
{
GC.SuppressFinalize(this);
}
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
GC.SuppressFinalize(this);
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
~Process()
{
Dispose(false);
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return OpenProcessHandle();
}
}
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveId | State.IsLocal);
ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(_processId);
ProcessModule[] newModulesArray = new ProcessModule[moduleInfos.Length];
for (int i = 0; i < moduleInfos.Length; i++)
{
newModulesArray[i] = new ProcessModule(moduleInfos[i]);
}
ProcessModuleCollection newModules = new ProcessModuleCollection(newModulesArray);
_modules = newModules;
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, typeof(ProcessPriorityClass)));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/>
/// .
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
OpenProcessHandle();
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// Release the temporary handle we used to get process information.
/// If we used the process handle stored in the process object (we have all access to the handle,) don't release it.
/// </devdoc>
/// <internalonly/>
private void ReleaseProcessHandle(SafeProcessHandle handle)
{
if (handle == null)
{
return;
}
if (_haveProcessHandle && handle == _processHandle)
{
return;
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process)");
#endif
handle.Dispose();
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object context, bool wasSignaled)
{
StopWatchingForExit();
RaiseOnExited();
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
internal void Close()
{
if (Associated)
{
if (_haveProcessHandle)
{
StopWatchingForExit();
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
#endif
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
//Don't call close on the Readers and writers
//since they might be referenced by somebody else while the
//process is still alive but this method called.
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId);
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we are watching for a process exit.
/// </devdoc>
/// <internalonly/>
private void EnsureWatchingForExit()
{
if (!_watchingForExit)
{
lock (this)
{
if (!_watchingForExit)
{
Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle");
Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
_watchingForExit = true;
try
{
_waitHandle = new ProcessWaitHandle(_processHandle);
_registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle,
new WaitOrTimerCallback(CompletionCallback), null, -1, true);
}
catch
{
_watchingForExit = false;
throw;
}
}
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
#if FEATURE_TRACESWITCH
Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")");
#if DEBUG
if (_processTracing.TraceVerbose) {
Debug.Indent();
for (int i = 0; i < processInfos.Length; i++) {
Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName);
}
Debug.Unindent();
}
#endif
#endif
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle OpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
}
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return StartCore(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException(nameof(startInfo));
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
RegisteredWaitHandle rwh = null;
WaitHandle wh = null;
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
wh = _waitHandle;
_waitHandle = null;
rwh = _registeredWaitHandle;
_registeredWaitHandle = null;
}
}
if (rwh != null)
{
rwh.Unregister(null);
}
if (wh != null)
{
wh.Dispose();
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(String data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
using DAL;
using DAL.Models;
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using FluentValidation.AspNetCore;
using AutoMapper;
using Newtonsoft.Json;
using DAL.Core;
using DAL.Core.Interfaces;
using Microsoft.AspNetCore.Authorization;
using lazarus.ViewModels;
using lazarus.Helpers;
using lazarus.Policies;
using AppPermissions = DAL.Core.ApplicationPermissions;
using AspNet.Security.OpenIdConnect.Primitives;
using OpenIddict.Core;
namespace lazarus
{
public class Startup
{
public IConfigurationRoot Configuration { get; }
private IHostingEnvironment _hostingEnvironment;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
_hostingEnvironment = env;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
SystemConfigurations.LoadConfiguration(
bool.Parse(Configuration["SysConfig:AutoProcessAppointments"]),
bool.Parse(Configuration["SysConfig:ManualProcessAppointments"]),
TimeSpan.FromMinutes(int.Parse(Configuration["SysConfig:AppointmentDuration"])));
EmailTemplates.Initialize(_hostingEnvironment);
EmailSender.Configuration = new SmtpConfig
{
Host = Configuration["SmtpConfig:Host"],
Port = int.Parse(Configuration["SmtpConfig:Port"]),
UseSSL = bool.Parse(Configuration["SmtpConfig:UseSSL"]),
Name = Configuration["SmtpConfig:Name"],
Username = Configuration["SmtpConfig:Username"],
EmailAddress = Configuration["SmtpConfig:EmailAddress"],
Password = Configuration["SmtpConfig:Password"]
};
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"], b => b.MigrationsAssembly("lazarus"));
options.UseOpenIddict();
});
// add identity
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Configure Identity options and password complexity here
services.Configure<IdentityOptions>(options =>
{
// User settings
options.User.RequireUniqueEmail = true;
// //// Password settings
// //options.Password.RequireDigit = true;
// //options.Password.RequiredLength = 8;
// //options.Password.RequireNonAlphanumeric = false;
// //options.Password.RequireUppercase = true;
// //options.Password.RequireLowercase = false;
// //// Lockout settings
// //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
// //options.Lockout.MaxFailedAccessAttempts = 10;
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
// Register the OpenIddict services.
services.AddOpenIddict(options =>
{
options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
options.AddMvcBinders();
options.EnableTokenEndpoint("/connect/token");
options.AllowPasswordFlow()
.AllowRefreshTokenFlow();
options.DisableHttpsRequirement();
// options.UseJsonWebTokens(); //Use JWT if preferred
options.AddSigningKey(new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["STSKey"])));
});
// Enable cors if required
//services.AddCors();
// Add framework services.
services.AddMvc();
//Todo: ***Using DataAnnotations for validation until Swashbuckle supports FluentValidation***
//services.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
//.AddJsonOptions(opts =>
//{
// opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//});
services.AddSwaggerGen(o =>
{
o.AddSecurityDefinition("BearerAuth", new Swashbuckle.Swagger.Model.ApiKeyScheme
{
Name = "Authorization",
Description = "Login with your bearer authentication token. e.g. Bearer <auth-token>",
In = "header",
Type = "apiKey"
});
});
services.AddAuthorization(options =>
{
options.AddPolicy(AuthPolicies.ViewUserByUserIdPolicy, policy => policy.Requirements.Add(new ViewUserByIdRequirement()));
options.AddPolicy(AuthPolicies.ViewUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewUsers));
options.AddPolicy(AuthPolicies.ManageUserByUserIdPolicy, policy => policy.Requirements.Add(new ManageUserByIdRequirement()));
options.AddPolicy(AuthPolicies.ManageUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageUsers));
options.AddPolicy(AuthPolicies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleByNameRequirement()));
options.AddPolicy(AuthPolicies.ViewRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewRoles));
options.AddPolicy(AuthPolicies.AssignRolesPolicy, policy => policy.Requirements.Add(new AssignRolesRequirement()));
options.AddPolicy(AuthPolicies.ManageRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageRoles));
});
Mapper.Initialize(cfg =>
{
cfg.AddProfile<AutoMapperProfile>();
});
// Repositories
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IAccountManager, AccountManager>();
// Auth Policies
services.AddSingleton<IAuthorizationHandler, ViewUserByIdHandler>();
services.AddSingleton<IAuthorizationHandler, ManageUserByIdHandler>();
services.AddSingleton<IAuthorizationHandler, ViewRoleByNameHandler>();
services.AddSingleton<IAuthorizationHandler, AssignRolesHandler>();
// DB Creation and Seeding
services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IDatabaseInitializer databaseInitializer, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(LogLevel.Warning);
loggerFactory.AddFile(Configuration.GetSection("Logging"));
Utilities.ConfigureLogger(loggerFactory);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
// Configure Cors if enabled
//app.UseCors(builder => builder
// .AllowAnyOrigin()
// .AllowAnyHeader()
// .AllowAnyMethod());
app.UseStaticFiles();
app.UseOAuthValidation();
app.UseOpenIddict();
// Configure jwt bearer authentication if enabled
//app.UseJwtBearerAuthentication(new JwtBearerOptions
//{
// AutomaticAuthenticate = true,
// AutomaticChallenge = true,
// RequireHttpsMetadata = false,
// Audience = "http://localhost:58292/",
// Authority = "http://localhost:58292/",
// //TokenValidationParameters = new TokenValidationParameters
// //{
// // ValidateIssuer = true,
// // ValidIssuer = "http://localhost:58292/",
// // ValidateAudience = true,
// // ValidAudience = "http://localhost:58292/",
// // ValidateLifetime = true,
// //}
//});
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = MediaTypeNames.ApplicationJson;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
string errorMsg = JsonConvert.SerializeObject(new { error = error.Error.Message });
await context.Response.WriteAsync(errorMsg).ConfigureAwait(false);
}
});
});
app.UseSwagger();
app.UseSwaggerUi();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
try
{
databaseInitializer.SeedAsync().Wait();
}
catch (Exception ex)
{
Utilities.CreateLogger<Startup>().LogCritical(LoggingEvents.INIT_DATABASE, ex, LoggingEvents.INIT_DATABASE.Name);
throw;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// ExecutionResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Studio.V2.Flow
{
public class ExecutionResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Active = new StatusEnum("active");
public static readonly StatusEnum Ended = new StatusEnum("ended");
}
private static Request BuildReadRequest(ReadExecutionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathFlowSid + "/Executions",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Executions for the Flow.
/// </summary>
/// <param name="options"> Read Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ResourceSet<ExecutionResource> Read(ReadExecutionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ExecutionResource>.FromJson("executions", response.Content);
return new ResourceSet<ExecutionResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Executions for the Flow.
/// </summary>
/// <param name="options"> Read Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ExecutionResource>> ReadAsync(ReadExecutionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ExecutionResource>.FromJson("executions", response.Content);
return new ResourceSet<ExecutionResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Executions for the Flow.
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="dateCreatedFrom"> Only show Executions that started on or after this ISO 8601 date-time </param>
/// <param name="dateCreatedTo"> Only show Executions that started before this ISO 8601 date-time </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ResourceSet<ExecutionResource> Read(string pathFlowSid,
DateTime? dateCreatedFrom = null,
DateTime? dateCreatedTo = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadExecutionOptions(pathFlowSid){DateCreatedFrom = dateCreatedFrom, DateCreatedTo = dateCreatedTo, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Executions for the Flow.
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="dateCreatedFrom"> Only show Executions that started on or after this ISO 8601 date-time </param>
/// <param name="dateCreatedTo"> Only show Executions that started before this ISO 8601 date-time </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ExecutionResource>> ReadAsync(string pathFlowSid,
DateTime? dateCreatedFrom = null,
DateTime? dateCreatedTo = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadExecutionOptions(pathFlowSid){DateCreatedFrom = dateCreatedFrom, DateCreatedTo = dateCreatedTo, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ExecutionResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ExecutionResource>.FromJson("executions", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ExecutionResource> NextPage(Page<ExecutionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Studio)
);
var response = client.Request(request);
return Page<ExecutionResource>.FromJson("executions", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ExecutionResource> PreviousPage(Page<ExecutionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Studio)
);
var response = client.Request(request);
return Page<ExecutionResource>.FromJson("executions", response.Content);
}
private static Request BuildFetchRequest(FetchExecutionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathFlowSid + "/Executions/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve an Execution
/// </summary>
/// <param name="options"> Fetch Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ExecutionResource Fetch(FetchExecutionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Retrieve an Execution
/// </summary>
/// <param name="options"> Fetch Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ExecutionResource> FetchAsync(FetchExecutionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Retrieve an Execution
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="pathSid"> The SID of the Execution resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ExecutionResource Fetch(string pathFlowSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchExecutionOptions(pathFlowSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Retrieve an Execution
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="pathSid"> The SID of the Execution resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ExecutionResource> FetchAsync(string pathFlowSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchExecutionOptions(pathFlowSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateExecutionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathFlowSid + "/Executions",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Triggers a new Execution for the Flow
/// </summary>
/// <param name="options"> Create Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ExecutionResource Create(CreateExecutionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Triggers a new Execution for the Flow
/// </summary>
/// <param name="options"> Create Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ExecutionResource> CreateAsync(CreateExecutionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Triggers a new Execution for the Flow
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="to"> The Contact phone number to start a Studio Flow Execution </param>
/// <param name="from"> The Twilio phone number or Messaging Service SID to send messages or initiate calls from during
/// the Flow Execution </param>
/// <param name="parameters"> JSON data that will be added to the Flow's context </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ExecutionResource Create(string pathFlowSid,
Types.PhoneNumber to,
Types.PhoneNumber from,
object parameters = null,
ITwilioRestClient client = null)
{
var options = new CreateExecutionOptions(pathFlowSid, to, from){Parameters = parameters};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Triggers a new Execution for the Flow
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="to"> The Contact phone number to start a Studio Flow Execution </param>
/// <param name="from"> The Twilio phone number or Messaging Service SID to send messages or initiate calls from during
/// the Flow Execution </param>
/// <param name="parameters"> JSON data that will be added to the Flow's context </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ExecutionResource> CreateAsync(string pathFlowSid,
Types.PhoneNumber to,
Types.PhoneNumber from,
object parameters = null,
ITwilioRestClient client = null)
{
var options = new CreateExecutionOptions(pathFlowSid, to, from){Parameters = parameters};
return await CreateAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteExecutionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathFlowSid + "/Executions/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete the Execution and all Steps relating to it.
/// </summary>
/// <param name="options"> Delete Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static bool Delete(DeleteExecutionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete the Execution and all Steps relating to it.
/// </summary>
/// <param name="options"> Delete Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteExecutionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete the Execution and all Steps relating to it.
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="pathSid"> The SID of the Execution resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static bool Delete(string pathFlowSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteExecutionOptions(pathFlowSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete the Execution and all Steps relating to it.
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="pathSid"> The SID of the Execution resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathFlowSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteExecutionOptions(pathFlowSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateExecutionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathFlowSid + "/Executions/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Update the status of an Execution to `ended`.
/// </summary>
/// <param name="options"> Update Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ExecutionResource Update(UpdateExecutionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Update the status of an Execution to `ended`.
/// </summary>
/// <param name="options"> Update Execution parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ExecutionResource> UpdateAsync(UpdateExecutionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Update the status of an Execution to `ended`.
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="pathSid"> The SID of the Execution resource to update </param>
/// <param name="status"> The status of the Execution </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Execution </returns>
public static ExecutionResource Update(string pathFlowSid,
string pathSid,
ExecutionResource.StatusEnum status,
ITwilioRestClient client = null)
{
var options = new UpdateExecutionOptions(pathFlowSid, pathSid, status);
return Update(options, client);
}
#if !NET35
/// <summary>
/// Update the status of an Execution to `ended`.
/// </summary>
/// <param name="pathFlowSid"> The SID of the Flow </param>
/// <param name="pathSid"> The SID of the Execution resource to update </param>
/// <param name="status"> The status of the Execution </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Execution </returns>
public static async System.Threading.Tasks.Task<ExecutionResource> UpdateAsync(string pathFlowSid,
string pathSid,
ExecutionResource.StatusEnum status,
ITwilioRestClient client = null)
{
var options = new UpdateExecutionOptions(pathFlowSid, pathSid, status);
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ExecutionResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ExecutionResource object represented by the provided JSON </returns>
public static ExecutionResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ExecutionResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Flow
/// </summary>
[JsonProperty("flow_sid")]
public string FlowSid { get; private set; }
/// <summary>
/// The phone number, SIP address or Client identifier that triggered the Execution
/// </summary>
[JsonProperty("contact_channel_address")]
public string ContactChannelAddress { get; private set; }
/// <summary>
/// The current state of the flow
/// </summary>
[JsonProperty("context")]
public object Context { get; private set; }
/// <summary>
/// The status of the Execution
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public ExecutionResource.StatusEnum Status { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// Nested resource URLs
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private ExecutionResource()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace OmniBeanEB.Library
{
public struct EBPrimitive
{
private class PrimitiveComparer : IEqualityComparer<EBPrimitive>
{
private static EBPrimitive.PrimitiveComparer _instance = new EBPrimitive.PrimitiveComparer();
public static EBPrimitive.PrimitiveComparer Instance
{
get
{
return EBPrimitive.PrimitiveComparer._instance;
}
}
private PrimitiveComparer()
{
}
public bool Equals(EBPrimitive x, EBPrimitive y)
{
return string.Equals(x.AsString, y.AsString, StringComparison.InvariantCultureIgnoreCase);
}
public int GetHashCode(EBPrimitive obj)
{
return obj.GetHashCode();
}
}
private string _primitive;
private decimal? _primitiveAsDecimal;
private Dictionary<EBPrimitive, EBPrimitive> _arrayMap;
public EBPrimitive this[EBPrimitive index]
{
get
{
if (this.ContainsKey(index))
{
return this._arrayMap[index];
}
return "";
}
set
{
EBPrimitive EBPrimitive = EBPrimitive.SetArrayValue(value, this, index);
this._primitive = EBPrimitive._primitive;
this._arrayMap = EBPrimitive._arrayMap;
this._primitiveAsDecimal = EBPrimitive._primitiveAsDecimal;
}
}
internal string AsString
{
get
{
if (this._primitive != null)
{
return this._primitive;
}
if (this._primitiveAsDecimal.HasValue)
{
this._primitive = this._primitiveAsDecimal.Value.ToString();
}
if (this._arrayMap != null)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (KeyValuePair<EBPrimitive, EBPrimitive> current in this._arrayMap)
{
stringBuilder.AppendFormat("{0}={1};", EBPrimitive.Escape(current.Key), EBPrimitive.Escape(current.Value));
}
this._primitive = stringBuilder.ToString();
}
return this._primitive;
}
}
internal bool IsArray
{
get
{
this.ConstructArrayMap();
return this._arrayMap.Count > 0;
}
}
internal bool IsEmpty
{
get
{
return string.IsNullOrEmpty(this._primitive) && !this._primitiveAsDecimal.HasValue && (this._arrayMap == null || this._arrayMap.Count == 0);
}
}
internal bool IsNumber
{
get
{
decimal num = 0m;
return this._primitiveAsDecimal.HasValue || decimal.TryParse(this.AsString, NumberStyles.Float, CultureInfo.InvariantCulture, out num);
}
}
public EBPrimitive(string primitiveText)
{
if (primitiveText == null)
{
throw new ArgumentNullException("primitiveText");
}
this._primitive = primitiveText;
this._primitiveAsDecimal = null;
this._arrayMap = null;
}
public EBPrimitive(int primitiveInteger)
{
this._primitiveAsDecimal = new decimal?(primitiveInteger);
this._primitive = null;
this._arrayMap = null;
}
public EBPrimitive(decimal primitiveDecimal)
{
this._primitiveAsDecimal = new decimal?(primitiveDecimal);
this._primitive = null;
this._arrayMap = null;
}
public EBPrimitive(float primitiveFloat)
{
this = new EBPrimitive((decimal)primitiveFloat);
}
public EBPrimitive(double primitiveDouble)
{
this = new EBPrimitive((decimal)primitiveDouble);
}
public EBPrimitive(short primitiveShort)
{
this = new EBPrimitive((int)primitiveShort);
}
public EBPrimitive(long primitiveLong)
{
this._primitiveAsDecimal = new decimal?(primitiveLong);
this._primitive = null;
this._arrayMap = null;
}
public EBPrimitive(object primitiveObject)
{
this._primitive = primitiveObject.ToString();
this._primitiveAsDecimal = null;
this._arrayMap = null;
}
public EBPrimitive(bool primitiveBool)
{
this._primitiveAsDecimal = null;
if (primitiveBool)
{
this._primitive = "True";
}
else
{
this._primitive = "False";
}
this._arrayMap = null;
}
public EBPrimitive Append(EBPrimitive EBPrimitive)
{
return new EBPrimitive(this.AsString + EBPrimitive.AsString);
}
public EBPrimitive Add(EBPrimitive addend)
{
decimal? num = this.TryGetAsDecimal();
decimal? num2 = addend.TryGetAsDecimal();
if (num.HasValue && num2.HasValue)
{
return num.Value + num2.Value;
}
return this.AsString + addend.AsString;
}
public EBPrimitive ContainsKey(EBPrimitive key)
{
this.ConstructArrayMap();
return this._arrayMap.ContainsKey(key);
}
public EBPrimitive ContainsValue(EBPrimitive value)
{
this.ConstructArrayMap();
return this._arrayMap.ContainsValue(value);
}
public EBPrimitive GetAllIndices()
{
this.ConstructArrayMap();
Dictionary<EBPrimitive, EBPrimitive> dictionary = new Dictionary<EBPrimitive, EBPrimitive>(this._arrayMap.Count, EBPrimitive.PrimitiveComparer.Instance);
int num = 1;
foreach (EBPrimitive current in this._arrayMap.Keys)
{
dictionary[num] = current;
num++;
}
return EBPrimitive.ConvertFromMap(dictionary);
}
public EBPrimitive GetItemCount()
{
this.ConstructArrayMap();
return this._arrayMap.Count;
}
public EBPrimitive Subtract(EBPrimitive addend)
{
return new EBPrimitive(this.GetAsDecimal() - addend.GetAsDecimal());
}
public EBPrimitive Multiply(EBPrimitive multiplicand)
{
return new EBPrimitive(this.GetAsDecimal() * multiplicand.GetAsDecimal());
}
public EBPrimitive Divide(EBPrimitive divisor)
{
divisor.GetAsDecimal();
return new EBPrimitive(this.GetAsDecimal() / divisor.GetAsDecimal());
}
public bool LessThan(EBPrimitive comparer)
{
return this.GetAsDecimal() < comparer.GetAsDecimal();
}
public bool GreaterThan(EBPrimitive comparer)
{
return this.GetAsDecimal() > comparer.GetAsDecimal();
}
public bool LessThanOrEqualTo(EBPrimitive comparer)
{
return this.GetAsDecimal() <= comparer.GetAsDecimal();
}
public bool GreaterThanOrEqualTo(EBPrimitive comparer)
{
return this.GetAsDecimal() >= comparer.GetAsDecimal();
}
public bool EqualTo(EBPrimitive comparer)
{
return this.Equals(comparer);
}
public bool NotEqualTo(EBPrimitive comparer)
{
return !this.Equals(comparer);
}
public override bool Equals(object obj)
{
if (this.AsString == null)
{
this._primitive = "";
}
if (!(obj is EBPrimitive))
{
return false;
}
EBPrimitive EBPrimitive = (EBPrimitive)obj;
if (EBPrimitive.AsString != null && EBPrimitive.AsString.ToLower(CultureInfo.InvariantCulture) == "true" && this.AsString != null && this.AsString.ToLower(CultureInfo.InvariantCulture) == "true")
{
return true;
}
if (this.IsNumber && EBPrimitive.IsNumber)
{
return this.GetAsDecimal() == EBPrimitive.GetAsDecimal();
}
return this.AsString == EBPrimitive.AsString;
}
public override int GetHashCode()
{
if (this.AsString == null)
{
this._primitive = "";
}
return this.AsString.ToUpper(CultureInfo.InvariantCulture).GetHashCode();
}
public override string ToString()
{
return this.AsString;
}
private void ConstructArrayMap()
{
if (this._arrayMap != null)
{
return;
}
this._arrayMap = new Dictionary<EBPrimitive, EBPrimitive>(EBPrimitive.PrimitiveComparer.Instance);
if (this.IsEmpty)
{
return;
}
char[] source = this.AsString.ToCharArray();
int num = 0;
while (true)
{
string value = EBPrimitive.Unescape(source, ref num);
if (string.IsNullOrEmpty(value))
{
break;
}
string text = EBPrimitive.Unescape(source, ref num);
if (text == null)
{
return;
}
this._arrayMap[value] = text;
}
}
internal decimal? TryGetAsDecimal()
{
if (this.IsEmpty)
{
return null;
}
if (this._primitiveAsDecimal.HasValue)
{
return this._primitiveAsDecimal;
}
decimal value = 0m;
if (decimal.TryParse(this.AsString, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
this._primitiveAsDecimal = new decimal?(value);
}
return this._primitiveAsDecimal;
}
internal decimal GetAsDecimal()
{
if (this.IsEmpty)
{
return 0m;
}
if (this._primitiveAsDecimal.HasValue)
{
return this._primitiveAsDecimal.Value;
}
decimal num = 0m;
if (decimal.TryParse(this.AsString, NumberStyles.Float, CultureInfo.InvariantCulture, out num))
{
this._primitiveAsDecimal = new decimal?(num);
}
return num;
}
public static bool ConvertToBoolean(EBPrimitive EBPrimitive)
{
return EBPrimitive;
}
public static implicit operator string(EBPrimitive EBPrimitive)
{
if (EBPrimitive.AsString == null)
{
return "";
}
return EBPrimitive.AsString;
}
public static implicit operator int(EBPrimitive EBPrimitive)
{
return (int)EBPrimitive.GetAsDecimal();
}
public static implicit operator float(EBPrimitive EBPrimitive)
{
return (float)EBPrimitive.GetAsDecimal();
}
public static implicit operator double(EBPrimitive EBPrimitive)
{
return (double)EBPrimitive.GetAsDecimal();
}
public static implicit operator bool(EBPrimitive EBPrimitive)
{
return EBPrimitive.AsString != null && EBPrimitive.AsString.Equals("true", StringComparison.InvariantCultureIgnoreCase);
}
public static EBPrimitive operator ==(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.Equals(primitive2);
}
public static EBPrimitive operator !=(EBPrimitive primitive1, EBPrimitive primitive2)
{
return !primitive1.Equals(primitive2);
}
public static EBPrimitive operator >(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.GreaterThan(primitive2);
}
public static EBPrimitive operator >=(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.GreaterThanOrEqualTo(primitive2);
}
public static EBPrimitive operator <(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.LessThan(primitive2);
}
public static EBPrimitive operator <=(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.LessThanOrEqualTo(primitive2);
}
public static EBPrimitive operator +(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.Add(primitive2);
}
public static EBPrimitive operator -(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.Subtract(primitive2);
}
public static EBPrimitive operator *(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.Multiply(primitive2);
}
public static EBPrimitive operator /(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1.Divide(primitive2);
}
public static EBPrimitive operator -(EBPrimitive EBPrimitive)
{
return -EBPrimitive.GetAsDecimal();
}
public static EBPrimitive operator |(EBPrimitive primitive1, EBPrimitive primitive2)
{
return EBPrimitive.op_Or(primitive1, primitive2);
}
public static EBPrimitive operator &(EBPrimitive primitive1, EBPrimitive primitive2)
{
return EBPrimitive.op_And(primitive1, primitive2);
}
public static bool operator true(EBPrimitive EBPrimitive)
{
return EBPrimitive;
}
public static bool operator false(EBPrimitive EBPrimitive)
{
return !EBPrimitive;
}
public static EBPrimitive op_And(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1 && primitive2;
}
public static EBPrimitive op_Or(EBPrimitive primitive1, EBPrimitive primitive2)
{
return primitive1 || primitive2;
}
public static implicit operator EBPrimitive(int value)
{
return new EBPrimitive(value);
}
public static implicit operator EBPrimitive(bool value)
{
return new EBPrimitive(value);
}
public static implicit operator EBPrimitive(string value)
{
if (value == null)
{
return new EBPrimitive("");
}
return new EBPrimitive(value);
}
public static implicit operator EBPrimitive(double value)
{
return new EBPrimitive((decimal)value);
}
public static implicit operator EBPrimitive(decimal value)
{
return new EBPrimitive(value);
}
public static implicit operator EBPrimitive(DateTime value)
{
return new EBPrimitive(value);
}
public static EBPrimitive GetArrayValue(EBPrimitive array, EBPrimitive indexer)
{
array.ConstructArrayMap();
EBPrimitive result;
if (!array._arrayMap.TryGetValue(indexer, out result))
{
result = default(EBPrimitive);
}
return result;
}
public static EBPrimitive SetArrayValue(EBPrimitive value, EBPrimitive array, EBPrimitive indexer)
{
array.ConstructArrayMap();
Dictionary<EBPrimitive, EBPrimitive> dictionary = new Dictionary<EBPrimitive, EBPrimitive>(array._arrayMap, EBPrimitive.PrimitiveComparer.Instance);
if (value.IsEmpty)
{
dictionary.Remove(indexer);
}
else
{
dictionary[indexer] = value;
}
return EBPrimitive.ConvertFromMap(dictionary);
}
public static EBPrimitive ConvertFromMap(Dictionary<EBPrimitive, EBPrimitive> map)
{
return new EBPrimitive
{
_primitive = null,
_primitiveAsDecimal = null,
_arrayMap = map
};
}
private static string Escape(string value)
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
if (c == '=')
{
stringBuilder.Append("\\=");
}
else if (c == ';')
{
stringBuilder.Append("\\;");
}
else if (c == '\\')
{
stringBuilder.Append("\\\\");
}
else
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString();
}
private static string Unescape(char[] source, ref int index)
{
bool flag = false;
bool flag2 = true;
int num = source.Length;
StringBuilder stringBuilder = new StringBuilder();
while (index < num)
{
char c = source[index];
index++;
if (!flag)
{
if (c == '\\')
{
flag = true;
continue;
}
if (c == '=')
{
break;
}
if (c == ';')
{
break;
}
}
else
{
flag = false;
}
flag2 = false;
stringBuilder.Append(c);
}
if (flag2)
{
return null;
}
return stringBuilder.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsSubscriptionIdApiVersion
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class MicrosoftAzureTestUrl : Microsoft.Rest.ServiceClient<MicrosoftAzureTestUrl>, IMicrosoftAzureTestUrl, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// API Version with value '2014-04-01-preview'.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IGroupOperations.
/// </summary>
public virtual IGroupOperations Group { get; private set; }
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MicrosoftAzureTestUrl(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MicrosoftAzureTestUrl(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MicrosoftAzureTestUrl(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MicrosoftAzureTestUrl(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Group = new GroupOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com/");
this.ApiVersion = "2014-04-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Threading;
namespace System.Management
{
/// <summary>
/// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementOperationObserver.ObjectReady'/> event.</para>
/// </summary>
public delegate void ObjectReadyEventHandler(object sender, ObjectReadyEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementOperationObserver.Completed'/> event.</para>
/// </summary>
public delegate void CompletedEventHandler (object sender, CompletedEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementOperationObserver.Progress'/> event.</para>
/// </summary>
public delegate void ProgressEventHandler (object sender, ProgressEventArgs e);
/// <summary>
/// <para>Represents the method that will handle the <see cref='E:System.Management.ManagementOperationObserver.ObjectPut'/> event.</para>
/// </summary>
public delegate void ObjectPutEventHandler(object sender, ObjectPutEventArgs e);
/// <summary>
/// <para>Used to manage asynchronous operations and handle management information and events received asynchronously.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This sample demonstrates how to read a ManagementObject asychronously
/// // using the ManagementOperationObserver object.
///
/// class Sample_ManagementOperationObserver {
/// public static int Main(string[] args) {
///
/// //Set up a handler for the asynchronous callback
/// ManagementOperationObserver observer = new ManagementOperationObserver();
/// MyHandler completionHandler = new MyHandler();
/// observer.Completed += new CompletedEventHandler(completionHandler.Done);
///
/// //Invoke the asynchronous read of the object
/// ManagementObject disk = new ManagementObject("Win32_logicaldisk='C:'");
/// disk.Get(observer);
///
/// //For the purpose of this sample, we keep the main
/// // thread alive until the asynchronous operation is completed.
///
/// while (!completionHandler.IsComplete) {
/// System.Threading.Thread.Sleep(500);
/// }
///
/// Console.WriteLine("Size= " + disk["Size"] + " bytes.");
///
/// return 0;
/// }
///
/// public class MyHandler
/// {
/// private bool isComplete = false;
///
/// public void Done(object sender, CompletedEventArgs e) {
/// isComplete = true;
/// }
///
/// public bool IsComplete {
/// get {
/// return isComplete;
/// }
/// }
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This sample demonstrates how to read a ManagementObject asychronously
/// ' using the ManagementOperationObserver object.
///
/// Class Sample_ManagementOperationObserver
/// Overloads Public Shared Function Main(args() As String) As Integer
///
/// 'Set up a handler for the asynchronous callback
/// Dim observer As New ManagementOperationObserver()
/// Dim completionHandler As New MyHandler()
/// AddHandler observer.Completed, AddressOf completionHandler.Done
///
/// ' Invoke the object read asynchronously
/// Dim disk As New ManagementObject("Win32_logicaldisk='C:'")
/// disk.Get(observer)
///
/// ' For the purpose of this sample, we keep the main
/// ' thread alive until the asynchronous operation is finished.
/// While Not completionHandler.IsComplete Then
/// System.Threading.Thread.Sleep(500)
/// End While
///
/// Console.WriteLine("Size = " + disk("Size").ToString() & " bytes")
///
/// Return 0
/// End Function
///
/// Public Class MyHandler
/// Private _isComplete As Boolean = False
///
/// Public Sub Done(sender As Object, e As CompletedEventArgs)
/// _isComplete = True
/// End Sub 'Done
///
/// Public ReadOnly Property IsComplete() As Boolean
/// Get
/// Return _isComplete
/// End Get
/// End Property
/// End Class
/// End Class
/// </code>
/// </example>
public class ManagementOperationObserver
{
private Hashtable m_sinkCollection;
private WmiDelegateInvoker delegateInvoker;
/// <summary>
/// <para> Occurs when a new object is available.</para>
/// </summary>
public event ObjectReadyEventHandler ObjectReady;
/// <summary>
/// <para> Occurs when an operation has completed.</para>
/// </summary>
public event CompletedEventHandler Completed;
/// <summary>
/// <para> Occurs to indicate the progress of an ongoing operation.</para>
/// </summary>
public event ProgressEventHandler Progress;
/// <summary>
/// <para> Occurs when an object has been successfully committed.</para>
/// </summary>
public event ObjectPutEventHandler ObjectPut;
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.Management.ManagementOperationObserver'/> class. This is the default constructor.</para>
/// </summary>
public ManagementOperationObserver ()
{
// We make our sink collection synchronized
m_sinkCollection = new Hashtable ();
delegateInvoker = new WmiDelegateInvoker (this);
}
/// <summary>
/// <para> Cancels all outstanding operations.</para>
/// </summary>
public void Cancel ()
{
// Cancel all the sinks we have - make a copy to avoid things
// changing under our feet
Hashtable copiedSinkTable = new Hashtable ();
lock (m_sinkCollection)
{
IDictionaryEnumerator sinkEnum = m_sinkCollection.GetEnumerator();
try
{
sinkEnum.Reset ();
while (sinkEnum.MoveNext ())
{
DictionaryEntry entry = (DictionaryEntry) sinkEnum.Current;
copiedSinkTable.Add (entry.Key, entry.Value);
}
}
catch
{
}
}
// Now step through the copy and cancel everything
try
{
IDictionaryEnumerator copiedSinkEnum = copiedSinkTable.GetEnumerator();
copiedSinkEnum.Reset ();
while (copiedSinkEnum.MoveNext ())
{
DictionaryEntry entry = (DictionaryEntry) copiedSinkEnum.Current;
WmiEventSink eventSink = (WmiEventSink) entry.Value;
try
{
eventSink.Cancel ();
}
catch
{
}
}
}
catch
{
}
}
internal WmiEventSink GetNewSink (
ManagementScope scope,
object context)
{
try
{
WmiEventSink eventSink = WmiEventSink.GetWmiEventSink(this, context, scope, null, null);
// Add it to our collection
lock (m_sinkCollection)
{
m_sinkCollection.Add (eventSink.GetHashCode(), eventSink);
}
return eventSink;
}
catch
{
return null;
}
}
internal bool HaveListenersForProgress
{
get
{
bool result = false;
try
{
if (Progress != null)
result = ((Progress.GetInvocationList ()).Length > 0);
}
catch
{
}
return result;
}
}
internal WmiEventSink GetNewPutSink (
ManagementScope scope,
object context,
string path,
string className)
{
try
{
WmiEventSink eventSink = WmiEventSink.GetWmiEventSink(this, context, scope, path, className);
// Add it to our collection
lock (m_sinkCollection)
{
m_sinkCollection.Add (eventSink.GetHashCode(), eventSink);
}
return eventSink;
}
catch
{
return null;
}
}
internal WmiGetEventSink GetNewGetSink (
ManagementScope scope,
object context,
ManagementObject managementObject)
{
try
{
WmiGetEventSink eventSink = WmiGetEventSink.GetWmiGetEventSink(this,
context, scope, managementObject);
// Add it to our collection
lock (m_sinkCollection)
{
m_sinkCollection.Add (eventSink.GetHashCode(), eventSink);
}
return eventSink;
}
catch
{
return null;
}
}
internal void RemoveSink (WmiEventSink eventSink)
{
try
{
lock (m_sinkCollection)
{
m_sinkCollection.Remove (eventSink.GetHashCode ());
}
// Release the stub as we are now disconnected
eventSink.ReleaseStub ();
}
catch
{
}
}
/// <summary>
/// Fires the ObjectReady event to whomsoever is listening
/// </summary>
/// <param name="args"> </param>
internal void FireObjectReady (ObjectReadyEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates (ObjectReady, args);
}
catch
{
}
}
internal void FireCompleted (CompletedEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates (Completed, args);
}
catch
{
}
}
internal void FireProgress (ProgressEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates (Progress, args);
}
catch
{
}
}
internal void FireObjectPut (ObjectPutEventArgs args)
{
try
{
delegateInvoker.FireEventToDelegates (ObjectPut, args);
}
catch
{
}
}
}
internal class WmiEventState
{
private Delegate d;
private ManagementEventArgs args;
private AutoResetEvent h;
internal WmiEventState (Delegate d, ManagementEventArgs args, AutoResetEvent h)
{
this.d = d;
this.args = args;
this.h = h;
}
public Delegate Delegate
{
get { return d; }
}
public ManagementEventArgs Args
{
get { return args; }
}
public AutoResetEvent AutoResetEvent
{
get { return h; }
}
}
/// <summary>
/// This class handles the posting of events to delegates. For each event
/// it queues a set of requests (one per target delegate) to the thread pool
/// to handle the event. It ensures that no single delegate can throw
/// an exception that prevents the event from reaching any other delegates.
/// It also ensures that the sender does not signal the processing of the
/// WMI event as "done" until all target delegates have signalled that they are
/// done.
/// </summary>
internal class WmiDelegateInvoker
{
internal object sender;
internal WmiDelegateInvoker (object sender)
{
this.sender = sender;
}
/// <summary>
/// Custom handler for firing a WMI event to a list of delegates. We use
/// the process thread pool to handle the firing.
/// </summary>
/// <param name="md">The MulticastDelegate representing the collection
/// of targets for the event</param>
/// <param name="args">The accompanying event arguments</param>
internal void FireEventToDelegates (MulticastDelegate md, ManagementEventArgs args)
{
try
{
if (null != md)
{
foreach (Delegate d in md.GetInvocationList())
{
try
{
d.DynamicInvoke (new object [] {this.sender, args});
}
catch
{
}
}
}
}
catch
{
}
}
}
}
| |
// --------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International.
// <copyright from='2003' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// File: ScrPassageControlTest.cs
// --------------------------------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Forms;
using NUnit.Framework;
using SIL.Scripture;
using SIL.Scripture.Tests;
namespace SIL.Windows.Forms.Scripture.Tests
{
#region Dummy test classes for accessing protected properties/methods
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Dummy test class for testing <see cref="ScrPassageControl"/>
/// </summary>
/// ----------------------------------------------------------------------------------------
internal class DummyScrPassageControl: ScrPassageControl
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Create a new <see cref="ScrPassageDropDown"/> object
/// </summary>
/// <param name="owner">The owner</param>
/// <returns>A new object</returns>
/// <remarks>Added this method to allow test class create it's own derived control
/// </remarks>
/// ------------------------------------------------------------------------------------
protected override ScrPassageDropDown CreateScrPassageDropDown(ScrPassageControl owner)
{
return new DummyScrPassageDropDown(owner, m_versification);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Simulates sending a keypress to the text box portion of the control.
/// </summary>
/// <param name="e"></param>
/// ------------------------------------------------------------------------------------
public void PerformKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
txtScrRef_KeyPress(null, new KeyPressEventArgs('\r'));
else
txtScrRef_KeyDown(null, e);
}
#region Properties
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the textbox for the scripture reference
/// </summary>
/// ------------------------------------------------------------------------------------
internal TextBox ReferenceTextBox
{
get { return txtScrRef; }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Simulate a mouse down on the DropDown button
/// </summary>
/// ------------------------------------------------------------------------------------
internal void SimulateDropDownButtonClick()
{
btnScrPsgDropDown_MouseDown(null, new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the drop-down button portion of the control.
/// </summary>
/// ------------------------------------------------------------------------------------
internal Control DropDownButton
{
get {return btnScrPsgDropDown;}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the <see cref="ScrPassageDropDown"/>
/// </summary>
/// ------------------------------------------------------------------------------------
internal DummyScrPassageDropDown DropDownWindow
{
get {return (DummyScrPassageDropDown)m_dropdownForm;}
}
#endregion
#region DummyScrPassageDropDown
/// ------------------------------------------------------------------------------------
/// <summary>
/// Dummy test class for testing <see cref="ScrPassageDropDown"/>
/// </summary>
/// ------------------------------------------------------------------------------------
internal class DummyScrPassageDropDown : ScrPassageDropDown
{
/// --------------------------------------------------------------------------------
/// <summary>
/// Initializes a new object
/// </summary>
/// <param name="owner">The owner.</param>
/// <param name="versification">The current versification to use when creating
/// instances of BCVRef</param>
/// --------------------------------------------------------------------------------
public DummyScrPassageDropDown(ScrPassageControl owner, IScrVers versification) :
base(owner, false, versification)
{
}
/// --------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="e"></param>
/// --------------------------------------------------------------------------------
internal void PerformKeyDown(KeyEventArgs e)
{
OnKeyDown(e);
}
/// --------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="e"></param>
/// --------------------------------------------------------------------------------
protected override void OnDeactivate(EventArgs e)
{
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Sets the current button whose BCVValue property is the same as that specified.
/// </summary>
/// <param name="bcv">The Book, Chapter, or Verse of the button to make current.
/// </param>
/// ---------------------------------------------------------------------------------
internal void SetCurrentButton(short bcv)
{
foreach (ScrDropDownButton button in m_buttons)
{
if (button.BCVValue == bcv)
{
m_currButton = button.Index;
break;
}
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Gets the number of LabelButtons in the drop-down's control collection.
/// </summary>
/// ---------------------------------------------------------------------------------
internal int ButtonsShowing
{
get
{
int count = 0;
foreach (Control ctrl in this.Controls)
{
if (ctrl is LabelButton)
count++;
}
return count;
}
}
/// --------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether the window will be activated when it is shown.
/// </summary>
/// <value></value>
/// <returns>Always <c>true</c>.</returns>
/// --------------------------------------------------------------------------------
protected override bool ShowWithoutActivation
{
get { return true; }
}
}
#endregion
}
#endregion
/// <summary>
/// Tests the Scripture Passage Control
/// </summary>
[TestFixture]
[SuppressMessage("Gendarme.Rules.Design", "TypesWithDisposableFieldsShouldBeDisposableRule",
Justification="Unit test - m_ctrlOwner gets disposed in TestTearDown(), m_scp and " +
"m_filteredScp get added to m_ctrlOwner.Controls collection")]
public class ScrPassageControlTest
{
private Form m_ctrlOwner;
private DummyScrPassageControl m_scp;
private DummyScrPassageControl m_filteredScp;
private IScrVers m_versification;
#region Setup methods
/// ------------------------------------------------------------------------------------
[SetUp]
public void TestSetup()
{
m_versification = new TestScrVers();
m_ctrlOwner = new Form();
m_scp = new DummyScrPassageControl();
m_scp.Initialize(new BCVRef(01001001), m_versification);
m_filteredScp = new DummyScrPassageControl();
m_filteredScp.Initialize(new BCVRef(01001001), m_versification, new[] { 57, 59, 65 });
m_ctrlOwner.Controls.Add(m_scp);
m_ctrlOwner.Controls.Add(m_filteredScp);
m_ctrlOwner.CreateControl();
if (m_scp.DropDownWindow != null)
m_scp.DropDownWindow.Close();
if (m_filteredScp.DropDownWindow != null)
m_filteredScp.DropDownWindow.Close();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// End of a test
/// </summary>
/// ------------------------------------------------------------------------------------
[TearDown]
public void TestTearDown()
{
#if !__MonoCS__
// m_dbScp.SimulateDropDownButtonClick(); can cause this form to hang on close on mono.
m_ctrlOwner.Close();
#endif
m_ctrlOwner.Dispose();
}
#endregion
#region Test methods
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test parsing textual references and getting the text after setting references
/// programmatically
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ValidateReferenceText()
{
m_scp.Reference = "Gen 1:10";
Assert.IsTrue(m_scp.Valid);
m_scp.Reference = "Gen 1:31";
Assert.IsTrue(m_scp.Valid);
m_scp.Reference = "Gen 1:0";
Assert.IsTrue(m_scp.Valid);
// set to James 3:5
m_scp.ScReference = new BCVRef(59, 3, 5);
Assert.AreEqual("JAS 3:5", m_scp.ReferenceTextBox.Text);
// Set to Exodus 8:20
m_scp.ScReference = new BCVRef(2, 8, 20);
Assert.AreEqual("EXO 8:20", m_scp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test that the drop-down window opens and closes properly
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ScrPassageDropDownBehaviorTests()
{
if (m_scp.DropDownWindow != null)
m_scp.DropDownWindow.Close();
Assert.IsNull(m_scp.DropDownWindow);
m_scp.SimulateDropDownButtonClick();
Assert.IsTrue(m_scp.DropDownWindow.Visible);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Escape));
Assert.IsNull(m_scp.DropDownWindow);
// Verify that Alt-Down shows the list.
m_scp.PerformKeyDown(new KeyEventArgs(Keys.Down | Keys.Alt));
Assert.IsNotNull(m_scp.DropDownWindow);
Assert.IsTrue(m_scp.DropDownWindow.Visible);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test parsing textual reference typed into control
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void SettingReferenceByTypingTextTest()
{
m_scp.ReferenceTextBox.Text = "GEN 2:5";
m_scp.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual(1, m_scp.ScReference.Book);
Assert.AreEqual(2, m_scp.ScReference.Chapter);
Assert.AreEqual(5, m_scp.ScReference.Verse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test that the reference gets resolved properly when pressing enter when the
/// text box has focus.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ResolveReferenceOnEnter()
{
m_scp.ReferenceTextBox.Focus();
m_scp.ReferenceTextBox.Text = "gen";
m_scp.PerformKeyDown(new KeyEventArgs(Keys.Return));
Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Resolves an incomplete reference when the user types "j" (Joshua is the first book
/// that starts with "j")
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ResolveReference_IncompleteMultilingScrBooks()
{
m_scp.ReferenceTextBox.Focus();
m_scp.ReferenceTextBox.Text = "j";
m_scp.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("JOS 1:1", m_scp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Resolves an incomplete reference for James when the user types "j" with
/// DBMultilingScrBooks. It is not Joshua, Judges, Job, Jeremiah, Joel, etc because these
/// books are not in the list.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ResolveReference_IncompleteInFilteredList()
{
m_filteredScp.ReferenceTextBox.Focus();
m_filteredScp.ReferenceTextBox.Text = "j";
m_filteredScp.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("JAS 1:1", m_filteredScp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test resolving an incomplete reference when the user types "q". Since no book begins
/// with "q", it should return the first book in our project, which is Philemon.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ResolveReference_InvalidBook()
{
m_filteredScp.ReferenceTextBox.Focus();
m_filteredScp.ReferenceTextBox.Text = "q";
m_filteredScp.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("PHM 1:1", m_filteredScp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Attempts to resolve an incomplete reference when the user types "p" in the filtered
/// control. Even though there are books in the Bible that begin with "p", since no
/// books in the filtered list do, the first book in the list should be returned.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ResolveReference_IncompleteNotInProject()
{
m_filteredScp.ReferenceTextBox.Focus();
m_filteredScp.ReferenceTextBox.Text = "p";
m_filteredScp.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("PHM 1:1", m_filteredScp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test that the reference gets resolved properly when the text box loses focus.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ResolveReferenceOnLoseFocus()
{
m_ctrlOwner.Visible = true;
m_scp.ReferenceTextBox.Focus();
m_scp.ReferenceTextBox.Text = "rev";
m_scp.DropDownButton.Focus();
Assert.AreEqual("REV 1:1", m_scp.ReferenceTextBox.Text);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test that the text portion is all selected when the text box gains focus.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void TextAllSelectedOnFocus()
{
m_ctrlOwner.Visible = true;
m_scp.DropDownButton.Focus();
m_scp.ReferenceTextBox.Text = "REV 1:1";
m_scp.ReferenceTextBox.Focus();
Assert.AreEqual(0, m_scp.ReferenceTextBox.SelectionStart);
Assert.AreEqual(7, m_scp.ReferenceTextBox.SelectionLength);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests that all the books that are in the database are shown in the drop down list.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void VerifyBookCountForFilteredList()
{
m_filteredScp.SimulateDropDownButtonClick();
Assert.AreEqual(3, m_filteredScp.DropDownWindow.ButtonsShowing, "Incorrect number of books showing");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests that all the books that are in the database are shown in the drop down list.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void FilteredListHasBooksInCanonicalOrder()
{
m_filteredScp.Initialize(new BCVRef(3, 3, 3), m_versification, new [] {4, 5, 3, 2});
Assert.AreEqual(4, m_filteredScp.BookLabels.Length);
Assert.AreEqual(2, m_filteredScp.BookLabels[0].BookNum);
Assert.AreEqual(3, m_filteredScp.BookLabels[1].BookNum);
Assert.AreEqual(4, m_filteredScp.BookLabels[2].BookNum);
Assert.AreEqual(5, m_filteredScp.BookLabels[3].BookNum);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests that all the books that are in the database are shown in the drop down list.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void FilteredListPreventsDuplicateBooks()
{
m_filteredScp.Initialize(new BCVRef(3, 3, 3), m_versification, new[] { 4, 3, 3, 4 });
Assert.AreEqual(2, m_filteredScp.BookLabels.Length);
Assert.AreEqual(3, m_filteredScp.BookLabels[0].BookNum);
Assert.AreEqual(4, m_filteredScp.BookLabels[1].BookNum);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests populating drop down control - this doesn't work well on build machine, so
/// test has been marked as being "ByHand".
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
[Category("ByHand")]
public void VerifyDropDownContentWithInvalidDefault()
{
// Set control to really invalid reference.
m_scp.Reference = "DAVID 100:100";
m_scp.SimulateDropDownButtonClick();
WaitForDropDownWindow(m_scp, 66);
// Verify Genesis is the current and default book.
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue,
"Incorrect Current Book Button");
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentBook, "Incorrect Current Book");
Assert.AreEqual(ScrPassageDropDown.ListTypes.Books,
m_scp.DropDownWindow.CurrentListType, "Incorrect List is showing");
Assert.AreEqual(66, m_scp.DropDownWindow.ButtonsShowing,
"Incorrect number of books showing");
// Choose Deuteronomy and move to the chapter list.
m_scp.DropDownWindow.SetCurrentButton(5);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
// Verify the contents of the passage control's text box.
Assert.AreEqual("DEU 1:1", m_scp.ReferenceTextBox.Text.ToUpper());
// Verify that chapter 1 is current and default chapter.
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue,
"Incorrect Current Chapter Button");
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentChapter, "Incorrect Current Chapter");
Assert.AreEqual(ScrPassageDropDown.ListTypes.Chapters,
m_scp.DropDownWindow.CurrentListType, "Incorrect List is showing");
// Should be 34 chapters showing
Assert.AreEqual(34, m_scp.DropDownWindow.ButtonsShowing,
"Incorrect number of chapters showing");
// Choose Chapter 17 and move to the verse list.
m_scp.DropDownWindow.SetCurrentButton(17);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
// Verify the contents of the passage control's text box.
Assert.AreEqual("DEU 17:1", m_scp.ReferenceTextBox.Text.ToUpper());
// Verify that verse 1 is current and default verse.
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue,
"Incorrect Current Verse Button");
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentVerse, "Incorrect Current Verse");
Assert.AreEqual(ScrPassageDropDown.ListTypes.Verses,
m_scp.DropDownWindow.CurrentListType, "Incorrect List is showing");
// Should be 20 verses showing
Assert.AreEqual(20, m_scp.DropDownWindow.ButtonsShowing,
"Incorrect number of verses showing");
// Choose verse 13, press enter and verify the drop-down disappears.
m_scp.DropDownWindow.SetCurrentButton(13);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible");
// Verify the contents of the passage control's text box and it's reference object.
Assert.AreEqual("DEU 17:13", m_scp.ReferenceTextBox.Text.ToUpper());
Assert.AreEqual("DEU 17:13", m_scp.Reference);
Assert.AreEqual("DEU 17:13", m_scp.ScReference.AsString.ToUpper());
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests populating drop down control - this doesn't work well on build machine, so
/// test has been marked as being "ByHand".
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
[Category("ByHand")]
public void VerifyEscapeBehavior()
{
// Set control to really invalid reference.
m_scp.Reference = "DAVID 100:100";
m_scp.SimulateDropDownButtonClick();
WaitForDropDownWindow(m_scp, 66);
// Move to chapter list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper());
// Move to verse list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper());
// Escape from the drop-down and verify that the drop-down goes away.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Escape));
Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests populating drop down control - this doesn't work well on build machine, so
/// test has been marked as being "ByHand".
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
[Category("ByHand")]
public void VerifyClickingOutsideDropdownBehavior()
{
// Set control to really invalid reference.
m_scp.Reference = "DAVID 100:100";
m_scp.SimulateDropDownButtonClick();
WaitForDropDownWindow(m_scp, 66);
// Move to chapter list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper());
// Move to verse list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper());
// Close the drop-down and verify the control's text box has the reference that
// was selected so far.
m_scp.DropDownWindow.Close();
Assert.AreEqual("GEN 1:1", m_scp.ReferenceTextBox.Text.ToUpper());
Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests selecting books, chapters, and verses using the keyboard in the drop down
/// control - this doesn't work well on build machine, so test has been marked as being
/// "ByHand".
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
[Category("ByHand")]
public void VerifyKeyboardAcceleratorDropdownBehavior()
{
// Set control to really invalid reference.
m_scp.Reference = "DAVID 100:100";
m_scp.SimulateDropDownButtonClick();
WaitForDropDownWindow(m_scp, 66);
// Select a book using the keyboard.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Q));
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J));
Assert.AreEqual(6, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J));
Assert.AreEqual(7, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.U));
Assert.AreEqual(7, m_scp.DropDownWindow.CurrentButtonValue);
// Move to chapter list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue);
// Select a chapter using the keyboard.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D0));
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1));
Assert.AreEqual(10, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1));
Assert.AreEqual(11, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1));
Assert.AreEqual(12, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D2));
Assert.AreEqual(20, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D2));
Assert.AreEqual(21, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Q));
Assert.AreEqual(21, m_scp.DropDownWindow.CurrentButtonValue);
// Move to verse list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue);
// Select a verse using the keyboard.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D3));
Assert.AreEqual(3, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D3));
Assert.AreEqual(3, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1));
Assert.AreEqual(10, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1));
Assert.AreEqual(11, m_scp.DropDownWindow.CurrentButtonValue);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests selecting books, chapters, and verses using the keyboard in the drop down
/// control - this doesn't work well on build machine, so test has been marked as being
/// "ByHand".
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
[Ignore("Not sure that it's really desirable to have the selected book and chapter be" +
" retained if the user cancels or clicks away. Anyway, it doesn't actually behave that way now.")]
public void VerifyreferenceIsRetainedWhenDropdownCloses()
{
// Set control to really invalid reference.
m_scp.Reference = "DAVID 100:100";
m_scp.SimulateDropDownButtonClick();
WaitForDropDownWindow(m_scp, 66);
// Select a book using the keyboard.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J));
Assert.AreEqual(6, m_scp.DropDownWindow.CurrentButtonValue);
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.J));
Assert.AreEqual(7, m_scp.DropDownWindow.CurrentButtonValue);
// Move to chapter list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue);
// Select a chapter using the keyboard.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D1));
Assert.AreEqual(10, m_scp.DropDownWindow.CurrentButtonValue);
// Move to verse list and verify content in the passage control's text box.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.Enter));
Assert.AreEqual(1, m_scp.DropDownWindow.CurrentButtonValue);
// Select a verse using the keyboard.
m_scp.DropDownWindow.PerformKeyDown(new KeyEventArgs(Keys.D3));
Assert.AreEqual(3, m_scp.DropDownWindow.CurrentButtonValue);
// Close the drop-down and verify the control's text box has the reference that
// was selected so far.
m_scp.DropDownWindow.Close();
Assert.AreEqual("JDG 10:3", m_scp.ReferenceTextBox.Text.ToUpper());
Assert.IsNull(m_scp.DropDownWindow, "Drop-down should not be visible");
}
#endregion
#region helper methods
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tries the DoEvents a few times to give the DropDownWindow a chance to become active.
/// Tests were occassionally failing due to a null DropDownWindow reference.
/// </summary>
/// ------------------------------------------------------------------------------------
private static void WaitForDropDownWindow(DummyScrPassageControl spc, int expectedCount)
{
int i = 0;
do
{
Application.DoEvents();
if (spc.DropDownWindow != null && spc.DropDownWindow.Menu != null &&
spc.DropDownWindow.Menu.MenuItems.Count == expectedCount)
break;
i++;
}
while (i < 20);
}
#endregion
}
}
| |
namespace Nancy.Routing
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Nancy.Helpers;
using Responses.Negotiation;
/// <summary>
/// Default implementation of a request dispatcher.
/// </summary>
public class DefaultRequestDispatcher : IRequestDispatcher
{
private readonly IRouteResolver routeResolver;
private readonly IEnumerable<IResponseProcessor> responseProcessors;
private readonly IRouteInvoker routeInvoker;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultRequestDispatcher"/> class, with
/// the provided <paramref name="routeResolver"/>, <paramref name="responseProcessors"/> and <paramref name="routeInvoker"/>.
/// </summary>
/// <param name="routeResolver"></param>
/// <param name="responseProcessors"></param>
/// <param name="routeInvoker"></param>
public DefaultRequestDispatcher(IRouteResolver routeResolver, IEnumerable<IResponseProcessor> responseProcessors, IRouteInvoker routeInvoker)
{
this.routeResolver = routeResolver;
this.responseProcessors = responseProcessors;
this.routeInvoker = routeInvoker;
}
/// <summary>
/// Dispatches a requests.
/// </summary>
/// <param name="context">The <see cref="NancyContext"/> for the current request.</param>
public Task<Response> Dispatch(NancyContext context, CancellationToken cancellationToken)
{
// TODO - May need to make this run off context rather than response .. seems a bit icky currently
var tcs = new TaskCompletionSource<Response>();
var resolveResult = this.Resolve(context);
context.Parameters = resolveResult.Parameters;
context.ResolvedRoute = resolveResult.Route;
var preReqTask = ExecuteRoutePreReq(context, cancellationToken, resolveResult.Before);
preReqTask.WhenCompleted(
completedTask =>
{
context.Response = completedTask.Result;
if (context.Response == null)
{
var routeTask = this.routeInvoker.Invoke(resolveResult.Route, cancellationToken, resolveResult.Parameters, context);
routeTask.WhenCompleted(
completedRouteTask =>
{
context.Response = completedRouteTask.Result;
if (context.Request.Method.ToUpperInvariant() == "HEAD")
{
context.Response = new HeadResponse(context.Response);
}
ExecutePost(context, cancellationToken, resolveResult.After, resolveResult.OnError, tcs);
},
HandleFaultedTask(context, resolveResult.OnError, tcs));
return;
}
ExecutePost(context, cancellationToken, resolveResult.After, resolveResult.OnError, tcs);
},
HandleFaultedTask(context, resolveResult.OnError, tcs));
return tcs.Task;
}
private static void ExecutePost(NancyContext context, CancellationToken cancellationToken, AfterPipeline postHook, Func<NancyContext, Exception, Response> onError, TaskCompletionSource<Response> tcs)
{
if (postHook == null)
{
tcs.SetResult(context.Response);
return;
}
postHook.Invoke(context, cancellationToken).WhenCompleted(
completedTask => tcs.SetResult(context.Response),
completedTask => HandlePostHookFaultedTask(context, onError, completedTask, tcs),
false);
}
private static void HandlePostHookFaultedTask(NancyContext context, Func<NancyContext, Exception, Response> onError, Task completedTask, TaskCompletionSource<Response> tcs)
{
var response = ResolveErrorResult(context, onError, completedTask.Exception);
if (response != null)
{
context.Response = response;
tcs.SetResult(response);
}
else
{
tcs.SetException(completedTask.Exception);
}
}
private static Action<Task<Response>> HandleFaultedTask(NancyContext context, Func<NancyContext, Exception, Response> onError, TaskCompletionSource<Response> tcs)
{
return task =>
{
var response = ResolveErrorResult(context, onError, task.Exception);
if (response != null)
{
context.Response = response;
tcs.SetResult(response);
}
else
{
tcs.SetException(task.Exception);
}
};
}
private static Task<Response> ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)
{
if (resolveResultPreReq == null)
{
return TaskHelpers.GetCompletedTask<Response>(null);
}
return resolveResultPreReq.Invoke(context, cancellationToken);
}
private static Response ResolveErrorResult(NancyContext context, Func<NancyContext, Exception, Response> resolveResultOnError, Exception exception)
{
if (resolveResultOnError != null)
{
return resolveResultOnError.Invoke(context, exception);
}
return null;
}
private ResolveResult Resolve(NancyContext context)
{
var extension =
Path.GetExtension(context.Request.Path);
var originalAcceptHeaders = context.Request.Headers.Accept;
var originalRequestPath = context.Request.Path;
if (!string.IsNullOrEmpty(extension))
{
var mappedMediaRanges = this.GetMediaRangesForExtension(extension.Substring(1))
.ToArray();
if (mappedMediaRanges.Any())
{
var newMediaRanges =
mappedMediaRanges.Where(x => !context.Request.Headers.Accept.Any(header => header.Equals(x)));
var modifiedRequestPath =
context.Request.Path.Replace(extension, string.Empty);
var match =
this.InvokeRouteResolver(context, modifiedRequestPath, newMediaRanges);
if (!(match.Route is NotFoundRoute))
{
return match;
}
}
}
return this.InvokeRouteResolver(context, originalRequestPath, originalAcceptHeaders);
}
private IEnumerable<Tuple<string, decimal>> GetMediaRangesForExtension(string extension)
{
return this.responseProcessors
.SelectMany(processor => processor.ExtensionMappings)
.Where(mapping => mapping != null)
.Where(mapping => mapping.Item1.Equals(extension, StringComparison.OrdinalIgnoreCase))
.Select(mapping => new Tuple<string, decimal>(mapping.Item2, Decimal.MaxValue))
.Distinct();
}
private ResolveResult InvokeRouteResolver(NancyContext context, string path, IEnumerable<Tuple<string, decimal>> acceptHeaders)
{
context.Request.Headers.Accept = acceptHeaders.ToList();
context.Request.Url.Path = path;
return this.routeResolver.Resolve(context);
}
}
}
| |
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 EmpMan.Web.Areas.HelpPage.ModelDescriptions;
using EmpMan.Web.Areas.HelpPage.Models;
namespace EmpMan.Web.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);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.Extensions.Logging;
namespace Orleans.CodeGeneration
{
public class Program
{
public static int Main(string[] args)
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
Console.WriteLine("Orleans-CodeGen - command-line = {0}", Environment.CommandLine);
if (args.Length < 1)
{
PrintUsage();
return 1;
}
try
{
var options = new CodeGenOptions();
// STEP 1 : Parse parameters
if (args.Length == 1 && args[0].StartsWith("@"))
{
// Read command line args from file
string arg = args[0];
string argsFile = arg.Trim('"').Substring(1).Trim('"');
Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile);
AssertWellFormed(argsFile);
args = File.ReadAllLines(argsFile);
}
foreach (string a in args)
{
string arg = a.Trim('"').Trim().Trim('"');
if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg)) continue;
if (arg.StartsWith("/"))
{
if (arg.StartsWith("/waitForDebugger"))
{
var i = 0;
while (!Debugger.IsAttached)
{
if (i++ % 50 == 0)
{
Console.WriteLine("Waiting for debugger to attach.");
}
Thread.Sleep(100);
}
}
else if (arg.StartsWith("/reference:") || arg.StartsWith("/r:"))
{
// list of references passed from from project file. separator =';'
string refstr = arg.Substring(arg.IndexOf(':') + 1);
string[] references = refstr.Split(';');
foreach (string rp in references)
{
AssertWellFormed(rp);
options.ReferencedAssemblies.Add(rp);
}
}
else if (arg.StartsWith("/in:"))
{
var infile = arg.Substring(arg.IndexOf(':') + 1);
AssertWellFormed(infile);
options.InputAssembly = new FileInfo(infile);
}
else if (arg.StartsWith("/out:"))
{
var outfile = arg.Substring(arg.IndexOf(':') + 1);
AssertWellFormed(outfile);
options.OutputFileName = outfile;
}
else if (arg.StartsWith("/loglevel:"))
{
var levelString = arg.Substring(arg.IndexOf(':') + 1);
if (!Enum.TryParse(ignoreCase: true, value: levelString, result: out LogLevel level))
{
var validValues = string.Join(", ", Enum.GetNames(typeof(LogLevel)).Select(v => v.ToString()));
Console.WriteLine($"ERROR: \"{levelString}\" is not a valid log level. Valid values are {validValues}");
return 1;
}
options.LogLevel = level;
}
}
else
{
Console.WriteLine($"Invalid argument: {arg}.");
PrintUsage();
return 1;
}
}
// STEP 2 : Validate and calculate unspecified parameters
if (options.InputAssembly == null)
{
Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified.");
return 2;
}
if (String.IsNullOrEmpty(options.OutputFileName))
{
Console.WriteLine("ERROR: Orleans-Codegen - no output filename specified");
return 2;
}
// STEP 3 : Dump useful info for debugging
Console.WriteLine($"Orleans-CodeGen - Options {Environment.NewLine}\tInputLib={options.InputAssembly.FullName}{Environment.NewLine}\tOutputFileName={options.OutputFileName}");
bool referencesOrleans = options.InputAssembly.Name.Equals(CodeGenerator.OrleansAssemblyFileName);
foreach (string assembly in options.ReferencedAssemblies)
{
var fileName = Path.GetFileName(assembly);
Console.WriteLine("\t{0} => {1}", fileName, assembly);
if (fileName != null && fileName.Equals(CodeGenerator.OrleansAssemblyFileName)) referencesOrleans = true;
}
// STEP 5 : Finally call code generation
var stopWatch = Stopwatch.StartNew();
if (referencesOrleans)
{
if (!CodeGenerator.GenerateCode(options))
{
Console.WriteLine("WARNING: Orleans-CodeGen - the input assembly contained no types which required code generation.");
}
}
else
{
Console.WriteLine("ERROR: Orleans-CodeGen - the input assembly does not reference Orleans and therefore code can not be generated.");
return -2;
}
stopWatch.Stop();
Console.WriteLine($"Build time code generation for assembly {options.InputAssembly} took {stopWatch.ElapsedMilliseconds} milliseconds");
// DONE!
return 0;
}
catch (Exception ex)
{
Console.WriteLine("-- Code Generation FAILED -- \n{0}", LogFormatter.PrintException(ex));
return 3;
}
}
private static void PrintUsage()
{
Console.WriteLine("Usage: /in:<grain assembly filename> /out:<fileName for output file> /r:<reference assemblies>");
Console.WriteLine(" @<arguments fileName> - Arguments will be read and processed from this file.");
Console.WriteLine();
Console.WriteLine("Example: /in:MyGrain.dll /out:C:\\OrleansSample\\MyGrain\\obj\\Debug\\MyGrain.orleans.g.cs /r:Orleans.dll;..\\MyInterfaces\\bin\\Debug\\MyInterfaces.dll");
}
private static void AssertWellFormed(string path)
{
CheckPathNotStartWith(path, ":");
CheckPathNotStartWith(path, "\"");
CheckPathNotEndsWith(path, "\"");
CheckPathNotEndsWith(path, "/");
CheckPath(path, p => !string.IsNullOrWhiteSpace(p), "Empty path string");
}
private static void CheckPathNotStartWith(string path, string str)
{
CheckPath(path, p => !p.StartsWith(str), string.Format("Cannot start with '{0}'", str));
}
private static void CheckPathNotEndsWith(string path, string str)
{
CheckPath(
path,
p => !p.EndsWith(str, StringComparison.InvariantCultureIgnoreCase),
string.Format("Cannot end with '{0}'", str));
}
private static void CheckPath(string path, Func<string, bool> condition, string what)
{
if (condition(path)) return;
var errMsg = string.Format("Bad path {0} Reason = {1}", path, what);
Console.WriteLine("CODEGEN-ERROR: " + errMsg);
throw new ArgumentException("FAILED: " + errMsg);
}
private static class LogFormatter
{
/// <summary>
/// Utility function to convert an exception into printable format, including expanding and formatting any nested sub-expressions.
/// </summary>
/// <param name="exception">The exception to be printed.</param>
/// <returns>Formatted string representation of the exception, including expanding and formatting any nested sub-expressions.</returns>
public static string PrintException(Exception exception)
{
return exception == null ? String.Empty : PrintException_Helper(exception, 0, true);
}
private static string PrintException_Helper(Exception exception, int level, bool includeStackTrace)
{
if (exception == null) return String.Empty;
var sb = new StringBuilder();
sb.Append(PrintOneException(exception, level, includeStackTrace));
if (exception is ReflectionTypeLoadException loadException)
{
var loaderExceptions = loadException.LoaderExceptions;
if (loaderExceptions == null || loaderExceptions.Length == 0)
{
sb.Append("No LoaderExceptions found");
}
else
{
foreach (Exception inner in loaderExceptions)
{
// call recursively on all loader exceptions. Same level for all.
sb.Append(PrintException_Helper(inner, level + 1, includeStackTrace));
}
}
}
else if (exception is AggregateException)
{
var innerExceptions = ((AggregateException)exception).InnerExceptions;
if (innerExceptions == null) return sb.ToString();
foreach (Exception inner in innerExceptions)
{
// call recursively on all inner exceptions. Same level for all.
sb.Append(PrintException_Helper(inner, level + 1, includeStackTrace));
}
}
else if (exception.InnerException != null)
{
// call recursively on a single inner exception.
sb.Append(PrintException_Helper(exception.InnerException, level + 1, includeStackTrace));
}
return sb.ToString();
}
private static string PrintOneException(Exception exception, int level, bool includeStackTrace)
{
if (exception == null) return String.Empty;
string stack = String.Empty;
if (includeStackTrace && exception.StackTrace != null)
stack = String.Format(Environment.NewLine + exception.StackTrace);
string message = exception.Message;
return string.Format(Environment.NewLine + "Exc level {0}: {1}: {2}{3}",
level,
exception.GetType(),
message,
stack);
}
}
}
}
| |
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using WootzJs.Compiler.JsAst;
namespace WootzJs.Compiler
{
public class ExpressionTreeTransformer : CSharpSyntaxVisitor<JsExpression>
{
private Idioms idioms;
private SemanticModel model;
private Dictionary<string, string> parameterVariables;
public ExpressionTreeTransformer(SemanticModel model, Idioms idioms)
{
this.model = model;
this.idioms = idioms;
this.parameterVariables = new Dictionary<string, string>();
}
public override JsExpression DefaultVisit(SyntaxNode node)
{
throw new Exception();
}
private IMethodSymbol GetExpressionMethod(string methodName, params ITypeSymbol[] parameterTypes)
{
return Context.Instance.Expression.GetMethod(methodName, parameterTypes);
}
/*
private MemberExpression GetExpressionMethod(string methodName, Type[] parameterTypes)
{
var method = project.FindMethod(typeof(System.Linq.Expressions.Expression).GetMethod(methodName, parameterTypes));
return SkJs.EntityMethodToJsFunctionRef(method);
}
*/
public override JsExpression VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node)
{
return VisitLambdaExpression(node, new[] { node.Parameter }, node.Body);
}
public override JsExpression VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node)
{
return VisitLambdaExpression(node, node.ParameterList.Parameters.ToArray(), node.Body);
}
private JsExpression VisitLambdaExpression(ExpressionSyntax node, ParameterSyntax[] parameters, CSharpSyntaxNode body)
{
var expressionType = (INamedTypeSymbol)model.GetTypeInfo(node).ConvertedType;
INamedTypeSymbol delegateType;
if (Equals(expressionType.OriginalDefinition, Context.Instance.ExpressionGeneric))
delegateType = (INamedTypeSymbol)expressionType.TypeArguments[0];
else
delegateType = expressionType;
var lambdaParameters = parameters.ToArray();
var delegateMethod = (IMethodSymbol)delegateType.GetMembers("Invoke")[0];
// Compiler.CsCompilation.FindType()
var lambdaMethods = Context.Instance.Expression.GetMembers("Lambda").OfType<IMethodSymbol>().ToArray();
var lambdaMethods2 = lambdaMethods.Where(x => x.TypeParameters.Count() == 1 && x.Parameters.Count() == 2 && Equals(x.Parameters[0].Type, Context.Instance.Expression) && Equals(x.Parameters[1].Type, Context.Instance.ParameterExpressionArray)).ToArray();
var lambdaMethod = lambdaMethods2.Single();
var parameterMethod = Context.Instance.Expression.GetMembers("Parameter").OfType<IMethodSymbol>().Single(x => x.Parameters.Count() == 2 && Equals(x.Parameters[0].Type, Context.Instance.TypeType) && Equals(x.Parameters[1].Type, Context.Instance.String));
lambdaMethod = lambdaMethod.Construct(delegateType);
var jsLambda = idioms.InvokeStatic(lambdaMethod);
// Convert parameters
var workspace = new JsBlockStatement();
var jsParameters = Js.Array();
for (var i = 0; i < delegateMethod.Parameters.Count(); i++)
{
var delegateParameter = delegateMethod.Parameters[i];
var lambdaParameter = lambdaParameters[i];
var jsParameter = idioms.InvokeStatic(parameterMethod, idioms.TypeOf(delegateParameter.Type), Js.Primitive(lambdaParameter.Identifier.ToString()));
var parameterVariableName = "$lambdaparam$" + lambdaParameter.Identifier;
parameterVariables[lambdaParameter.Identifier.ToString()] = parameterVariableName;
// Declare a variable to hold the parameter object in the parenthetical's scope
workspace.Local(parameterVariableName, jsParameter);
// Add a reference to this variable (a ParameterExpression) as one of the
// parameters to the lambda.
jsParameters.Elements.Add(Js.Reference(parameterVariableName));
}
var jsBody = body.Accept(this);
jsLambda.AddArgument(jsBody);
jsLambda.AddArgument(jsParameters);
workspace.Return(jsLambda);
return idioms.Wrap(workspace);
}
public override JsExpression VisitIdentifierName(IdentifierNameSyntax node)
{
var key = node.Identifier.ToString();
var symbol = model.GetSymbolInfo(node).Symbol;
if (parameterVariables.ContainsKey(key))
{
return Js.Reference(parameterVariables[key]);
}
else
{
var constantMethod = Context.Instance.Expression.GetMethod("Constant", Context.Instance.ObjectType, Context.Instance.TypeType);
var typeInfo = model.GetTypeInfo(node);
JsExpression keyReference;
if (symbol is ILocalSymbol)
keyReference = Js.Reference(key);
else
keyReference = idioms.MemberReference(Js.This(), symbol);
return idioms.InvokeStatic(constantMethod, keyReference, idioms.TypeOf(typeInfo.ConvertedType));
}
}
public override JsExpression VisitLiteralExpression(LiteralExpressionSyntax node)
{
var constantMethod = Context.Instance.Expression.GetMethod("Constant", Context.Instance.ObjectType, Context.Instance.TypeType);
var typeInfo = model.GetTypeInfo(node);
return idioms.InvokeStatic(constantMethod, Js.Literal(node.Token.Value), idioms.TypeOf(typeInfo.ConvertedType));
}
public override JsExpression VisitBinaryExpression(BinaryExpressionSyntax node)
{
switch (node.Kind())
{
case SyntaxKind.IsExpression:
{
var operand = node.Left.Accept(this);
var type = (INamedTypeSymbol)model.GetSymbolInfo(node.Right).Symbol;
var typeIs = GetExpressionMethod("TypeIs", Context.Instance.Expression, Context.Instance.TypeType);
return idioms.InvokeStatic(typeIs, operand, idioms.TypeOf(type));
}
case SyntaxKind.AsExpression:
{
var operand = node.Left.Accept(this);
var type = (INamedTypeSymbol)model.GetSymbolInfo(node.Right).Symbol;
var typeAs = GetExpressionMethod("TypeAs", Context.Instance.Expression, Context.Instance.TypeType);
return idioms.InvokeStatic(typeAs, operand, idioms.TypeOf(type));
}
}
ExpressionType op;
switch (node.Kind())
{
case SyntaxKind.AddExpression:
op = ExpressionType.Add;
break;
case SyntaxKind.MultiplyExpression:
op = ExpressionType.Multiply;
break;
case SyntaxKind.BitwiseAndExpression:
op = ExpressionType.And;
break;
case SyntaxKind.BitwiseOrExpression:
op = ExpressionType.Or;
break;
case SyntaxKind.DivideExpression:
op = ExpressionType.Divide;
break;
case SyntaxKind.GreaterThanExpression:
op = ExpressionType.GreaterThan;
break;
case SyntaxKind.EqualsExpression:
op = ExpressionType.Equal;
break;
case SyntaxKind.ExclusiveOrExpression:
op = ExpressionType.OrElse;
break;
case SyntaxKind.GreaterThanOrEqualExpression:
op = ExpressionType.GreaterThanOrEqual;
break;
case SyntaxKind.LessThanExpression:
op = ExpressionType.LessThan;
break;
case SyntaxKind.LessThanOrEqualExpression:
op = ExpressionType.LessThanOrEqual;
break;
case SyntaxKind.ModuloExpression:
op = ExpressionType.Modulo;
break;
case SyntaxKind.LeftShiftExpression:
op = ExpressionType.LeftShift;
break;
case SyntaxKind.RightShiftExpression:
op = ExpressionType.RightShift;
break;
case SyntaxKind.SubtractExpression:
op = ExpressionType.Subtract;
break;
case SyntaxKind.CoalesceExpression:
op = ExpressionType.Coalesce;
break;
case SyntaxKind.LogicalAndExpression:
op = ExpressionType.AndAlso;
break;
case SyntaxKind.LogicalOrExpression:
op = ExpressionType.OrElse;
break;
default:
throw new Exception("Unknown operation: " + node.Kind());
}
var left = node.Left.Accept(this);
var right = node.Right.Accept(this);
var jsMethodInfo = GetExpressionMethod("MakeBinary", Context.Instance.ExpressionType, Context.Instance.Expression, Context.Instance.Expression);
var opExpression = idioms.GetEnumValue(Context.Instance.ExpressionType.GetMembers(op.ToString()).OfType<IFieldSymbol>().Single());
var jsMethod = idioms.InvokeStatic(jsMethodInfo, opExpression, left, right);
return jsMethod;
}
public override JsExpression VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
var symbol = model.GetSymbolInfo(node);
var target = node.Expression.Accept(this);
var arguments = node.ArgumentList.Arguments[0].Accept(this);
if (symbol.Symbol is IPropertySymbol)
{
var property = (IPropertySymbol)symbol.Symbol;
var propertyInfo = idioms.MemberOf(property);
var jsMethodInfo = GetExpressionMethod("MakeIndex", Context.Instance.Expression, Context.Instance.PropertyInfo, Context.Instance.EnumerableGeneric.Construct(Context.Instance.Expression));
return idioms.InvokeStatic(jsMethodInfo, target, propertyInfo, Js.Array(node.ArgumentList.Arguments.Select(x => x.Accept(this)).ToArray()));
}
else
{
if (node.ArgumentList.Arguments.Count == 1)
{
var jsMethodInfo = GetExpressionMethod("ArrayIndex", Context.Instance.Expression, Context.Instance.Expression);
return idioms.InvokeStatic(jsMethodInfo, target, node.ArgumentList.Arguments.Single().Accept(this));
}
else
{
var jsMethodInfo = GetExpressionMethod("ArrayIndex", Context.Instance.Expression, Context.Instance.ExpressionArray);
return idioms.InvokeStatic(jsMethodInfo, target, node.ArgumentList.Arguments.Single().Accept(this));
}
}
}
public override JsExpression VisitArgument(ArgumentSyntax node)
{
return node.Expression.Accept(this);
}
public override JsExpression VisitConditionalExpression(ConditionalExpressionSyntax node)
{
var jsMethodInfo = GetExpressionMethod("Condition", Context.Instance.Expression, Context.Instance.Expression, Context.Instance.Expression, Context.Instance.TypeType);
var type = model.GetTypeInfo(node).ConvertedType;
return idioms.InvokeStatic(jsMethodInfo,
node.Condition.Accept(this),
node.WhenTrue.Accept(this),
node.WhenFalse.Accept(this),
idioms.TypeOf(type));
}
public override JsExpression VisitDefaultExpression(DefaultExpressionSyntax node)
{
var type = model.GetTypeInfo(node).ConvertedType;
var jsMethodInfo = GetExpressionMethod("Default", Context.Instance.TypeType);
return idioms.InvokeStatic(jsMethodInfo, idioms.TypeOf(type));
}
public override JsExpression VisitInvocationExpression(InvocationExpressionSyntax node)
{
var symbol = model.GetSymbolInfo(node).Symbol;
var method = (IMethodSymbol)symbol;
if (method.IsStatic)
{
var jsMethodInfo = GetExpressionMethod("Call", Context.Instance.MethodInfo, Context.Instance.ExpressionArray);
var arguments = node.ArgumentList.Arguments.Select(x => x.Accept(this)).ToList();
return idioms.InvokeStatic(jsMethodInfo, idioms.MemberOf(method), Js.Array(arguments.ToArray()));
}
if (method.ContainingType.DelegateInvokeMethod != method)
{
var jsMethodInfo = GetExpressionMethod("Call", Context.Instance.Expression, Context.Instance.MethodInfo, Context.Instance.ExpressionArray);
var methodTarget = ((MemberAccessExpressionSyntax)node.Expression).Expression.Accept(this);
var arguments = node.ArgumentList.Arguments.Select(x => x.Accept(this)).ToArray();
var jsMethod = idioms.InvokeStatic(jsMethodInfo, methodTarget, idioms.MemberOf(method), idioms.MakeArray(Js.Array(arguments), Context.Instance.ExpressionArray));
return jsMethod;
}
else
{
var jsMethodInfo = GetExpressionMethod("Invoke", Context.Instance.Expression, Context.Instance.ExpressionArray);
var target = node.Expression.Accept(this);
var arguments = node.ArgumentList.Arguments.Select(x => x.Accept(this)).ToArray();
return idioms.InvokeStatic(jsMethodInfo, target, idioms.MakeArray(Js.Array(arguments), Context.Instance.ExpressionArray));
}
}
private JsExpression VisitMemberInit(AssignmentExpressionSyntax node)
{
var symbol = model.GetSymbolInfo(node.Left).Symbol;
var member = idioms.MemberOf(symbol);
//System.Linq.Expressions.Expression.Bind(MemberInfo, Expression)
var jsMethodInfo = GetExpressionMethod("Bind", Context.Instance.MemberInfo, Context.Instance.Expression);
return idioms.InvokeStatic(jsMethodInfo, member, node.Right.Accept(this));
}
public override JsExpression VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
var constructor = (IMethodSymbol)model.GetSymbolInfo(node).Symbol;
var jsConstructor = idioms.MemberOf(constructor);
var args = node.ArgumentList == null ? new JsExpression[0] : node.ArgumentList.Arguments.Select(x => x.Accept(this)).ToArray();
var jsMethodInfo = GetExpressionMethod("New", Context.Instance.ConstructorInfo, Context.Instance.ExpressionArray);
var jsMethod = idioms.InvokeStatic(jsMethodInfo, jsConstructor, Js.Array(args));
if (node.Initializer != null && node.Initializer.Expressions.Count > 0)
{
if (node.Initializer.Kind() == SyntaxKind.ObjectInitializerExpression)
{
var memberInit = GetExpressionMethod("MemberInit", Context.Instance.NewExpression, Context.Instance.MemberBindingArray);
var jsMemberInit = idioms.InvokeStatic(
memberInit,
jsMethod,
idioms.Array(Context.Instance.MemberBindingArray, node.Initializer.Expressions.Select(x => VisitMemberInit((AssignmentExpressionSyntax)x)).ToArray()));
return jsMemberInit;
}
else
{
var firstItem = node.Initializer.Expressions.First();
var items = new List<List<ExpressionSyntax>>();
var subitemCount = 1;
if (firstItem is InitializerExpressionSyntax)
{
var initializer = (InitializerExpressionSyntax)firstItem;
items.AddRange(node.Initializer.Expressions.Select(x => ((InitializerExpressionSyntax)x).Expressions.ToList()));
subitemCount = initializer.Expressions.Count;
}
else
{
items.AddRange(node.Initializer.Expressions.Select(x => new List<ExpressionSyntax> { x }));
}
var addMethodInfo = constructor.ContainingType.GetMembers("Add").OfType<IMethodSymbol>().First(x => x.Parameters.Count() == subitemCount);
var addMethod = idioms.MemberOf(addMethodInfo);
var elementInitMethodInfo = GetExpressionMethod("ElementInit", Context.Instance.MethodInfo, Context.Instance.ExpressionArray);
var jsMemberInitMethodInfo = GetExpressionMethod("ListInit", Context.Instance.NewExpression, Context.Instance.ElementInitArray);
var jsMemberInitMethod = idioms.InvokeStatic(
jsMemberInitMethodInfo,
jsMethod,
idioms.MakeArray(Js.Array(items
.Select(x => idioms.InvokeStatic(
elementInitMethodInfo,
addMethod,
idioms.MakeArray(Js.Array(x.Select(y => y.Accept(this)).ToArray()), Context.Instance.ExpressionArray)))
.ToArray()), Context.Instance.ElementInitArray));
return jsMemberInitMethod;
}
}
else
{
return jsMethod;
}
}
public override JsExpression VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
var jsMethodInfo = GetExpressionMethod("MakeMemberAccess");
var symbol = model.GetSymbolInfo(node).Symbol;
var jsMethod = idioms.InvokeStatic(jsMethodInfo,
node.Expression.Accept(this),
idioms.MemberOf(symbol));
return jsMethod;
}
public override JsExpression VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node)
{
var type = (IArrayTypeSymbol)model.GetTypeInfo(node).ConvertedType;
var elementType = type.ElementType;
var newArrayInit = GetExpressionMethod("NewArrayInit", Context.Instance.TypeType, Context.Instance.ExpressionArray);
var jsMethod = idioms.InvokeStatic(
newArrayInit,
idioms.TypeOf(elementType),
idioms.Array(Context.Instance.ExpressionArray, node.Initializer.Expressions.Select(x => x.Accept(this)).ToArray()));
return jsMethod;
}
public override JsExpression VisitArrayCreationExpression(ArrayCreationExpressionSyntax node)
{
var type = (IArrayTypeSymbol)model.GetTypeInfo(node).ConvertedType;
var elementType = type.ElementType;
if (node.Initializer != null)
{
var newArrayInit = GetExpressionMethod("NewArrayInit", Context.Instance.TypeType, Context.Instance.ExpressionArray);
var jsMethod = idioms.InvokeStatic(
newArrayInit,
idioms.TypeOf(elementType),
idioms.Array(Context.Instance.ExpressionArray, node.Initializer.Expressions.Select(x => x.Accept(this)).ToArray()));
return jsMethod;
}
else
{
var jsMethodInfo = GetExpressionMethod("NewArrayBounds", Context.Instance.TypeType, Context.Instance.ExpressionArray);
var jsMethod = idioms.InvokeStatic(
jsMethodInfo,
idioms.TypeOf(elementType),
idioms.Array(Context.Instance.ExpressionArray, node.Type.RankSpecifiers[0].Sizes.Select(x => x.Accept(this)).ToArray()));
return jsMethod;
}
}
public override JsExpression VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node)
{
return VisitUnaryExpression(node, node.Operand);
}
public override JsExpression VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node)
{
return VisitUnaryExpression(node, node.Operand);
}
public JsExpression VisitUnaryExpression(ExpressionSyntax node, ExpressionSyntax expression)
{
ExpressionType op;
switch (node.Kind())
{
case SyntaxKind.LogicalNotExpression:
op = ExpressionType.Not;
break;
case SyntaxKind.UnaryMinusExpression:
op = ExpressionType.Negate;
break;
case SyntaxKind.PostDecrementExpression:
case SyntaxKind.PostIncrementExpression:
throw new Exception("Expression trees cannot contain assignment operators.");
default:
throw new Exception("Unknown operation: " + node.Kind());
}
var makeUnary = GetExpressionMethod("MakeUnary", Context.Instance.ExpressionType, Context.Instance.Expression, Context.Instance.TypeType);
var opExpression = idioms.GetEnumValue(Context.Instance.ExpressionType.GetMembers(op.ToString()).OfType<IFieldSymbol>().Single());
var operand = expression.Accept(this);
var type = model.GetTypeInfo(node).ConvertedType;
return idioms.InvokeStatic(
makeUnary,
opExpression,
operand,
idioms.TypeOf(type));
}
}
}
| |
// 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 Xunit;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
public class ValueTupleTests : ParsingTests
{
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
[Fact]
public void SimpleTuple()
{
var tree = UsingTree(@"
class C
{
(int, string) Foo()
{
return (1, ""Alice"");
}
}", options: TestOptions.Regular);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ReturnStatement);
{
N(SyntaxKind.ReturnKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.StringLiteralExpression);
{
N(SyntaxKind.StringLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void LongTuple()
{
var tree = UsingTree(@"
class C
{
(int, int, int, string, string, string, int, int, int) Foo()
{
}
}", options: TestOptions.Regular);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void TuplesInLambda()
{
var tree = UsingTree(@"
class C
{
var x = ((string, string) a, (int, int) b) => { };
}", options: TestOptions.Regular);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void TuplesWithNamesInLambda()
{
var tree = UsingTree(@"
class C
{
var x = ((string a, string) a, (int, int b) b) => { };
}", options: TestOptions.Regular);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void TupleInParameters()
{
var tree = UsingTree(@"
class C
{
void Foo((int, string) a)
{
}
}", options: TestOptions.Regular);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(13667, "https://github.com/dotnet/roslyn/issues/13667")]
public void MissingShortTupleErrorWhenWarningPresent()
{
// Diff errors
var test = @"
class Program
{
object a = (x: 3l);
}
";
ParseAndValidate(test,
// (4,16): error CS8124: Tuple must contain at least two elements.
// object a = (x: 3l);
Diagnostic(ErrorCode.ERR_TupleTooFewElements, "(x: 3l)").WithLocation(4, 16),
// (4,21): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// object a = (x: 3l);
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 21)
);
}
#region "Helpers"
public static void ParseAndValidate(string text, params DiagnosticDescription[] expectedErrors)
{
var parsedTree = ParseWithRoundTripCheck(text);
var actualErrors = parsedTree.GetDiagnostics();
actualErrors.Verify(expectedErrors);
}
#endregion "Helpers"
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KSP;
using UnityEngine;
using KSPPluginFramework;
namespace DropDownTest
{
[KSPAddon(KSPAddon.Startup.MainMenu, false)]
class DropDownTest : MonoBehaviour
{
void Awake()
{
RenderingManager.AddToPostDrawQueue(0, DrawCall);
//register for the event
ddlTest.SelectionChanged += ddlTestSelectionChanged; ;
}
void OnDestroy()
{
RenderingManager.RemoveFromPostDrawQueue(0, DrawCall);
}
Rect windowRect = new Rect(300, 0, 200, 200);
Boolean StylesSet = false;
void DrawCall()
{
if (!StylesSet)
{
ddlTest.styleListItem = new GUIStyle() { };
ddlTest.styleListItem.normal.textColor = Color.white;
Texture2D texInit = new Texture2D(1, 1);
texInit.SetPixel(0, 0, Color.white);
texInit.Apply();
ddlTest.styleListItem.hover.background = texInit;
ddlTest.styleListItem.onHover.background = texInit;
ddlTest.styleListItem.hover.textColor = Color.black;
ddlTest.styleListItem.onHover.textColor = Color.black;
ddlTest.styleListItem.padding = new RectOffset(4, 4, 4, 4);
ddlTest.styleListBlocker = new GUIStyle();
ddlTest.styleListBox = new GUIStyle(GUI.skin.box);
}
GUI.skin = HighLogic.Skin;
windowRect = GUILayout.Window(50, windowRect, DrawWindow, "Caption");
}
DropDownList ddlTest = new DropDownList(new List<String>() { "Option 1", "Option 2", "Option 3" });
public void ddlTestSelectionChanged(Int32 OldIndex, Int32 NewIndex)
{
ScreenMessages.PostScreenMessage(String.Format("ListChanged {0}->{1}", ddlTest.Items[OldIndex], ddlTest.Items[NewIndex]));
}
void DrawWindow(Int32 id)
{
//this draws the transparent catching button that stops items behind the listbox getting events - and does the actual selection of listitems
ddlTest.DrawBlockingSelector();
//Layout Code here
GUILayout.BeginVertical();
GUILayout.Label("The dropdown should work and obscure the second button");
//This draws the button and displays/hides the listbox - returns true if someone clicked the button
ddlTest.DrawButton();
if (GUILayout.Button("Dont click this through list"))
ScreenMessages.PostScreenMessage("Clicked the Dont Button", 1, ScreenMessageStyle.UPPER_RIGHT);
GUILayout.EndVertical();
//These two go at the end so the dropdown is drawn over the other controls, and closes the dropdown if someone clicks elsewhere in the window
ddlTest.DrawDropDown();
ddlTest.CloseOnOutsideClick();
GUI.DragWindow();
}
void OnGUI()
{
//this one closes the dropdown if you click outside the window elsewhere
ddlTest.CloseOnOutsideClick();
}
}
public class DropDownList
{
//properties to use
internal List<String> Items { get; set; }
internal Int32 SelectedIndex { get; private set; }
internal String SelectedValue { get { return Items[SelectedIndex]; } }
internal Boolean ListVisible;
private Rect rectButton;
private Rect rectListBox;
internal GUIStyle styleListItem;
internal GUIStyle styleListBox;
internal GUIStyle styleListBlocker = new GUIStyle();
internal Int32 ListItemHeight = 20;
//event for changes
public delegate void SelectionChangedEventHandler(Int32 OldIndex, Int32 NewIndex);
public event SelectionChangedEventHandler SelectionChanged;
//Constructors
public DropDownList(List<String> Items)
: this()
{
this.Items = Items;
}
public DropDownList()
{
ListVisible = false;
SelectedIndex = 0;
}
//Draw the button behind everything else to catch the first mouse click
internal void DrawBlockingSelector()
{
//do we need to draw the blocker
if (ListVisible)
{
//This will collect the click event before any other controls under the listrect
if (GUI.Button(rectListBox, "", styleListBlocker))
{
Int32 oldIndex = SelectedIndex;
SelectedIndex = (Int32)Math.Floor((Event.current.mousePosition.y - rectListBox.y) / (rectListBox.height / Items.Count));
//Throw an event or some such from here
SelectionChanged(oldIndex, SelectedIndex);
ListVisible = false;
}
}
}
//Draw the actual button for the list
internal Boolean DrawButton()
{
Boolean blnReturn = false;
//this is the dropdown button - toggle list visible if clicked
if (GUILayout.Button(SelectedValue))
{
ListVisible = !ListVisible;
blnReturn = true;
}
//get the drawn button rectangle
if (Event.current.type == EventType.repaint)
rectButton = GUILayoutUtility.GetLastRect();
//draw a dropdown symbol on the right edge
Rect rectDropIcon = new Rect(rectButton) { x = (rectButton.x + rectButton.width - 20), width = 20 };
GUI.Box(rectDropIcon, "\\/");
return blnReturn;
}
//Draw the hovering dropdown
internal void DrawDropDown()
{
if (ListVisible)
{
//work out the list of items box
rectListBox = new Rect(rectButton)
{
y = rectButton.y + rectButton.height,
height = Items.Count * ListItemHeight
};
//and draw it
GUI.Box(rectListBox, "", styleListBox);
//now draw each listitem
for (int i = 0; i < Items.Count; i++)
{
Rect ListButtonRect = new Rect(rectListBox) { y = rectListBox.y + (i * ListItemHeight), height = 20 };
if (GUI.Button(ListButtonRect, Items[i], styleListItem))
{
ListVisible = false;
SelectedIndex = i;
}
}
//maybe put this here to limit what happens in pre/post calls
//CloseOnOutsideClick();
}
}
internal Boolean CloseOnOutsideClick()
{
if (ListVisible && Event.current.type == EventType.mouseDown && !rectListBox.Contains(Event.current.mousePosition))
{
ListVisible = false;
return true;
}
else { return false; }
}
//internal List<GUIContent> List {get;set;}
//internal void Add(GUIContent NewItem) { List.Add(NewItem); }
//internal void Add(String NewItem) { List.Add(new GUIContent(NewItem)); }
//internal void Add(IEnumerable<String> NewItems) { foreach (String NewItem in NewItems) { List.Add(new GUIContent(NewItem)); } }
//internal void Remove(GUIContent ExistingItem) { if(List.Contains(ExistingItem)) List.Remove(ExistingItem); }
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("New", "AzureRmSnapshotConfig", SupportsShouldProcess = true)]
[OutputType(typeof(Snapshot))]
public class NewAzureRmSnapshotConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
public StorageAccountTypes? AccountType { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public OperatingSystemTypes? OsType { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public int? DiskSizeGB { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public string Location { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public DiskCreateOption? CreateOption { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string StorageAccountId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public ImageDiskReference ImageReference { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string SourceUri { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string SourceResourceId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public bool? EncryptionSettingsEnabled { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public KeyVaultAndSecretReference DiskEncryptionKey { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public KeyVaultAndKeyReference KeyEncryptionKey { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("Snapshot", "New"))
{
Run();
}
}
private void Run()
{
// CreationData
Microsoft.Azure.Management.Compute.Models.CreationData vCreationData = null;
// EncryptionSettings
Microsoft.Azure.Management.Compute.Models.EncryptionSettings vEncryptionSettings = null;
if (this.CreateOption.HasValue)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.CreateOption = this.CreateOption.Value;
}
if (this.StorageAccountId != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.StorageAccountId = this.StorageAccountId;
}
if (this.ImageReference != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.ImageReference = this.ImageReference;
}
if (this.SourceUri != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.SourceUri = this.SourceUri;
}
if (this.SourceResourceId != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.SourceResourceId = this.SourceResourceId;
}
if (this.EncryptionSettingsEnabled != null)
{
if (vEncryptionSettings == null)
{
vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings();
}
vEncryptionSettings.Enabled = this.EncryptionSettingsEnabled;
}
if (this.DiskEncryptionKey != null)
{
if (vEncryptionSettings == null)
{
vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings();
}
vEncryptionSettings.DiskEncryptionKey = this.DiskEncryptionKey;
}
if (this.KeyEncryptionKey != null)
{
if (vEncryptionSettings == null)
{
vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings();
}
vEncryptionSettings.KeyEncryptionKey = this.KeyEncryptionKey;
}
var vSnapshot = new Snapshot
{
AccountType = this.AccountType,
OsType = this.OsType,
DiskSizeGB = this.DiskSizeGB,
Location = this.Location,
Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value),
CreationData = vCreationData,
EncryptionSettings = vEncryptionSettings,
};
WriteObject(vSnapshot);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Streams;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
namespace Orleans.ServiceBus.Providers
{
/// <summary>
/// Queue adapter factory which allows the PersistentStreamProvider to use EventHub as its backend persistent event queue.
/// </summary>
public class EventHubAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache
{
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Data adapter
/// </summary>
protected readonly IEventHubDataAdapter dataAdapter;
/// <summary>
/// Orleans logging
/// </summary>
protected ILogger logger;
/// <summary>
/// Framework service provider
/// </summary>
protected IServiceProvider serviceProvider;
/// <summary>
/// Stream provider settings
/// </summary>
private EventHubOptions ehOptions;
private EventHubStreamCachePressureOptions cacheOptions;
private EventHubReceiverOptions receiverOptions;
private StreamStatisticOptions statisticOptions;
private StreamCacheEvictionOptions cacheEvictionOptions;
private IEventHubQueueMapper streamQueueMapper;
private string[] partitionIds;
private ConcurrentDictionary<QueueId, EventHubAdapterReceiver> receivers;
private EventHubProducerClient client;
private ITelemetryProducer telemetryProducer;
/// <summary>
/// Gets the serialization manager.
/// </summary>
public SerializationManager SerializationManager { get; private set; }
/// <summary>
/// Name of the adapter. Primarily for logging purposes
/// </summary>
public string Name { get; }
/// <summary>
/// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time.
/// </summary>
/// <returns>True if this is a rewindable stream adapter, false otherwise.</returns>
public bool IsRewindable => true;
/// <summary>
/// Direction of this queue adapter: Read, Write or ReadWrite.
/// </summary>
/// <returns>The direction in which this adapter provides data.</returns>
public StreamProviderDirection Direction { get; protected set; } = StreamProviderDirection.ReadWrite;
/// <summary>
/// Creates a message cache for an eventhub partition.
/// </summary>
protected Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> CacheFactory { get; set; }
/// <summary>
/// Creates a partition checkpointer.
/// </summary>
private IStreamQueueCheckpointerFactory checkpointerFactory;
/// <summary>
/// Creates a failure handler for a partition.
/// </summary>
protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; }
/// <summary>
/// Create a queue mapper to map EventHub partitions to queues
/// </summary>
protected Func<string[], IEventHubQueueMapper> QueueMapperFactory { get; set; }
/// <summary>
/// Create a receiver monitor to report performance metrics.
/// Factory function should return an IEventHubReceiverMonitor.
/// </summary>
protected Func<EventHubReceiverMonitorDimensions, ILoggerFactory, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory { get; set; }
//for testing purpose, used in EventHubGeneratorStreamProvider
/// <summary>
/// Factory to create a IEventHubReceiver
/// </summary>
protected Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> EventHubReceiverFactory;
internal ConcurrentDictionary<QueueId, EventHubAdapterReceiver> EventHubReceivers { get { return this.receivers; } }
internal IEventHubQueueMapper EventHubQueueMapper { get { return this.streamQueueMapper; } }
public EventHubAdapterFactory(
string name,
EventHubOptions ehOptions,
EventHubReceiverOptions receiverOptions,
EventHubStreamCachePressureOptions cacheOptions,
StreamCacheEvictionOptions cacheEvictionOptions,
StreamStatisticOptions statisticOptions,
IEventHubDataAdapter dataAdapter,
IServiceProvider serviceProvider,
SerializationManager serializationManager,
ITelemetryProducer telemetryProducer,
ILoggerFactory loggerFactory)
{
this.Name = name;
this.cacheEvictionOptions = cacheEvictionOptions ?? throw new ArgumentNullException(nameof(cacheEvictionOptions));
this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions));
this.ehOptions = ehOptions ?? throw new ArgumentNullException(nameof(ehOptions));
this.cacheOptions = cacheOptions?? throw new ArgumentNullException(nameof(cacheOptions));
this.dataAdapter = dataAdapter ?? throw new ArgumentNullException(nameof(dataAdapter));
this.receiverOptions = receiverOptions?? throw new ArgumentNullException(nameof(receiverOptions));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
this.SerializationManager = serializationManager ?? throw new ArgumentNullException(nameof(serializationManager));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}
public virtual void Init()
{
this.receivers = new ConcurrentDictionary<QueueId, EventHubAdapterReceiver>();
this.telemetryProducer = this.serviceProvider.GetService<ITelemetryProducer>();
InitEventHubClient();
if (this.CacheFactory == null)
{
this.CacheFactory = CreateCacheFactory(this.cacheOptions).CreateCache;
}
if (this.StreamFailureHandlerFactory == null)
{
//TODO: Add a queue specific default failure handler with reasonable error reporting.
this.StreamFailureHandlerFactory = partition => Task.FromResult<IStreamFailureHandler>(new NoOpStreamDeliveryFailureHandler());
}
if (this.QueueMapperFactory == null)
{
this.QueueMapperFactory = partitions => new EventHubQueueMapper(partitions, this.Name);
}
if (this.ReceiverMonitorFactory == null)
{
this.ReceiverMonitorFactory = (dimensions, logger, telemetryProducer) => new DefaultEventHubReceiverMonitor(dimensions, telemetryProducer);
}
this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{this.ehOptions.Path}");
}
//should only need checkpointer on silo side, so move its init logic when it is used
private void InitCheckpointerFactory()
{
this.checkpointerFactory = this.serviceProvider.GetRequiredServiceByName<IStreamQueueCheckpointerFactory>(this.Name);
}
/// <summary>
/// Create queue adapter.
/// </summary>
/// <returns></returns>
public async Task<IQueueAdapter> CreateAdapter()
{
if (this.streamQueueMapper == null)
{
this.partitionIds = await GetPartitionIdsAsync();
this.streamQueueMapper = this.QueueMapperFactory(this.partitionIds);
}
return this;
}
/// <summary>
/// Create queue message cache adapter
/// </summary>
/// <returns></returns>
public IQueueAdapterCache GetQueueAdapterCache()
{
return this;
}
/// <summary>
/// Create queue mapper
/// </summary>
/// <returns></returns>
public IStreamQueueMapper GetStreamQueueMapper()
{
//TODO: CreateAdapter must be called first. Figure out how to safely enforce this
return this.streamQueueMapper;
}
/// <summary>
/// Acquire delivery failure handler for a queue
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId)
{
return this.StreamFailureHandlerFactory(this.streamQueueMapper.QueueToPartition(queueId));
}
/// <summary>
/// Writes a set of events to the queue as a single batch associated with the provided streamId.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="streamId"></param>
/// <param name="events"></param>
/// <param name="token"></param>
/// <param name="requestContext"></param>
/// <returns></returns>
public virtual Task QueueMessageBatchAsync<T>(StreamId streamId, IEnumerable<T> events, StreamSequenceToken token,
Dictionary<string, object> requestContext)
{
EventData eventData = this.dataAdapter.ToQueueMessage(streamId, events, token, requestContext);
string partitionKey = this.dataAdapter.GetPartitionKey(streamId);
return this.client.SendAsync(new[] { eventData }, new SendEventOptions { PartitionKey = partitionKey });
}
/// <summary>
/// Creates a queue receiver for the specified queueId
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public IQueueAdapterReceiver CreateReceiver(QueueId queueId)
{
return GetOrCreateReceiver(queueId);
}
/// <summary>
/// Create a cache for a given queue id
/// </summary>
/// <param name="queueId"></param>
public IQueueCache CreateQueueCache(QueueId queueId)
{
return GetOrCreateReceiver(queueId);
}
private EventHubAdapterReceiver GetOrCreateReceiver(QueueId queueId)
{
return this.receivers.GetOrAdd(queueId, q => MakeReceiver(queueId));
}
protected virtual void InitEventHubClient()
{
this.client = ehOptions.TokenCredential != null
? new EventHubProducerClient(ehOptions.FullyQualifiedNamespace, ehOptions.Path, ehOptions.TokenCredential)
: new EventHubProducerClient(ehOptions.ConnectionString, ehOptions.Path);
}
/// <summary>
/// Create a IEventHubQueueCacheFactory. It will create a EventHubQueueCacheFactory by default.
/// User can override this function to return their own implementation of IEventHubQueueCacheFactory,
/// and other customization of IEventHubQueueCacheFactory if they may.
/// </summary>
/// <returns></returns>
protected virtual IEventHubQueueCacheFactory CreateCacheFactory(EventHubStreamCachePressureOptions eventHubCacheOptions)
{
var eventHubPath = this.ehOptions.Path;
var sharedDimensions = new EventHubMonitorAggregationDimensions(eventHubPath);
return new EventHubQueueCacheFactory(eventHubCacheOptions, cacheEvictionOptions, statisticOptions, this.dataAdapter, this.SerializationManager, sharedDimensions);
}
private EventHubAdapterReceiver MakeReceiver(QueueId queueId)
{
var config = new EventHubPartitionSettings
{
Hub = ehOptions,
Partition = this.streamQueueMapper.QueueToPartition(queueId),
ReceiverOptions = this.receiverOptions
};
var receiverMonitorDimensions = new EventHubReceiverMonitorDimensions
{
EventHubPartition = config.Partition,
EventHubPath = config.Hub.Path,
};
if (this.checkpointerFactory == null)
InitCheckpointerFactory();
return new EventHubAdapterReceiver(config, this.CacheFactory, this.checkpointerFactory.Create, this.loggerFactory, this.ReceiverMonitorFactory(receiverMonitorDimensions, this.loggerFactory, this.telemetryProducer),
this.serviceProvider.GetRequiredService<IOptions<LoadSheddingOptions>>().Value,
this.telemetryProducer,
this.EventHubReceiverFactory);
}
/// <summary>
/// Get partition Ids from eventhub
/// </summary>
/// <returns></returns>
protected virtual async Task<string[]> GetPartitionIdsAsync()
{
return await client.GetPartitionIdsAsync();
}
public static EventHubAdapterFactory Create(IServiceProvider services, string name)
{
var ehOptions = services.GetOptionsByName<EventHubOptions>(name);
var receiverOptions = services.GetOptionsByName<EventHubReceiverOptions>(name);
var cacheOptions = services.GetOptionsByName<EventHubStreamCachePressureOptions>(name);
var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name);
var evictionOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name);
IEventHubDataAdapter dataAdapter = services.GetServiceByName<IEventHubDataAdapter>(name)
?? services.GetService<IEventHubDataAdapter>()
?? ActivatorUtilities.CreateInstance<EventHubDataAdapter>(services);
var factory = ActivatorUtilities.CreateInstance<EventHubAdapterFactory>(services, name, ehOptions, receiverOptions, cacheOptions, evictionOptions, statisticOptions, dataAdapter);
factory.Init();
return factory;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Imaging.Metafile.cs
//
// Authors:
// Christian Meyer, eMail: Christian.Meyer@cs.tum.edu
// Dennis Hayes (dennish@raytek.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004,2006-2007 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.IO;
using System.Reflection;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
using System.Runtime.Serialization;
namespace System.Drawing.Imaging
{
#if !NETCORE
[Editor ("System.Drawing.Design.MetafileEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
#endif
[Serializable]
public sealed class Metafile : Image
{
// constructors
internal Metafile(IntPtr ptr) => SetNativeImage(ptr);
// Usually called when cloning images that need to have
// not only the handle saved, but also the underlying stream
// (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image)
internal Metafile(IntPtr ptr, Stream stream) => SetNativeImage(ptr);
public Metafile(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
// With libgdiplus we use a custom API for this, because there's no easy way
// to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
int status = Gdip.GdipCreateMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out nativeImage);
// Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive
// to avoid the object being collected and therefore the delegates would be collected as well.
GC.KeepAlive(sh);
Gdip.CheckStatus(status);
}
public Metafile(string filename)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(filename);
int status = Gdip.GdipCreateMetafileFromFile(filename, out nativeImage);
if (status == Gdip.GenericError)
throw new ExternalException("Couldn't load specified file.");
Gdip.CheckStatus(status);
}
public Metafile(IntPtr henhmetafile, bool deleteEmf)
{
int status = Gdip.GdipCreateMetafileFromEmf(henhmetafile, deleteEmf, out nativeImage);
Gdip.CheckStatus(status);
}
public Metafile(IntPtr referenceHdc, EmfType emfType) :
this(referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, emfType, null)
{
}
public Metafile(IntPtr referenceHdc, Rectangle frameRect) :
this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(IntPtr referenceHdc, RectangleF frameRect) :
this(referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader)
{
int status = Gdip.GdipCreateMetafileFromEmf(hmetafile, false, out nativeImage);
Gdip.CheckStatus(status);
}
public Metafile(Stream stream, IntPtr referenceHdc) :
this(stream, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc) :
this(fileName, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual,
null)
{
}
public Metafile(IntPtr referenceHdc, EmfType emfType, string description) :
this(referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, emfType, description)
{
}
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) :
this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, null)
{
}
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) :
this(referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, null)
{
}
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader, bool deleteWmf)
{
int status = Gdip.GdipCreateMetafileFromEmf(hmetafile, deleteWmf, out nativeImage);
Gdip.CheckStatus(status);
}
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type) :
this(stream, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, null)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect) :
this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect) :
this(stream, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, EmfType type) :
this(fileName, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect) :
this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect) :
this(fileName, referenceHdc, frameRect, MetafileFrameUnit.GdiCompatible, EmfType.EmfPlusDual, null)
{
}
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(referenceHdc, frameRect, frameUnit, type, null)
{
}
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type) :
this(referenceHdc, frameRect, frameUnit, type, null)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description) :
this(stream, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, description)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) :
this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, null)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) :
this(stream, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, EmfType type, string description) :
this(fileName, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, description)
{
}
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit) :
this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, null)
{
}
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type,
string desc)
{
int status = Gdip.GdipRecordMetafileI(referenceHdc, type, ref frameRect, frameUnit,
desc, out nativeImage);
Gdip.CheckStatus(status);
}
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type,
string description)
{
int status = Gdip.GdipRecordMetafile(referenceHdc, type, ref frameRect, frameUnit,
description, out nativeImage);
Gdip.CheckStatus(status);
}
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type) : this(stream, referenceHdc, frameRect, frameUnit, type, null)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit,
EmfType type) : this(stream, referenceHdc, frameRect, frameUnit, type, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type) : this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
string description) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual, description)
{
}
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit,
EmfType type) : this(fileName, referenceHdc, frameRect, frameUnit, type, null)
{
}
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit,
string desc) : this(fileName, referenceHdc, frameRect, frameUnit, EmfType.EmfPlusDual,
desc)
{
}
public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
if (stream == null)
throw new NullReferenceException(nameof(stream));
// With libgdiplus we use a custom API for this, because there's no easy way
// to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
int status = Gdip.GdipRecordMetafileFromDelegateI_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc,
type, ref frameRect, frameUnit, description, out nativeImage);
// Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive
// to avoid the object being collected and therefore the delegates would be collected as well.
GC.KeepAlive(sh);
Gdip.CheckStatus(status);
}
public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
if (stream == null)
throw new NullReferenceException(nameof(stream));
// With libgdiplus we use a custom API for this, because there's no easy way
// to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
int status = Gdip.GdipRecordMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc,
type, ref frameRect, frameUnit, description, out nativeImage);
// Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive
// to avoid the object being collected and therefore the delegates would be collected as well.
GC.KeepAlive(sh);
Gdip.CheckStatus(status);
}
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(fileName);
int status = Gdip.GdipRecordMetafileFileNameI(fileName, referenceHdc, type, ref frameRect,
frameUnit, description, out nativeImage);
Gdip.CheckStatus(status);
}
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(fileName);
int status = Gdip.GdipRecordMetafileFileName(fileName, referenceHdc, type, ref frameRect, frameUnit,
description, out nativeImage);
Gdip.CheckStatus(status);
}
private Metafile(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
// methods
public IntPtr GetHenhmetafile()
{
return nativeImage;
}
public MetafileHeader GetMetafileHeader()
{
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
int status = Gdip.GdipGetMetafileHeaderFromMetafile(nativeImage, header);
Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
finally
{
Marshal.FreeHGlobal(header);
}
}
public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile)
{
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
int status = Gdip.GdipGetMetafileHeaderFromEmf(henhmetafile, header);
Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
finally
{
Marshal.FreeHGlobal(header);
}
}
public static MetafileHeader GetMetafileHeader(Stream stream)
{
if (stream == null)
throw new NullReferenceException(nameof(stream));
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
// With libgdiplus we use a custom API for this, because there's no easy way
// to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
int status = Gdip.GdipGetMetafileHeaderFromDelegate_linux(sh.GetHeaderDelegate,
sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate,
sh.SizeDelegate, header);
// Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive
// to avoid the object being collected and therefore the delegates would be collected as well.
GC.KeepAlive(sh);
Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
finally
{
Marshal.FreeHGlobal(header);
}
}
public static MetafileHeader GetMetafileHeader(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
int status = Gdip.GdipGetMetafileHeaderFromFile(fileName, header);
Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
finally
{
Marshal.FreeHGlobal(header);
}
}
public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader)
{
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
int status = Gdip.GdipGetMetafileHeaderFromEmf(hmetafile, header);
Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
finally
{
Marshal.FreeHGlobal(header);
}
}
public void PlayRecord(EmfPlusRecordType recordType, int flags, int dataSize, byte[] data)
{
int status = Gdip.GdipPlayMetafileRecord(nativeImage, recordType, flags, dataSize, data);
Gdip.CheckStatus(status);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: CommonClasses
**
**
** Purpose: utility classes
**
**
===========================================================*/
// All classes and methods in here are only for the internal use by the XML and Binary Formatters.
// They are public so that the XMLFormatter can address them. Eventually they will
// be signed so that they can't be used by external applications.
namespace System.Runtime.Serialization.Formatters.Binary
{
using System;
using System.Collections;
using System.Reflection;
using System.Text;
using System.Globalization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Diagnostics;
// The ParseRecord class holds the parsed XML information. There is a
// ParsedRecord for each XML Element
internal sealed class ParseRecord
#if _DEBUG
: ITrace
#endif
{
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal static int parseRecordIdCount = 1;
internal int PRparseRecordId = 0;
#pragma warning restore 0414
// Enums
internal InternalParseTypeE PRparseTypeEnum = InternalParseTypeE.Empty;
internal InternalObjectTypeE PRobjectTypeEnum = InternalObjectTypeE.Empty;
internal InternalArrayTypeE PRarrayTypeEnum = InternalArrayTypeE.Empty;
internal InternalMemberTypeE PRmemberTypeEnum = InternalMemberTypeE.Empty;
internal InternalMemberValueE PRmemberValueEnum = InternalMemberValueE.Empty;
internal InternalObjectPositionE PRobjectPositionEnum = InternalObjectPositionE.Empty;
// Object
internal String PRname;
// Value
internal String PRvalue;
internal Object PRvarValue;
// dt attribute
internal String PRkeyDt;
internal Type PRdtType;
internal InternalPrimitiveTypeE PRdtTypeCode;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal bool PRisVariant = false; // Used by Binary
internal bool PRisEnum = false;
#pragma warning restore 0414
// Object ID
internal long PRobjectId;
// Reference ID
internal long PRidRef;
// Array
// Array Element Type
internal String PRarrayElementTypeString;
internal Type PRarrayElementType;
internal bool PRisArrayVariant = false;
internal InternalPrimitiveTypeE PRarrayElementTypeCode;
// Parsed array information
internal int PRrank;
internal int[] PRlengthA;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal int[] PRpositionA;
internal int[] PRlowerBoundA;
internal int[] PRupperBoundA;
#pragma warning restore 0414
// Array map for placing array elements in array
internal int[] PRindexMap;
internal int PRmemberIndex;
internal int PRlinearlength;
internal int[] PRrectangularMap;
internal bool PRisLowerBound;
// SerializedStreamHeader information
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal long PRtopId;
internal long PRheaderId;
#pragma warning restore 0414
// MemberInfo accumulated during parsing of members
internal ReadObjectInfo PRobjectInfo;
// ValueType Fixup needed
internal bool PRisValueTypeFixup = false;
// Created object
internal Object PRnewObj;
internal Object[] PRobjectA; //optimization, will contain object[]
internal PrimitiveArray PRprimitiveArray; // for Primitive Soap arrays, optimization
internal bool PRisRegistered; // Used when registering nested classes
internal Object[] PRmemberData; // member data is collected here before populating
internal SerializationInfo PRsi;
internal int PRnullCount; // Count of consecutive nulls within an array
internal ParseRecord()
{
}
#if _DEBUG
// Get a String describing the ParseRecord
// ITrace
public String Trace()
{
return "ParseRecord"+PRparseRecordId+" ParseType "+ ((Enum)PRparseTypeEnum).ToString() +" name "+PRname+" keyDt "+Util.PString(PRkeyDt);
}
#endif
// Initialize ParseRecord. Called when reusing.
internal void Init()
{
// Enums
PRparseTypeEnum = InternalParseTypeE.Empty;
PRobjectTypeEnum = InternalObjectTypeE.Empty;
PRarrayTypeEnum = InternalArrayTypeE.Empty;
PRmemberTypeEnum = InternalMemberTypeE.Empty;
PRmemberValueEnum = InternalMemberValueE.Empty;
PRobjectPositionEnum = InternalObjectPositionE.Empty;
// Object
PRname = null;
// Value
PRvalue = null;
// dt attribute
PRkeyDt = null;
PRdtType = null;
PRdtTypeCode = InternalPrimitiveTypeE.Invalid;
PRisEnum = false;
// Object ID
PRobjectId = 0;
// Reference ID
PRidRef = 0;
// Array
// Array Element Type
PRarrayElementTypeString = null;
PRarrayElementType = null;
PRisArrayVariant = false;
PRarrayElementTypeCode = InternalPrimitiveTypeE.Invalid;
// Parsed array information
PRrank = 0;
PRlengthA = null;
PRpositionA = null;
PRlowerBoundA = null;
PRupperBoundA = null;
// Array map for placing array elements in array
PRindexMap = null;
PRmemberIndex = 0;
PRlinearlength = 0;
PRrectangularMap = null;
PRisLowerBound = false;
// SerializedStreamHeader information
PRtopId = 0;
PRheaderId = 0;
// ValueType Fixup needed
PRisValueTypeFixup = false;
PRnewObj = null;
PRobjectA = null;
PRprimitiveArray = null;
PRobjectInfo = null;
PRisRegistered = false;
PRmemberData = null;
PRsi = null;
PRnullCount = 0;
}
#if _DEBUG // Dump ParseRecord.
[Conditional("SER_LOGGING")]
internal void Dump()
{
SerTrace.Log("ParseRecord Dump ",PRparseRecordId);
SerTrace.Log("Enums");
Util.NVTrace("ParseType",((Enum)PRparseTypeEnum).ToString());
Util.NVTrace("ObjectType",((Enum)PRobjectTypeEnum).ToString());
Util.NVTrace("ArrayType",((Enum)PRarrayTypeEnum).ToString());
Util.NVTrace("MemberType",((Enum)PRmemberTypeEnum).ToString());
Util.NVTrace("MemberValue",((Enum)PRmemberValueEnum).ToString());
Util.NVTrace("ObjectPosition",((Enum)PRobjectPositionEnum).ToString());
SerTrace.Log("Basics");
Util.NVTrace("Name",PRname);
Util.NVTrace("Value ",PRvalue);
Util.NVTrace("varValue ",PRvarValue);
if (PRvarValue != null)
Util.NVTrace("varValue type",PRvarValue.GetType());
Util.NVTrace("keyDt",PRkeyDt);
Util.NVTrace("dtType",PRdtType);
Util.NVTrace("code",((Enum)PRdtTypeCode).ToString());
Util.NVTrace("objectID",PRobjectId);
Util.NVTrace("idRef",PRidRef);
Util.NVTrace("isEnum",PRisEnum);
SerTrace.Log("Array ");
Util.NVTrace("arrayElementTypeString",PRarrayElementTypeString);
Util.NVTrace("arrayElementType",PRarrayElementType);
Util.NVTrace("arrayElementTypeCode",((Enum)PRarrayElementTypeCode).ToString());
Util.NVTrace("isArrayVariant",PRisArrayVariant);
Util.NVTrace("rank",PRrank);
Util.NVTrace("dimensions", Util.PArray(PRlengthA));
Util.NVTrace("position", Util.PArray(PRpositionA));
Util.NVTrace("lowerBoundA", Util.PArray(PRlowerBoundA));
Util.NVTrace("upperBoundA", Util.PArray(PRupperBoundA));
SerTrace.Log("Header ");
Util.NVTrace("nullCount", PRnullCount);
SerTrace.Log("New Object");
if (PRnewObj != null)
Util.NVTrace("newObj", PRnewObj);
}
#endif
}
#if _DEBUG
internal interface ITrace
{
String Trace();
}
#endif
// Implements a stack used for parsing
internal sealed class SerStack
{
internal Object[] objects = new Object[5];
internal String stackId;
internal int top = -1;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal int next = 0;
#pragma warning restore 0414
internal SerStack()
{
stackId = "System";
}
internal SerStack(String stackId) {
this.stackId = stackId;
}
// Push the object onto the stack
internal void Push(Object obj) {
#if _DEBUG
SerTrace.Log(this, "Push ",stackId," ",((obj is ITrace)?((ITrace)obj).Trace():""));
#endif
if (top == (objects.Length -1))
{
IncreaseCapacity();
}
objects[++top] = obj;
}
// Pop the object from the stack
internal Object Pop() {
if (top < 0)
return null;
Object obj = objects[top];
objects[top--] = null;
#if _DEBUG
SerTrace.Log(this, "Pop ",stackId," ",((obj is ITrace)?((ITrace)obj).Trace():""));
#endif
return obj;
}
internal void IncreaseCapacity() {
int size = objects.Length * 2;
Object[] newItems = new Object[size];
Array.Copy(objects, 0, newItems, 0, objects.Length);
objects = newItems;
}
// Gets the object on the top of the stack
internal Object Peek() {
if (top < 0)
return null;
#if _DEBUG
SerTrace.Log(this, "Peek ",stackId," ",((objects[top] is ITrace)?((ITrace)objects[top]).Trace():""));
#endif
return objects[top];
}
// Gets the second entry in the stack.
internal Object PeekPeek() {
if (top < 1)
return null;
#if _DEBUG
SerTrace.Log(this, "PeekPeek ",stackId," ",((objects[top - 1] is ITrace)?((ITrace)objects[top - 1]).Trace():""));
#endif
return objects[top - 1];
}
// The number of entries in the stack
internal int Count() {
return top + 1;
}
// The number of entries in the stack
internal bool IsEmpty() {
if (top > 0)
return false;
else
return true;
}
[Conditional("SER_LOGGING")]
internal void Dump()
{
for (int i=0; i<Count(); i++)
{
Object obj = objects[i];
#if _DEBUG
SerTrace.Log(this, "Stack Dump ",stackId," "+((obj is ITrace)?((ITrace)obj).Trace():""));
#endif
}
}
}
// Implements a Growable array
[Serializable]
internal sealed class SizedArray : ICloneable
{
internal Object[] objects = null;
internal Object[] negObjects = null;
internal SizedArray()
{
objects = new Object[16];
negObjects = new Object[4];
}
internal SizedArray(int length)
{
objects = new Object[length];
negObjects = new Object[length];
}
private SizedArray(SizedArray sizedArray)
{
objects = new Object[sizedArray.objects.Length];
sizedArray.objects.CopyTo(objects, 0);
negObjects = new Object[sizedArray.negObjects.Length];
sizedArray.negObjects.CopyTo(negObjects, 0);
}
public Object Clone()
{
return new SizedArray(this);
}
internal Object this[int index]
{
get
{
if (index < 0)
{
if (-index > negObjects.Length - 1)
return null;
return negObjects[-index];
}
else
{
if (index > objects.Length - 1)
return null;
return objects[index];
}
}
set
{
if (index < 0)
{
if (-index > negObjects.Length-1 )
{
IncreaseCapacity(index);
}
negObjects[-index] = value;
}
else
{
if (index > objects.Length-1 )
{
IncreaseCapacity(index);
}
if (objects[index] != null)
{
//Console.WriteLine("SizedArray Setting a non-zero "+index+" "+value);
}
objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(negObjects.Length * 2, (-index)+1);
Object[] newItems = new Object[size];
Array.Copy(negObjects, 0, newItems, 0, negObjects.Length);
negObjects = newItems;
}
else
{
int size = Math.Max(objects.Length * 2, index+1);
Object[] newItems = new Object[size];
Array.Copy(objects, 0, newItems, 0, objects.Length);
objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(Environment.GetResourceString("Serialization_CorruptedStream"));
}
}
}
[Serializable]
internal sealed class IntSizedArray : ICloneable
{
internal int[] objects = new int[16];
internal int[] negObjects = new int[4];
public IntSizedArray()
{
}
private IntSizedArray(IntSizedArray sizedArray)
{
objects = new int[sizedArray.objects.Length];
sizedArray.objects.CopyTo(objects, 0);
negObjects = new int[sizedArray.negObjects.Length];
sizedArray.negObjects.CopyTo(negObjects, 0);
}
public Object Clone()
{
return new IntSizedArray(this);
}
internal int this[int index]
{
get
{
if (index < 0)
{
if (-index > negObjects.Length-1 )
return 0;
return negObjects[-index];
}
else
{
if (index > objects.Length-1 )
return 0;
return objects[index];
}
}
set
{
if (index < 0)
{
if (-index > negObjects.Length-1 )
{
IncreaseCapacity(index);
}
negObjects[-index] = value;
}
else
{
if (index > objects.Length-1 )
{
IncreaseCapacity(index);
}
objects[index] = value;
}
}
}
internal void IncreaseCapacity(int index)
{
try
{
if (index < 0)
{
int size = Math.Max(negObjects.Length * 2, (-index)+1);
int[] newItems = new int[size];
Array.Copy(negObjects, 0, newItems, 0, negObjects.Length);
negObjects = newItems;
}
else
{
int size = Math.Max(objects.Length * 2, index+1);
int[] newItems = new int[size];
Array.Copy(objects, 0, newItems, 0, objects.Length);
objects = newItems;
}
}
catch (Exception)
{
throw new SerializationException(Environment.GetResourceString("Serialization_CorruptedStream"));
}
}
}
internal sealed class NameCache
{
static System.Collections.Concurrent.ConcurrentDictionary<string, object> ht = new System.Collections.Concurrent.ConcurrentDictionary<string, object>();
String name = null;
internal Object GetCachedValue(String name)
{
this.name = name;
object value;
return ht.TryGetValue(name, out value) ? value : null;
}
internal void SetCachedValue(Object value)
{
ht[name] = value;
}
}
#if _DEBUG
// Utilities
internal static class Util
{
// Replaces a null string with an empty string
internal static String PString(String value)
{
if (value == null)
return "";
else
return value;
}
// Converts an object to a string and checks for nulls
internal static String PString(Object value)
{
if (value == null)
return "";
else
return value.ToString();
}
// Converts a single int array to a string
internal static String PArray(int[] array)
{
if (array != null)
{
StringBuilder sb = new StringBuilder(10);
sb.Append("[");
for (int i=0; i<array.Length; i++)
{
sb.Append(array[i]);
if (i != array.Length -1)
sb.Append(",");
}
sb.Append("]");
return sb.ToString();
}
else
return "";
}
// Traces an name value pair
[Conditional("SER_LOGGING")]
internal static void NVTrace(String name, String value)
{
SerTrace.Log(" "+name+((value == null)?" = null":" = "+value));
}
// Traces an name value pair
[Conditional("SER_LOGGING")]
internal static void NVTrace(String name, Object value)
{
SerTrace.Log(" "+name+((value == null)?" = null":" = "+value.ToString()));
}
// Traces an name value pair
[Conditional("_LOGGING")]
internal static void NVTraceI(String name, String value)
{
BCLDebug.Trace("Binary", " "+name+((value == null)?" = null":" = "+value));
}
// Traces an name value pair
[Conditional("_LOGGING")]
internal static void NVTraceI(String name, Object value)
{
BCLDebug.Trace("Binary", " "+name+((value == null)?" = null":" = "+value.ToString()));
}
}
#endif
// Used to fixup value types. Only currently used for valuetypes which are array items.
internal sealed class ValueFixup
{
internal ValueFixupEnum valueFixupEnum = ValueFixupEnum.Empty;
internal Array arrayObj;
internal int[] indexMap;
internal Object header = null;
internal Object memberObject;
internal static volatile MemberInfo valueInfo;
internal ReadObjectInfo objectInfo;
internal String memberName;
internal ValueFixup(Array arrayObj, int[] indexMap)
{
#if _DEBUG
SerTrace.Log(this, "Array Constructor ",arrayObj);
#endif
valueFixupEnum = ValueFixupEnum.Array;
this.arrayObj = arrayObj;
this.indexMap = indexMap;
}
internal ValueFixup(Object memberObject, String memberName, ReadObjectInfo objectInfo)
{
#if _DEBUG
SerTrace.Log(this, "Member Constructor ",memberObject);
#endif
valueFixupEnum = ValueFixupEnum.Member;
this.memberObject = memberObject;
this.memberName = memberName;
this.objectInfo = objectInfo;
}
[System.Security.SecurityCritical] // auto-generated
internal void Fixup(ParseRecord record, ParseRecord parent) {
Object obj = record.PRnewObj;
#if _DEBUG
SerTrace.Log(this, "Fixup ",obj," ",((Enum)valueFixupEnum).ToString());
#endif
switch (valueFixupEnum)
{
case ValueFixupEnum.Array:
arrayObj.SetValue(obj, indexMap);
break;
case ValueFixupEnum.Header:
Type type = typeof(Header);
if (valueInfo == null)
{
MemberInfo[] valueInfos = type.GetMember("Value");
if (valueInfos.Length != 1)
throw new SerializationException(Environment.GetResourceString("Serialization_HeaderReflection",valueInfos.Length));
valueInfo = valueInfos[0];
}
FormatterServices.SerializationSetValue(valueInfo, header, obj);
break;
case ValueFixupEnum.Member:
SerTrace.Log(this, "Fixup Member new object value ",obj," memberObject ",memberObject);
if (objectInfo.isSi)
{
SerTrace.Log(this, "Recording a fixup on member: ", memberName,
" in object id", parent.PRobjectId, " Required Object ", record.PRobjectId);
objectInfo.objectManager.RecordDelayedFixup(parent.PRobjectId, memberName, record.PRobjectId);
// Console.WriteLine("SerializationInfo: Main Object ({0}): {1}. SubObject ({2}): {3}", parent.PRobjectId,
// objectInfo.obj, record.PRobjectId, obj);
}
else
{
MemberInfo memberInfo = objectInfo.GetMemberInfo(memberName);
SerTrace.Log(this, "Recording a fixup on member:", memberInfo, " in object id ",
parent.PRobjectId," Required Object", record.PRobjectId);
if (memberInfo != null)
objectInfo.objectManager.RecordFixup(parent.PRobjectId, memberInfo, record.PRobjectId);
// Console.WriteLine("MemberFixup: Main Object({0}): {1}. SubObject({2}): {3}", parent.PRobjectId,
// objectInfo.obj.GetType(), record.PRobjectId, obj.GetType());
}
break;
}
}
#if _DEBUG
public String Trace()
{
return "ValueFixup"+((Enum)valueFixupEnum).ToString();
}
#endif
}
// Class used to transmit Enums from the XML and Binary Formatter class to the ObjectWriter and ObjectReader class
internal sealed class InternalFE
{
internal FormatterTypeStyle FEtypeFormat;
internal FormatterAssemblyStyle FEassemblyFormat;
internal TypeFilterLevel FEsecurityLevel;
internal InternalSerializerTypeE FEserializerTypeEnum;
}
internal sealed class NameInfo
{
internal String NIFullName; // Name from SerObjectInfo.GetType
internal long NIobjectId;
internal long NIassemId;
internal InternalPrimitiveTypeE NIprimitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
internal Type NItype;
internal bool NIisSealed;
internal bool NIisArray;
internal bool NIisArrayItem;
internal bool NItransmitTypeOnObject;
internal bool NItransmitTypeOnMember;
internal bool NIisParentTypeOnObject;
internal InternalArrayTypeE NIarrayEnum;
internal NameInfo()
{
}
internal void Init()
{
NIFullName = null;
NIobjectId = 0;
NIassemId = 0;
NIprimitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
NItype = null;
NIisSealed = false;
NItransmitTypeOnObject = false;
NItransmitTypeOnMember = false;
NIisParentTypeOnObject = false;
NIisArray = false;
NIisArrayItem = false;
NIarrayEnum = InternalArrayTypeE.Empty;
NIsealedStatusChecked = false;
}
#if _DEBUG
[Conditional("SER_LOGGING")]
internal void Dump(String value)
{
Util.NVTrace("name", NIFullName);
Util.NVTrace("objectId", NIobjectId);
Util.NVTrace("assemId", NIassemId);
Util.NVTrace("primitiveTypeEnum", ((Enum)NIprimitiveTypeEnum).ToString());
Util.NVTrace("type", NItype);
Util.NVTrace("isSealed", NIisSealed);
Util.NVTrace("transmitTypeOnObject", NItransmitTypeOnObject);
Util.NVTrace("transmitTypeOnMember", NItransmitTypeOnMember);
Util.NVTrace("isParentTypeOnObject", NIisParentTypeOnObject);
Util.NVTrace("isArray", NIisArray);
Util.NVTrace("isArrayItem", NIisArrayItem);
Util.NVTrace("arrayEnum", ((Enum)NIarrayEnum).ToString());
}
#endif
private bool NIsealedStatusChecked = false;
public bool IsSealed
{
get {
if (!NIsealedStatusChecked)
{
NIisSealed = NItype.IsSealed;
NIsealedStatusChecked = true;
}
return NIisSealed;
}
}
public String NIname
{
get {
if (this.NIFullName == null)
this.NIFullName = NItype.FullName;
return this.NIFullName;
}
set {
this.NIFullName = value;
}
}
}
internal sealed class PrimitiveArray
{
InternalPrimitiveTypeE code;
Boolean[] booleanA = null;
Char[] charA = null;
Double[] doubleA = null;
Int16[] int16A = null;
Int32[] int32A = null;
Int64[] int64A = null;
SByte[] sbyteA = null;
Single[] singleA = null;
UInt16[] uint16A = null;
UInt32[] uint32A = null;
UInt64[] uint64A = null;
internal PrimitiveArray(InternalPrimitiveTypeE code, Array array)
{
Init(code, array);
}
internal void Init(InternalPrimitiveTypeE code, Array array)
{
this.code = code;
switch (code)
{
case InternalPrimitiveTypeE.Boolean:
booleanA = (Boolean[])array;
break;
case InternalPrimitiveTypeE.Char:
charA = (Char[])array;
break;
case InternalPrimitiveTypeE.Double:
doubleA = (Double[])array;
break;
case InternalPrimitiveTypeE.Int16:
int16A = (Int16[])array;
break;
case InternalPrimitiveTypeE.Int32:
int32A = (Int32[])array;
break;
case InternalPrimitiveTypeE.Int64:
int64A = (Int64[])array;
break;
case InternalPrimitiveTypeE.SByte:
sbyteA = (SByte[])array;
break;
case InternalPrimitiveTypeE.Single:
singleA = (Single[])array;
break;
case InternalPrimitiveTypeE.UInt16:
uint16A = (UInt16[])array;
break;
case InternalPrimitiveTypeE.UInt32:
uint32A = (UInt32[])array;
break;
case InternalPrimitiveTypeE.UInt64:
uint64A = (UInt64[])array;
break;
}
}
internal void SetValue(String value, int index)
{
switch (code)
{
case InternalPrimitiveTypeE.Boolean:
booleanA[index] = Boolean.Parse(value);
break;
case InternalPrimitiveTypeE.Char:
if ((value[0] == '_') && (value.Equals("_0x00_")))
charA[index] = Char.MinValue;
else
charA[index] = Char.Parse(value);
break;
case InternalPrimitiveTypeE.Double:
doubleA[index] = Double.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int16:
int16A[index] = Int16.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int32:
int32A[index] = Int32.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Int64:
int64A[index] = Int64.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.SByte:
sbyteA[index] = SByte.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.Single:
singleA[index] = Single.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt16:
uint16A[index] = UInt16.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt32:
uint32A[index] = UInt32.Parse(value, CultureInfo.InvariantCulture);
break;
case InternalPrimitiveTypeE.UInt64:
uint64A[index] = UInt64.Parse(value, CultureInfo.InvariantCulture);
break;
}
}
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsUrl
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// PathItems operations.
/// </summary>
public partial class PathItems : IServiceOperations<AutoRestUrlTestService>, IPathItems
{
/// <summary>
/// Initializes a new instance of the PathItems class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public PathItems(AutoRestUrlTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestUrlTestService
/// </summary>
public AutoRestUrlTestService Client { get; private set; }
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery='globalStringQuery',
/// pathItemStringQuery='pathItemStringQuery',
/// localStringQuery='localStringQuery'
/// </summary>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value 'localStringQuery'
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> GetAllWithValuesWithHttpMessagesAsync(string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (localStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localStringPath");
}
if (pathItemStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pathItemStringPath");
}
if (this.Client.GlobalStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.GlobalStringPath");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("localStringPath", localStringPath);
tracingParameters.Add("localStringQuery", localStringQuery);
tracingParameters.Add("pathItemStringPath", pathItemStringPath);
tracingParameters.Add("pathItemStringQuery", pathItemStringQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetAllWithValues", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/pathItemStringQuery/localStringQuery").ToString();
_url = _url.Replace("{localStringPath}", Uri.EscapeDataString(localStringPath));
_url = _url.Replace("{pathItemStringPath}", Uri.EscapeDataString(pathItemStringPath));
_url = _url.Replace("{globalStringPath}", Uri.EscapeDataString(this.Client.GlobalStringPath));
List<string> _queryParameters = new List<string>();
if (localStringQuery != null)
{
_queryParameters.Add(string.Format("localStringQuery={0}", Uri.EscapeDataString(localStringQuery)));
}
if (pathItemStringQuery != null)
{
_queryParameters.Add(string.Format("pathItemStringQuery={0}", Uri.EscapeDataString(pathItemStringQuery)));
}
if (this.Client.GlobalStringQuery != null)
{
_queryParameters.Add(string.Format("globalStringQuery={0}", Uri.EscapeDataString(this.Client.GlobalStringQuery)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery=null,
/// pathItemStringQuery='pathItemStringQuery',
/// localStringQuery='localStringQuery'
/// </summary>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value 'localStringQuery'
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> GetGlobalQueryNullWithHttpMessagesAsync(string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (localStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localStringPath");
}
if (pathItemStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pathItemStringPath");
}
if (this.Client.GlobalStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.GlobalStringPath");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("localStringPath", localStringPath);
tracingParameters.Add("localStringQuery", localStringQuery);
tracingParameters.Add("pathItemStringPath", pathItemStringPath);
tracingParameters.Add("pathItemStringQuery", pathItemStringQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetGlobalQueryNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/null/pathItemStringQuery/localStringQuery").ToString();
_url = _url.Replace("{localStringPath}", Uri.EscapeDataString(localStringPath));
_url = _url.Replace("{pathItemStringPath}", Uri.EscapeDataString(pathItemStringPath));
_url = _url.Replace("{globalStringPath}", Uri.EscapeDataString(this.Client.GlobalStringPath));
List<string> _queryParameters = new List<string>();
if (localStringQuery != null)
{
_queryParameters.Add(string.Format("localStringQuery={0}", Uri.EscapeDataString(localStringQuery)));
}
if (pathItemStringQuery != null)
{
_queryParameters.Add(string.Format("pathItemStringQuery={0}", Uri.EscapeDataString(pathItemStringQuery)));
}
if (this.Client.GlobalStringQuery != null)
{
_queryParameters.Add(string.Format("globalStringQuery={0}", Uri.EscapeDataString(this.Client.GlobalStringQuery)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// send globalStringPath=globalStringPath,
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery=null,
/// pathItemStringQuery='pathItemStringQuery', localStringQuery=null
/// </summary>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain null value
/// </param>
/// <param name='pathItemStringQuery'>
/// A string value 'pathItemStringQuery' that appears as a query parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> GetGlobalAndLocalQueryNullWithHttpMessagesAsync(string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (localStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localStringPath");
}
if (pathItemStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pathItemStringPath");
}
if (this.Client.GlobalStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.GlobalStringPath");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("localStringPath", localStringPath);
tracingParameters.Add("localStringQuery", localStringQuery);
tracingParameters.Add("pathItemStringPath", pathItemStringPath);
tracingParameters.Add("pathItemStringQuery", pathItemStringQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetGlobalAndLocalQueryNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/null/pathItemStringQuery/null").ToString();
_url = _url.Replace("{localStringPath}", Uri.EscapeDataString(localStringPath));
_url = _url.Replace("{pathItemStringPath}", Uri.EscapeDataString(pathItemStringPath));
_url = _url.Replace("{globalStringPath}", Uri.EscapeDataString(this.Client.GlobalStringPath));
List<string> _queryParameters = new List<string>();
if (localStringQuery != null)
{
_queryParameters.Add(string.Format("localStringQuery={0}", Uri.EscapeDataString(localStringQuery)));
}
if (pathItemStringQuery != null)
{
_queryParameters.Add(string.Format("pathItemStringQuery={0}", Uri.EscapeDataString(pathItemStringQuery)));
}
if (this.Client.GlobalStringQuery != null)
{
_queryParameters.Add(string.Format("globalStringQuery={0}", Uri.EscapeDataString(this.Client.GlobalStringQuery)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// send globalStringPath='globalStringPath',
/// pathItemStringPath='pathItemStringPath',
/// localStringPath='localStringPath', globalStringQuery='globalStringQuery',
/// pathItemStringQuery=null, localStringQuery=null
/// </summary>
/// <param name='localStringPath'>
/// should contain value 'localStringPath'
/// </param>
/// <param name='pathItemStringPath'>
/// A string value 'pathItemStringPath' that appears in the path
/// </param>
/// <param name='localStringQuery'>
/// should contain value null
/// </param>
/// <param name='pathItemStringQuery'>
/// should contain value null
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> GetLocalPathItemQueryNullWithHttpMessagesAsync(string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (localStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localStringPath");
}
if (pathItemStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "pathItemStringPath");
}
if (this.Client.GlobalStringPath == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.GlobalStringPath");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("localStringPath", localStringPath);
tracingParameters.Add("localStringQuery", localStringQuery);
tracingParameters.Add("pathItemStringPath", pathItemStringPath);
tracingParameters.Add("pathItemStringQuery", pathItemStringQuery);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetLocalPathItemQueryNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/null/null").ToString();
_url = _url.Replace("{localStringPath}", Uri.EscapeDataString(localStringPath));
_url = _url.Replace("{pathItemStringPath}", Uri.EscapeDataString(pathItemStringPath));
_url = _url.Replace("{globalStringPath}", Uri.EscapeDataString(this.Client.GlobalStringPath));
List<string> _queryParameters = new List<string>();
if (localStringQuery != null)
{
_queryParameters.Add(string.Format("localStringQuery={0}", Uri.EscapeDataString(localStringQuery)));
}
if (pathItemStringQuery != null)
{
_queryParameters.Add(string.Format("pathItemStringQuery={0}", Uri.EscapeDataString(pathItemStringQuery)));
}
if (this.Client.GlobalStringQuery != null)
{
_queryParameters.Add(string.Format("globalStringQuery={0}", Uri.EscapeDataString(this.Client.GlobalStringQuery)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Security;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Text
{
public abstract class EncoderFallback
{
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal bool bIsMicrosoftBestFitFallback = false;
#pragma warning restore 0414
private static EncoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?"
private static EncoderFallback s_exceptionFallback;
// Get each of our generic fallbacks.
public static EncoderFallback ReplacementFallback
{
get
{
if (s_replacementFallback == null)
Interlocked.CompareExchange<EncoderFallback>(ref s_replacementFallback, new EncoderReplacementFallback(), null);
return s_replacementFallback;
}
}
public static EncoderFallback ExceptionFallback
{
get
{
if (s_exceptionFallback == null)
Interlocked.CompareExchange<EncoderFallback>(ref s_exceptionFallback, new EncoderExceptionFallback(), null);
return s_exceptionFallback;
}
}
// Fallback
//
// Return the appropriate unicode string alternative to the character that need to fall back.
// Most implimentations will be:
// return new MyCustomEncoderFallbackBuffer(this);
public abstract EncoderFallbackBuffer CreateFallbackBuffer();
// Maximum number of characters that this instance of this fallback could return
public abstract int MaxCharCount { get; }
}
public abstract class EncoderFallbackBuffer
{
// Most implementations will probably need an implemenation-specific constructor
// Public methods that cannot be overriden that let us do our fallback thing
// These wrap the internal methods so that we can check for people doing stuff that is incorrect
public abstract bool Fallback(char charUnknown, int index);
public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index);
// Get next character
public abstract char GetNextChar();
// Back up a character
public abstract bool MovePrevious();
// How many chars left in this fallback?
public abstract int Remaining { get; }
// Not sure if this should be public or not.
// Clear the buffer
public virtual void Reset()
{
while (GetNextChar() != (char)0) ;
}
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
[SecurityCritical]
internal unsafe char* charStart;
[SecurityCritical]
internal unsafe char* charEnd;
internal EncoderNLS encoder;
internal bool setEncoder;
internal bool bUsedEncoder;
internal bool bFallingBack = false;
internal int iRecursionCount = 0;
private const int iMaxRecursion = 250;
// Internal Reset
// For example, what if someone fails a conversion and wants to reset one of our fallback buffers?
[System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalReset()
{
charStart = null;
bFallingBack = false;
iRecursionCount = 0;
Reset();
}
// Set the above values
// This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder)
{
this.charStart = charStart;
this.charEnd = charEnd;
this.encoder = encoder;
this.setEncoder = setEncoder;
this.bUsedEncoder = false;
this.bFallingBack = false;
this.iRecursionCount = 0;
}
internal char InternalGetNextChar()
{
char ch = GetNextChar();
bFallingBack = (ch != 0);
if (ch == 0) iRecursionCount = 0;
return ch;
}
// Fallback the current character using the remaining buffer and encoder if necessary
// This can only be called by our encodings (other have to use the public fallback methods), so
// we can use our EncoderNLS here too.
// setEncoder is true if we're calling from a GetBytes method, false if we're calling from a GetByteCount
//
// Note that this could also change the contents of this.encoder, which is the same
// object that the caller is using, so the caller could mess up the encoder for us
// if they aren't careful.
[System.Security.SecurityCritical] // auto-generated
internal unsafe virtual bool InternalFallback(char ch, ref char* chars)
{
// Shouldn't have null charStart
Contract.Assert(charStart != null,
"[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized");
// Get our index, remember chars was preincremented to point at next char, so have to -1
int index = (int)(chars - charStart) - 1;
// See if it was a high surrogate
if (Char.IsHighSurrogate(ch))
{
// See if there's a low surrogate to go with it
if (chars >= this.charEnd)
{
// Nothing left in input buffer
// No input, return 0 if mustflush is false
if (this.encoder != null && !this.encoder.MustFlush)
{
// Done, nothing to fallback
if (this.setEncoder)
{
bUsedEncoder = true;
this.encoder.charLeftOver = ch;
}
bFallingBack = false;
return false;
}
}
else
{
// Might have a low surrogate
char cNext = *chars;
if (Char.IsLowSurrogate(cNext))
{
// If already falling back then fail
if (bFallingBack && iRecursionCount++ > iMaxRecursion)
ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext));
// Next is a surrogate, add it as surrogate pair, and increment chars
chars++;
bFallingBack = Fallback(ch, cNext, index);
return bFallingBack;
}
// Next isn't a low surrogate, just fallback the high surrogate
}
}
// If already falling back then fail
if (bFallingBack && iRecursionCount++ > iMaxRecursion)
ThrowLastCharRecursive((int)ch);
// Fall back our char
bFallingBack = Fallback(ch, index);
return bFallingBack;
}
// private helper methods
internal void ThrowLastCharRecursive(int charRecursive)
{
// Throw it, using our complete character
throw new ArgumentException(
SR.Format(SR.Argument_RecursiveFallback,
charRecursive), "chars");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
using BytesRef = Lucene.Net.Util.BytesRef;
using Counter = Lucene.Net.Util.Counter;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using DocValuesType_e = Lucene.Net.Index.FieldInfo.DocValuesType_e;
using IOUtils = Lucene.Net.Util.IOUtils;
internal sealed class DocValuesProcessor : StoredFieldsConsumer
{
// TODO: somewhat wasteful we also keep a map here; would
// be more efficient if we could "reuse" the map/hash
// lookup DocFieldProcessor already did "above"
private readonly IDictionary<string, DocValuesWriter> Writers = new Dictionary<string, DocValuesWriter>();
private readonly Counter BytesUsed;
public DocValuesProcessor(Counter bytesUsed)
{
this.BytesUsed = bytesUsed;
}
public override void StartDocument()
{
}
public override void FinishDocument()
{
}
public override void AddField(int docID, IndexableField field, FieldInfo fieldInfo)
{
DocValuesType_e? dvType = field.FieldType().DocValueType;
if (dvType != null)
{
fieldInfo.DocValuesType = dvType;
if (dvType == DocValuesType_e.BINARY)
{
AddBinaryField(fieldInfo, docID, field.BinaryValue());
}
else if (dvType == DocValuesType_e.SORTED)
{
AddSortedField(fieldInfo, docID, field.BinaryValue());
}
else if (dvType == DocValuesType_e.SORTED_SET)
{
AddSortedSetField(fieldInfo, docID, field.BinaryValue());
}
else if (dvType == DocValuesType_e.NUMERIC)
{
if (!(field.NumericValue is long?))
{
throw new System.ArgumentException("illegal type " + field.NumericValue.GetType() + ": DocValues types must be Long");
}
AddNumericField(fieldInfo, docID, (long)field.NumericValue);
}
else
{
Debug.Assert(false, "unrecognized DocValues.Type: " + dvType);
}
}
}
public override void Flush(SegmentWriteState state)
{
if (Writers.Count > 0)
{
DocValuesFormat fmt = state.SegmentInfo.Codec.DocValuesFormat();
DocValuesConsumer dvConsumer = fmt.FieldsConsumer(state);
bool success = false;
try
{
foreach (DocValuesWriter writer in Writers.Values)
{
writer.Finish(state.SegmentInfo.DocCount);
writer.Flush(state, dvConsumer);
}
// TODO: catch missing DV fields here? else we have
// null/"" depending on how docs landed in segments?
// but we can't detect all cases, and we should leave
// this behavior undefined. dv is not "schemaless": its column-stride.
Writers.Clear();
success = true;
}
finally
{
if (success)
{
IOUtils.Close(dvConsumer);
}
else
{
IOUtils.CloseWhileHandlingException(dvConsumer);
}
}
}
}
internal void AddBinaryField(FieldInfo fieldInfo, int docID, BytesRef value)
{
DocValuesWriter writer;
Writers.TryGetValue(fieldInfo.Name, out writer);
BinaryDocValuesWriter binaryWriter;
if (writer == null)
{
binaryWriter = new BinaryDocValuesWriter(fieldInfo, BytesUsed);
Writers[fieldInfo.Name] = binaryWriter;
}
else if (!(writer is BinaryDocValuesWriter))
{
throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to binary");
}
else
{
binaryWriter = (BinaryDocValuesWriter)writer;
}
binaryWriter.AddValue(docID, value);
}
internal void AddSortedField(FieldInfo fieldInfo, int docID, BytesRef value)
{
DocValuesWriter writer;
Writers.TryGetValue(fieldInfo.Name, out writer);
SortedDocValuesWriter sortedWriter;
if (writer == null)
{
sortedWriter = new SortedDocValuesWriter(fieldInfo, BytesUsed);
Writers[fieldInfo.Name] = sortedWriter;
}
else if (!(writer is SortedDocValuesWriter))
{
throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to sorted");
}
else
{
sortedWriter = (SortedDocValuesWriter)writer;
}
sortedWriter.AddValue(docID, value);
}
internal void AddSortedSetField(FieldInfo fieldInfo, int docID, BytesRef value)
{
DocValuesWriter writer;
Writers.TryGetValue(fieldInfo.Name, out writer);
SortedSetDocValuesWriter sortedSetWriter;
if (writer == null)
{
sortedSetWriter = new SortedSetDocValuesWriter(fieldInfo, BytesUsed);
Writers[fieldInfo.Name] = sortedSetWriter;
}
else if (!(writer is SortedSetDocValuesWriter))
{
throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to sorted");
}
else
{
sortedSetWriter = (SortedSetDocValuesWriter)writer;
}
sortedSetWriter.AddValue(docID, value);
}
internal void AddNumericField(FieldInfo fieldInfo, int docID, long value)
{
DocValuesWriter writer;
Writers.TryGetValue(fieldInfo.Name, out writer);
NumericDocValuesWriter numericWriter;
if (writer == null)
{
numericWriter = new NumericDocValuesWriter(fieldInfo, BytesUsed, true);
Writers[fieldInfo.Name] = numericWriter;
}
else if (!(writer is NumericDocValuesWriter))
{
throw new System.ArgumentException("Incompatible DocValues type: field \"" + fieldInfo.Name + "\" changed from " + GetTypeDesc(writer) + " to numeric");
}
else
{
numericWriter = (NumericDocValuesWriter)writer;
}
numericWriter.AddValue(docID, value);
}
private string GetTypeDesc(DocValuesWriter obj)
{
if (obj is BinaryDocValuesWriter)
{
return "binary";
}
else if (obj is NumericDocValuesWriter)
{
return "numeric";
}
else
{
Debug.Assert(obj is SortedDocValuesWriter);
return "sorted";
}
}
public override void Abort()
{
foreach (DocValuesWriter writer in Writers.Values)
{
try
{
writer.Abort();
}
catch (Exception t)
{
}
}
Writers.Clear();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.HSSF.UserModel
{
using System;
using System.Text;
using System.IO;
using NPOI.DDF;
using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using NPOI.SS.Util;
using System.Drawing;
/// <summary>
/// Represents a escher picture. Eg. A GIF, JPEG etc...
/// @author Glen Stampoultzis
/// @author Yegor Kozlov (yegor at apache.org)
/// </summary>
public class HSSFPicture : HSSFSimpleShape, IPicture
{
//int pictureIndex;
//HSSFPatriarch patriarch;
private static POILogger logger = POILogFactory.GetLogger(typeof(HSSFPicture));
public HSSFPicture(EscherContainerRecord spContainer, ObjRecord objRecord)
: base(spContainer, objRecord)
{
}
/// <summary>
/// Constructs a picture object.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="anchor">The anchor.</param>
public HSSFPicture(HSSFShape parent, HSSFAnchor anchor)
: base(parent, anchor)
{
base.ShapeType = (OBJECT_TYPE_PICTURE);
CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord)GetObjRecord().SubRecords[0];
cod.ObjectType = CommonObjectType.Picture;
}
protected override EscherContainerRecord CreateSpContainer()
{
EscherContainerRecord spContainer = base.CreateSpContainer();
EscherOptRecord opt = (EscherOptRecord)spContainer.GetChildById(EscherOptRecord.RECORD_ID);
opt.RemoveEscherProperty(EscherProperties.LINESTYLE__LINEDASHING);
opt.RemoveEscherProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH);
spContainer.RemoveChildRecord(spContainer.GetChildById(EscherTextboxRecord.RECORD_ID));
return spContainer;
}
/// <summary>
/// Reset the image to the dimension of the embedded image
/// </summary>
/// <remarks>
/// Please note, that this method works correctly only for workbooks
/// with default font size (Arial 10pt for .xls).
/// If the default font is changed the resized image can be streched vertically or horizontally.
/// </remarks>
public void Resize()
{
Resize(Double.MaxValue);
}
/// <summary>
/// Resize the image proportionally.
/// </summary>
/// <param name="scale">scale</param>
/// <seealso cref="Resize(double, double)"/>
public void Resize(double scale)
{
Resize(scale, scale);
}
/**
* Resize the image
* <p>
* Please note, that this method works correctly only for workbooks
* with default font size (Arial 10pt for .xls).
* If the default font is changed the resized image can be streched vertically or horizontally.
* </p>
* <p>
* <code>resize(1.0,1.0)</code> keeps the original size,<br/>
* <code>resize(0.5,0.5)</code> resize to 50% of the original,<br/>
* <code>resize(2.0,2.0)</code> resizes to 200% of the original.<br/>
* <code>resize({@link Double#MAX_VALUE},{@link Double#MAX_VALUE})</code> resizes to the dimension of the embedded image.
* </p>
*
* @param scaleX the amount by which the image width is multiplied relative to the original width.
* @param scaleY the amount by which the image height is multiplied relative to the original height.
*/
public void Resize(double scaleX, double scaleY)
{
HSSFClientAnchor anchor = (HSSFClientAnchor)ClientAnchor;
anchor.AnchorType = AnchorType.MoveDontResize;
HSSFClientAnchor pref = GetPreferredSize(scaleX, scaleY) as HSSFClientAnchor;
int row2 = anchor.Row1 + (pref.Row2 - pref.Row1);
int col2 = anchor.Col1 + (pref.Col2 - pref.Col1);
anchor.Col2=((short)col2);
// anchor.setDx1(0);
anchor.Dx2=(pref.Dx2);
anchor.Row2 = (row2);
// anchor.setDy1(0);
anchor.Dy2 = (pref.Dy2);
}
/// <summary>
/// Gets or sets the index of the picture.
/// </summary>
/// <value>The index of the picture.</value>
public int PictureIndex
{
get
{
EscherSimpleProperty property = (EscherSimpleProperty)GetOptRecord().Lookup(EscherProperties.BLIP__BLIPTODISPLAY);
if (null == property)
{
return -1;
}
return property.PropertyValue;
}
set
{
SetPropertyValue(new EscherSimpleProperty(EscherProperties.BLIP__BLIPTODISPLAY, false, true, value));
}
}
/**
* Calculate the preferred size for this picture.
*
* @param scale the amount by which image dimensions are multiplied relative to the original size.
* @return HSSFClientAnchor with the preferred size for this image
* @since POI 3.0.2
*/
public IClientAnchor GetPreferredSize(double scale)
{
return GetPreferredSize(scale, scale);
}
/// <summary>
/// Calculate the preferred size for this picture.
/// </summary>
/// <param name="scaleX">the amount by which image width is multiplied relative to the original width.</param>
/// <param name="scaleY">the amount by which image height is multiplied relative to the original height.</param>
/// <returns>HSSFClientAnchor with the preferred size for this image</returns>
public IClientAnchor GetPreferredSize(double scaleX, double scaleY)
{
ImageUtils.SetPreferredSize(this, scaleX, scaleY);
return ClientAnchor;
}
/// <summary>
/// Calculate the preferred size for this picture.
/// </summary>
/// <returns>HSSFClientAnchor with the preferred size for this image</returns>
public IClientAnchor GetPreferredSize()
{
return GetPreferredSize(1.0);
}
/// <summary>
/// The metadata of PNG and JPEG can contain the width of a pixel in millimeters.
/// Return the the "effective" dpi calculated as
/// <c>25.4/HorizontalPixelSize</c>
/// and
/// <c>25.4/VerticalPixelSize</c>
/// . Where 25.4 is the number of mm in inch.
/// </summary>
/// <param name="r">The image.</param>
/// <returns>the resolution</returns>
protected Size GetResolution(Image r)
{
//int hdpi = 96, vdpi = 96;
//double mm2inch = 25.4;
return new Size((int)r.HorizontalResolution, (int)r.VerticalResolution);
}
/// <summary>
/// Return the dimension of the embedded image in pixel
/// </summary>
/// <returns>image dimension</returns>
public Size GetImageDimension()
{
InternalWorkbook iwb = (_patriarch.Sheet.Workbook as HSSFWorkbook).Workbook;
EscherBSERecord bse = iwb.GetBSERecord(PictureIndex);
byte[] data = bse.BlipRecord.PictureData;
//int type = bse.BlipTypeWin32;
using (MemoryStream ms = new MemoryStream(data))
{
using (Image img = Image.FromStream(ms))
{
return img.Size;
}
}
}
/**
* Return picture data for this shape
*
* @return picture data for this shape
*/
public IPictureData PictureData
{
get
{
InternalWorkbook iwb = ((_patriarch.Sheet.Workbook) as HSSFWorkbook).Workbook;
EscherBSERecord bse = iwb.GetBSERecord(PictureIndex);
EscherBlipRecord blipRecord = bse.BlipRecord;
return new HSSFPictureData(blipRecord);
}
}
internal override void AfterInsert(HSSFPatriarch patriarch)
{
EscherAggregate agg = patriarch.GetBoundAggregate();
agg.AssociateShapeToObjRecord(GetEscherContainer().GetChildById(EscherClientDataRecord.RECORD_ID), GetObjRecord());
EscherBSERecord bse =
(patriarch.Sheet.Workbook as HSSFWorkbook).Workbook.GetBSERecord(PictureIndex);
bse.Ref = (bse.Ref + 1);
}
/**
* The color applied to the lines of this shape.
*/
public String FileName
{
get
{
EscherComplexProperty propFile = (EscherComplexProperty)GetOptRecord().Lookup(
EscherProperties.BLIP__BLIPFILENAME);
return (null == propFile) ? "" : Trim(StringUtil.GetFromUnicodeLE(propFile.ComplexData));
}
set
{
// TODO: add trailing \u0000?
byte[] bytes = StringUtil.GetToUnicodeLE(value);
EscherComplexProperty prop = new EscherComplexProperty(EscherProperties.BLIP__BLIPFILENAME, true, bytes);
SetPropertyValue(prop);
}
}
private String Trim(string value)
{
int end = value.Length;
int st = 0;
//int off = offset; /* avoid getfield opcode */
char[] val = value.ToCharArray(); /* avoid getfield opcode */
while ((st < end) && (val[st] <= ' '))
{
st++;
}
while ((st < end) && (val[end - 1] <= ' '))
{
end--;
}
return ((st > 0) || (end < value.Length)) ? value.Substring(st, end - st) : value;
}
public override int ShapeType
{
get { return base.ShapeType; }
set
{
throw new InvalidOperationException("Shape type can not be changed in " + this.GetType().Name);
}
}
internal override HSSFShape CloneShape()
{
EscherContainerRecord spContainer = new EscherContainerRecord();
byte[] inSp = GetEscherContainer().Serialize();
spContainer.FillFields(inSp, 0, new DefaultEscherRecordFactory());
ObjRecord obj = (ObjRecord)GetObjRecord().CloneViaReserialise();
return new HSSFPicture(spContainer, obj);
}
/**
* @return the anchor that is used by this picture.
*/
public IClientAnchor ClientAnchor
{
get
{
HSSFAnchor a = Anchor;
return (a is HSSFClientAnchor) ? (HSSFClientAnchor)a : null;
}
}
/**
* @return the sheet which contains the picture shape
*/
public ISheet Sheet
{
get
{
return Patriarch.Sheet;
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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 UnityEngine;
using System.Collections; // required for Coroutines
/// <summary>
/// Fades the screen from black after a new scene is loaded. Fade can also be controlled mid-scene using SetUIFade and SetFadeLevel
/// </summary>
public class OVRScreenFade : MonoBehaviour
{
[Tooltip("Fade duration")]
public float fadeTime = 2.0f;
[Tooltip("Screen color at maximum fade")]
public Color fadeColor = new Color(0.01f, 0.01f, 0.01f, 1.0f);
public bool fadeOnStart = true;
/// <summary>
/// The render queue used by the fade mesh. Reduce this if you need to render on top of it.
/// </summary>
public int renderQueue = 5000;
private float uiFadeAlpha = 0;
private MeshRenderer fadeRenderer;
private MeshFilter fadeMesh;
private Material fadeMaterial = null;
private bool isFading = false;
public float currentAlpha { get; private set; }
void Awake()
{
// create the fade material
fadeMaterial = new Material(Shader.Find("Oculus/Unlit Transparent Color"));
fadeMesh = gameObject.AddComponent<MeshFilter>();
fadeRenderer = gameObject.AddComponent<MeshRenderer>();
var mesh = new Mesh();
fadeMesh.mesh = mesh;
Vector3[] vertices = new Vector3[4];
float width = 2f;
float height = 2f;
float depth = 1f;
vertices[0] = new Vector3(-width, -height, depth);
vertices[1] = new Vector3(width, -height, depth);
vertices[2] = new Vector3(-width, height, depth);
vertices[3] = new Vector3(width, height, depth);
mesh.vertices = vertices;
int[] tri = new int[6];
tri[0] = 0;
tri[1] = 2;
tri[2] = 1;
tri[3] = 2;
tri[4] = 3;
tri[5] = 1;
mesh.triangles = tri;
Vector3[] normals = new Vector3[4];
normals[0] = -Vector3.forward;
normals[1] = -Vector3.forward;
normals[2] = -Vector3.forward;
normals[3] = -Vector3.forward;
mesh.normals = normals;
Vector2[] uv = new Vector2[4];
uv[0] = new Vector2(0, 0);
uv[1] = new Vector2(1, 0);
uv[2] = new Vector2(0, 1);
uv[3] = new Vector2(1, 1);
mesh.uv = uv;
SetFadeLevel(0);
}
/// <summary>
/// Start a fade out
/// </summary>
public void FadeOut()
{
StartCoroutine(Fade(0,1));
}
/// <summary>
/// Starts a fade in when a new level is loaded
/// </summary>
void OnLevelFinishedLoading(int level)
{
StartCoroutine(Fade(1,0));
}
/// <summary>
/// Automatically starts a fade in
/// </summary>
void Start()
{
if (fadeOnStart)
{
StartCoroutine(Fade(1,0));
}
}
void OnEnable()
{
if (!fadeOnStart)
{
SetFadeLevel(0);
}
}
/// <summary>
/// Cleans up the fade material
/// </summary>
void OnDestroy()
{
if (fadeRenderer != null)
Destroy(fadeRenderer);
if (fadeMaterial != null)
Destroy(fadeMaterial);
if (fadeMesh != null)
Destroy(fadeMesh);
}
/// <summary>
/// Set the UI fade level - fade due to UI in foreground
/// </summary>
public void SetUIFade(float level)
{
uiFadeAlpha = Mathf.Clamp01(level);
SetMaterialAlpha();
}
/// <summary>
/// Override current fade level
/// </summary>
/// <param name="level"></param>
public void SetFadeLevel(float level)
{
currentAlpha = level;
SetMaterialAlpha();
}
/// <summary>
/// Fades alpha from 1.0 to 0.0
/// </summary>
IEnumerator Fade(float startAlpha, float endAlpha)
{
float elapsedTime = 0.0f;
while (elapsedTime < fadeTime)
{
elapsedTime += Time.deltaTime;
currentAlpha = Mathf.Lerp(startAlpha, endAlpha, Mathf.Clamp01(elapsedTime / fadeTime));
SetMaterialAlpha();
yield return new WaitForEndOfFrame();
}
}
/// <summary>
/// Update material alpha. UI fade and the current fade due to fade in/out animations (or explicit control)
/// both affect the fade. (The max is taken)
/// </summary>
private void SetMaterialAlpha()
{
Color color = fadeColor;
color.a = Mathf.Max(currentAlpha, uiFadeAlpha);
isFading = color.a > 0;
if (fadeMaterial != null)
{
fadeMaterial.color = color;
fadeMaterial.renderQueue = renderQueue;
fadeRenderer.material = fadeMaterial;
fadeRenderer.enabled = isFading;
}
}
}
| |
// 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;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Xsl;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Localization;
namespace LocUtil
{
class Values
{
private object val;
private string comment;
public Values(object val, string comment)
{
this.val = val;
this.comment = comment;
}
public object Val
{
get { return val; }
}
public string Comment
{
get { return comment; }
}
}
class AppMain
{
const string COMMENT_NAMESPACE = "http://OpenLiveWriter.spaces.live.com/#comment";
const string COMMENT_ATTRIBUTE = "Comment";
[STAThread]
static int Main(string[] args)
{
if (args.Length == 1 && args[0].ToLowerInvariant() == "/validateall")
{
return ValidateAll() ? 0 : 1;
}
CommandLineOptions clo = new CommandLineOptions(
new ArgSpec("c", ArgSpec.Options.Multiple, "Command XML input file(s)"),
new ArgSpec("r", ArgSpec.Options.Multiple, "Ribbon XML input file"),
new ArgSpec("d", ArgSpec.Options.Multiple, "DisplayMessage XML input file(s)"),
new ArgSpec("s", ArgSpec.Options.Multiple, "Strings CSV input file(s)"),
new ArgSpec("cenum", ArgSpec.Options.Default, "Path to CommandId.cs enum output file"),
new ArgSpec("denum", ArgSpec.Options.Default, "Path to MessageId.cs enum output file"),
new ArgSpec("senum", ArgSpec.Options.Default, "Path to StringId.cs enum output file"),
new ArgSpec("props", ArgSpec.Options.Required, "Path to Properties.resx output file"),
new ArgSpec("propsnonloc", ArgSpec.Options.Required, "Path to PropertiesNonLoc.resx output file"),
new ArgSpec("strings", ArgSpec.Options.Required, "Path to Strings.resx output file")
);
if (!clo.Parse(args, true))
{
Console.Error.WriteLine(clo.ErrorMessage);
return 1;
}
Hashtable pairsLoc = new Hashtable();
Hashtable pairsNonLoc = new Hashtable();
string[] commandFiles = (string[])ArrayHelper.Narrow(clo.GetValues("c"), typeof(string));
string[] dialogFiles = (string[])ArrayHelper.Narrow(clo.GetValues("d"), typeof(string));
string[] ribbonFiles = (string[])ArrayHelper.Narrow(clo.GetValues("r"), typeof(string));
if (commandFiles.Length + dialogFiles.Length == 0)
{
Console.Error.WriteLine("No input files were specified.");
return 1;
}
HashSet ribbonIds;
Hashtable ribbonValues;
Console.WriteLine("Parsing commands from " + StringHelper.Join(commandFiles, ";"));
if (!ParseRibbonXml(ribbonFiles, pairsLoc, pairsNonLoc, typeof(Command), "//ribbon:Command", "Command.{0}.{1}", out ribbonIds, out ribbonValues))
return 1;
HashSet commandIds;
Console.WriteLine("Parsing commands from " + StringHelper.Join(commandFiles, ";"));
string[] transformedCommandFiles = commandFiles;
try
{
// Transform the files
XslCompiledTransform xslTransform = new XslCompiledTransform(true);
string xslFile = Path.GetFullPath("Commands.xsl");
for (int i = 0; i < commandFiles.Length; i++)//string filename in commandFiles)
{
string inputFile = Path.GetFullPath(commandFiles[i]);
if (!File.Exists(inputFile))
throw new ConfigurationErrorsException("File not found: " + inputFile);
xslTransform.Load(xslFile);
string transformedFile = inputFile.Replace(".xml", ".transformed.xml");
xslTransform.Transform(inputFile, transformedFile);
transformedCommandFiles[i] = transformedFile;
}
}
catch (Exception ex)
{
Console.Error.WriteLine("Failed to transform file: " + ex);
return 1;
}
if (!ParseCommandXml(transformedCommandFiles, pairsLoc, pairsNonLoc, typeof(Command), "/Commands/Command", "Command.{0}.{1}", out commandIds))
return 1;
HashSet dialogIds;
Console.WriteLine("Parsing messages from " + StringHelper.Join(dialogFiles, ";"));
if (!ParseCommandXml(dialogFiles, pairsLoc, pairsNonLoc, typeof(DisplayMessage), "/Messages/Message", "DisplayMessage.{0}.{1}", out dialogIds))
return 1;
string propsFile = (string)clo.GetValue("props", null);
Console.WriteLine("Writing localizable resources to " + propsFile);
WritePairs(pairsLoc, propsFile, true);
string propsNonLocFile = (string)clo.GetValue("propsnonloc", null);
Console.WriteLine("Writing non-localizable resources to " + propsNonLocFile);
WritePairs(pairsNonLoc, propsNonLocFile, false);
if (clo.IsArgPresent("cenum"))
{
string cenum = (string)clo.GetValue("cenum", null);
Console.WriteLine("Generating CommandId enum file " + cenum);
// commandId: command name
// ribbonValues: command name --> resource id
commandIds.AddAll(ribbonIds);
if (!GenerateEnum(commandIds, "CommandId", cenum, null, ribbonValues))
return 1;
}
if (clo.IsArgPresent("denum"))
{
string denum = (string)clo.GetValue("denum", null);
Console.WriteLine("Generating MessageId enum file " + denum);
if (!GenerateEnum(dialogIds, "MessageId", denum, null, null))
return 1;
}
if (clo.IsArgPresent("s"))
{
Hashtable pairs = new Hashtable();
Console.WriteLine("Reading strings");
foreach (string sPath in clo.GetValues("s"))
{
using (CsvParser csvParser = new CsvParser(new StreamReader(new FileStream(Path.GetFullPath(sPath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.Default), true))
{
foreach (string[] line in csvParser)
{
string value = line[1];
value = value.Replace(((char)8230) + "", "..."); // undo ellipses
string comment = (line.Length > 2) ? line[2] : "";
pairs.Add(line[0], new Values(value, comment));
}
}
}
if (clo.IsArgPresent("senum"))
{
string senum = (string)clo.GetValue("senum", null);
Console.WriteLine("Writing StringId enum file " + senum);
if (!GenerateEnum(new HashSet(pairs), "StringId", senum, pairs, null))
return 1;
}
if (clo.IsArgPresent("strings"))
{
string stringsResx = (string)clo.GetValue("strings", null);
Console.WriteLine("Writing " + pairs.Count + " localizable strings to " + stringsResx);
WritePairs(pairs, stringsResx, false);
}
}
return 0;
}
private static bool ValidateAll()
{
bool success = true;
string basePath = Path.Combine(Environment.GetEnvironmentVariable("INETROOT"), @"client\writer\intl\lba\");
foreach (string dir in Directory.GetDirectories(basePath))
{
string name = Path.GetFileName(dir);
if (name != "default")
{
if (name == "zh-chs")
name = "zh-cn";
else if (name == "zh-cht")
name = "zh-tw";
try
{
Thread.CurrentThread.CurrentUICulture = CultureHelper.GetBestCulture(name);
string[] errors = Res.Validate();
if (errors.Length > 0)
{
success = false;
Console.Error.WriteLine(name);
foreach (string err in errors)
Console.Error.WriteLine("\t" + err);
Console.Error.WriteLine();
}
}
catch (Exception e)
{
Console.Error.WriteLine("ERROR [" + name + "]: " + e);
Console.Error.WriteLine();
success = false;
}
}
}
return success;
}
private static void WritePairs(Hashtable pairs, string path, bool includeFonts)
{
if (includeFonts)
{
pairs = (Hashtable)pairs.Clone();
// HACK: hard-code invariant font resource values
pairs.Add("Font", new Values("Segoe UI", "The font to be used to render all text in the product in Windows Vista and later. DO NOT specify more than one font!"));
pairs.Add("Font.Size.Normal", new Values("9", "The default font size used throughout the product in Windows Vista and later"));
pairs.Add("Font.Size.Large", new Values("10", "The size of titles in some error dialogs in Windows Vista and later"));
pairs.Add("Font.Size.XLarge", new Values("11", "The size of titles in some error dialogs in Windows Vista and later. Also used for the text that shows an error on the video publish place holder."));
pairs.Add("Font.Size.XXLarge", new Values("12", "The size of panel titles in the Preferences dialog in Windows Vista and later. Also the size of the text used to show the status on the video before publish."));
pairs.Add("Font.Size.Heading", new Values("12", "The size of the header text in the Add Weblog wizard and Welcome wizard in Windows Vista and later"));
pairs.Add("Font.Size.GiantHeading", new Values("15.75", "The size of the header text in the Add Weblog wizard and Welcome wizard in Windows Vista and later"));
pairs.Add("Font.Size.ToolbarFormatButton", new Values("15", "The size of the font used to draw the edit toolbar's B(old), I(talic), U(nderline), and S(trikethrough) in Windows Vista and later. THIS SIZE IS IN PIXELS, NOT POINTS! Example: 14.75"));
pairs.Add("Font.Size.PostSplitCaption", new Values("7", "The size of the font used to draw the 'More...' divider when using the Format | Split Post feature in Windows Vista and later."));
pairs.Add("Font.Size.Small", new Values("7", "The size used for small messages, such as please respect copyright, in Windows Vista and later. "));
// HACK: hard-code default sidebar size
pairs.Add("Sidebar.WidthInPixels", new Values("200", "The width of the sidebar, in pixels."));
// HACK: hard-code wizard height
pairs.Add("ConfigurationWizard.Height", new Values("380", "The height of the configuration wizard, in pixels."));
}
pairs.Add("Culture.UseItalics", new Values("True", "Whether or not the language uses italics"));
ArrayList keys = new ArrayList(pairs.Keys);
keys.Sort(new CaseInsensitiveComparer(CultureInfo.InvariantCulture));
//using (TextWriter tw = new StreamWriter(path, false))
StringBuilder xmlBuffer = new StringBuilder();
using (TextWriter tw = new StringWriter(xmlBuffer))
{
ResXResourceWriter writer = new ResXResourceWriter(tw);
foreach (string key in keys)
{
writer.AddResource(key, ((Values)pairs[key]).Val);
}
writer.Close();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlBuffer.ToString());
foreach (XmlElement dataNode in xmlDoc.SelectNodes("/root/data"))
{
string name = dataNode.GetAttribute("name");
if (pairs.ContainsKey(name))
{
string comment = ((Values)pairs[name]).Comment;
if (comment != null && comment.Length > 0)
{
XmlElement commentEl = xmlDoc.CreateElement("comment");
XmlText text = xmlDoc.CreateTextNode(comment);
commentEl.AppendChild(text);
dataNode.AppendChild(commentEl);
}
}
}
xmlDoc.Save(path);
}
// @RIBBON TODO: For now the union of the command in Commands.xml and Ribbon.xml will go into the CommandId enum.
private static bool GenerateEnum(HashSet commandIds, string enumName, string enumPath, Hashtable descriptions, Hashtable values)
{
const string TEMPLATE = @"namespace OpenLiveWriter.Localization
{{
public enum {0}
{{
None,
{1}
}}
}}
";
ArrayList commandList = commandIds.ToArrayList();
commandList.Sort(new CaseInsensitiveComparer(CultureInfo.InvariantCulture));
using (StreamWriter sw = new StreamWriter(Path.GetFullPath(enumPath)))
{
if (descriptions == null && values == null)
{
sw.Write(string.Format(CultureInfo.InvariantCulture, TEMPLATE, enumName, StringHelper.Join(commandList.ToArray(), ",\r\n\t\t")));
}
else if (descriptions == null)
{
// insert values
const string VALUE_TEMPLATE = "{0} = {1}";
const string VALUELESS_TEMPLATE = "{0}";
ArrayList pairs = new ArrayList();
ArrayList unmappedCommands = new ArrayList();
foreach (string command in commandList.ToArray())
{
string value = values[command] as string;
if (value != null)
{
pairs.Add(string.Format(CultureInfo.InvariantCulture, VALUE_TEMPLATE, command, value));
}
else
{
ConsoleColor color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("ERROR: Command " + command + " is missing an Id (required for instrumentation)");
Console.Beep();
Console.ForegroundColor = color;
Console.Error.Flush();
// This command is not mapped to a ribbon command
// We'll keep track of these and put them at the end
unmappedCommands.Add(command);
}
}
if (unmappedCommands.Count > 0)
{
return false;
}
// Now add the commands that were not mapped to a value
int index = 1;
foreach (string command in unmappedCommands.ToArray())
{
if (index == 1)
pairs.Add(string.Format(CultureInfo.InvariantCulture, VALUE_TEMPLATE, command, index));
else
pairs.Add(string.Format(CultureInfo.InvariantCulture, VALUELESS_TEMPLATE, command));
index++;
}
sw.Write(string.Format(CultureInfo.InvariantCulture, TEMPLATE, enumName, StringHelper.Join(pairs.ToArray(), ",\r\n\t\t")));
}
else if (values == null)
{
const string DESC_TEMPLATE = @"/// <summary>
/// {0}
/// </summary>
{1}";
ArrayList descs = new ArrayList();
foreach (string command in commandList.ToArray())
{
string description = ((Values)descriptions[command]).Val as string;
description = description.Replace("\n", "\n\t\t/// ");
descs.Add(string.Format(CultureInfo.InvariantCulture, DESC_TEMPLATE, description, command));
}
sw.Write(string.Format(CultureInfo.InvariantCulture, TEMPLATE, enumName, StringHelper.Join(descs.ToArray(), ",\r\n\t\t")));
}
else
{
// insert values and descriptions
throw new NotImplementedException("Inserting values and descriptions not supported presently");
}
}
return true;
}
private static bool ParseRibbonXml(string[] inputFiles, Hashtable pairs, Hashtable pairsNonLoc, Type t, string xpath, string KEY_FORMAT, out HashSet ids, out Hashtable values)
{
// Add to the proptable
Hashtable propTable = new Hashtable();
foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
propTable.Add(prop.Name, prop);
}
ids = new HashSet();
values = new Hashtable();
foreach (string relativeInputFile in inputFiles)
{
string inputFile = Path.GetFullPath(relativeInputFile);
try
{
if (!File.Exists(inputFile))
throw new ConfigurationErrorsException("File not found");
XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());
nsm.AddNamespace(RibbonMarkup.XPathPrefix, RibbonMarkup.NamespaceUri);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(inputFile);
foreach (XmlElement el in xmlDoc.SelectNodes(xpath, nsm))
{
string id = el.GetAttribute("Id");
string symbol = el.GetAttribute("Symbol");
if (id == "")
throw new ConfigurationErrorsException(
string.Format(CultureInfo.CurrentCulture, "The following command is missing an identifier:\r\n{0}", el.OuterXml));
// RibbonDUI.js requires that command names begin with the prefix "cmd".
// We will strip that prefix when generating the CommandId enum.
int cmdIndex = symbol.IndexOf("cmd");
if (cmdIndex >= 0)
{
symbol = symbol.Substring(cmdIndex + 3);
}
if (!ids.Add(symbol))
throw new ConfigurationErrorsException("Duplicate command: " + symbol + " with id " + id);
values.Add(symbol, id);
foreach (XmlAttribute attr in el.Attributes)
{
if (attr.NamespaceURI.Length != 0)
continue;
string name = attr.Name;
object val;
PropertyInfo thisProp = propTable[name] as PropertyInfo;
if (thisProp == null)
continue; // This attribute does not have a corresponding property in the type.
if (thisProp.PropertyType.IsPrimitive)
{
try
{
val = Convert.ChangeType(attr.Value, thisProp.PropertyType).ToString();
}
catch (ArgumentException)
{
throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "Invalid attribute value: {0}=\"{1}\"", attr.Name, attr.Value));
}
}
else if (thisProp.PropertyType == typeof(string))
{
val = attr.Value;
}
else
{
throw new ConfigurationErrorsException("Unexpected attribute: " + attr.Name);
}
string comment = GetComment(el, name);
object[] locAttr = thisProp.GetCustomAttributes(typeof(LocalizableAttribute), true);
bool isNonLoc = locAttr.Length == 0 || !((LocalizableAttribute)locAttr[0]).IsLocalizable;
if (isNonLoc)
pairsNonLoc.Add(string.Format(CultureInfo.InvariantCulture, KEY_FORMAT, symbol, name), new Values(val, comment));
else
pairs.Add(string.Format(CultureInfo.InvariantCulture, KEY_FORMAT, symbol, name), new Values(val, comment));
}
}
}
catch (ConfigurationErrorsException ce)
{
Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "Error in file {0}: {1}", inputFile, ce.Message));
return false;
}
}
return true;
}
private static bool ParseCommandXml(string[] inputFiles, Hashtable pairs, Hashtable pairsNonLoc, Type t, string xpath, string KEY_FORMAT, out HashSet ids)
{
bool seenMenu = false;
Hashtable propTable = new Hashtable();
foreach (PropertyInfo prop in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
propTable.Add(prop.Name, prop);
}
ids = new HashSet();
foreach (string relativeInputFile in inputFiles)
{
string inputFile = Path.GetFullPath(relativeInputFile);
try
{
if (!File.Exists(inputFile))
throw new ConfigurationErrorsException("File not found");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(inputFile);
foreach (XmlElement el in xmlDoc.SelectNodes(xpath))
{
string id = el.GetAttribute("Identifier");
if (id == "")
throw new ConfigurationErrorsException(
String.Format(CultureInfo.CurrentCulture, "The following command is missing an identifier:\r\n{0}", el.OuterXml));
if (!ids.Add(id))
throw new ConfigurationErrorsException("Duplicate command identifier: " + id);
foreach (XmlAttribute attr in el.Attributes)
{
if (attr.NamespaceURI.Length != 0)
continue;
string name = attr.Name;
if (name == "DebugOnly" || name == "Identifier")
continue;
object val;
PropertyInfo thisProp = propTable[name] as PropertyInfo;
if (thisProp == null)
throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, "Attribute {0} does not have a corresponding property", name));
if (thisProp.PropertyType.IsEnum)
{
try
{
val = Enum.Parse(thisProp.PropertyType, attr.Value, false).ToString();
}
catch (ArgumentException)
{
throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "Invalid attribute value: {0}=\"{1}\"", attr.Name, attr.Value));
}
}
else if (thisProp.PropertyType.IsPrimitive)
{
try
{
val = Convert.ChangeType(attr.Value, thisProp.PropertyType).ToString();
}
catch (ArgumentException)
{
throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "Invalid attribute value: {0}=\"{1}\"", attr.Name, attr.Value));
}
}
else if (thisProp.PropertyType == typeof(string))
{
val = attr.Value;
}
else
{
throw new ConfigurationErrorsException("Unexpected attribute: " + attr.Name);
}
string comment = GetComment(el, name);
object[] locAttr = thisProp.GetCustomAttributes(typeof(LocalizableAttribute), true);
bool isNonLoc = locAttr.Length == 0 || !((LocalizableAttribute)locAttr[0]).IsLocalizable;
if (isNonLoc)
pairsNonLoc.Add(string.Format(CultureInfo.InvariantCulture, KEY_FORMAT, id, name), new Values(val, comment));
else
pairs.Add(string.Format(CultureInfo.InvariantCulture, KEY_FORMAT, id, name), new Values(val, comment));
}
}
foreach (XmlElement mainMenuEl in xmlDoc.SelectNodes("/Commands/MainMenu"))
{
if (seenMenu)
throw new ConfigurationErrorsException("Duplicate main menu definition detected");
seenMenu = true;
Console.WriteLine("Parsing main menu definition");
StringBuilder menuStructure = new StringBuilder();
BuildMenuString(menuStructure, mainMenuEl, ids, pairs);
pairsNonLoc.Add("MainMenuStructure", new Values(menuStructure.ToString(), ""));
}
}
catch (ConfigurationErrorsException ce)
{
Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "Error in file {0}: {1}", inputFile, ce.Message));
return false;
}
}
return true;
}
/// <summary>
/// Gets a comment for the specified property.
/// </summary>
private static string GetComment(XmlElement element, string property)
{
// Legacy XML files use a special namespace for comments (e.g. <Command MenuText="..." comment:MenuText="..." />)
string comment = element.GetAttribute(property, COMMENT_NAMESPACE);
// Ribbon XML files use a Comment attribute (e.g. <Command Comment=".." />)
if (String.IsNullOrEmpty(comment) && element.HasAttribute("Comment"))
comment = element.GetAttribute("Comment");
return comment;
}
private static void BuildMenuString(StringBuilder structure, XmlElement el, HashSet commandIds, Hashtable pairs)
{
int startLen = structure.Length;
int pos = 0;
bool lastWasSeparator = false;
foreach (XmlNode childNode in el.ChildNodes)
{
XmlElement childEl = childNode as XmlElement;
if (childEl == null)
continue;
if (childEl.HasAttribute("Position"))
pos = int.Parse(childEl.GetAttribute("Position"), CultureInfo.InvariantCulture);
string separator = "";
if (childEl.Name == "Separator")
{
lastWasSeparator = true;
continue;
}
else if (lastWasSeparator)
{
separator = "-";
lastWasSeparator = false;
}
if (childEl.Name == "Menu" || childEl.Name == "Command")
{
if (!childEl.HasAttribute("Identifier"))
throw new ConfigurationErrorsException(childEl.Name + " element was missing required attribute 'Identifier'");
string id = childEl.GetAttribute("Identifier");
if (childEl.Name == "Command")
{
if (!commandIds.Contains(id))
throw new ConfigurationErrorsException("Main menu definition uses unknown command id: " + id);
}
string idWithOrder = string.Format(CultureInfo.InvariantCulture, "{0}{1}@{2}", separator, id, (pos++ * 10));
if (structure.Length != 0)
structure.Append(" ");
switch (childEl.Name)
{
case "Menu":
if (!childEl.HasAttribute("Text"))
throw new ConfigurationErrorsException("Menu with id '" + id + "' was missing the required Text attribute");
string menuText = childEl.GetAttribute("Text");
pairs.Add("MainMenu." + id, new Values(menuText, ""));
structure.Append("(" + idWithOrder);
BuildMenuString(structure, childEl, commandIds, pairs);
structure.Append(")");
break;
case "Command":
structure.Append(idWithOrder);
break;
}
}
else
throw new ConfigurationErrorsException("Unexpected element " + childEl.Name);
}
}
}
}
| |
using System;
using NAudio.Dsp;
namespace NAudio.Wave
{
/// <summary>
/// A simple compressor
/// </summary>
public class SimpleCompressorStream : WaveStream
{
private readonly int bytesPerSample;
private readonly int channels;
private readonly SimpleCompressor simpleCompressor;
private byte[] sourceBuffer; // buffer used by Read function
private WaveStream sourceStream;
/// <summary>
/// Create a new simple compressor stream
/// </summary>
/// <param name="sourceStream">Source stream</param>
public SimpleCompressorStream(WaveStream sourceStream)
{
this.sourceStream = sourceStream;
channels = sourceStream.WaveFormat.Channels;
bytesPerSample = sourceStream.WaveFormat.BitsPerSample/8;
simpleCompressor = new SimpleCompressor(5.0, 10.0, sourceStream.WaveFormat.SampleRate);
simpleCompressor.Threshold = 16;
simpleCompressor.Ratio = 6;
simpleCompressor.MakeUpGain = 16;
}
/// <summary>
/// Make-up Gain
/// </summary>
public double MakeUpGain
{
get { return simpleCompressor.MakeUpGain; }
set
{
lock (this)
{
simpleCompressor.MakeUpGain = value;
}
}
}
/// <summary>
/// Threshold
/// </summary>
public double Threshold
{
get { return simpleCompressor.Threshold; }
set
{
lock (this)
{
simpleCompressor.Threshold = value;
}
}
}
/// <summary>
/// Ratio
/// </summary>
public double Ratio
{
get { return simpleCompressor.Ratio; }
set
{
lock (this)
{
simpleCompressor.Ratio = value;
}
}
}
/// <summary>
/// Attack time
/// </summary>
public double Attack
{
get { return simpleCompressor.Attack; }
set
{
lock (this)
{
simpleCompressor.Attack = value;
}
}
}
/// <summary>
/// Release time
/// </summary>
public double Release
{
get { return simpleCompressor.Release; }
set
{
lock (this)
{
simpleCompressor.Release = value;
}
}
}
/// <summary>
/// Turns gain on or off
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Returns the stream length
/// </summary>
public override long Length
{
get { return sourceStream.Length; }
}
/// <summary>
/// Gets or sets the current position in the stream
/// </summary>
public override long Position
{
get { return sourceStream.Position; }
set
{
lock (this)
{
sourceStream.Position = value;
}
}
}
/// <summary>
/// Gets the WaveFormat of this stream
/// </summary>
public override WaveFormat WaveFormat
{
get { return sourceStream.WaveFormat; }
}
/// <summary>
/// Gets the block alignment for this stream
/// </summary>
public override int BlockAlign
{
get
{
// TODO: investigate forcing 20ms
return sourceStream.BlockAlign;
}
}
/// <summary>
/// Determine whether the stream has the required amount of data.
/// </summary>
/// <param name="count">Number of bytes of data required from the stream.</param>
/// <returns>Flag indicating whether the required amount of data is avialable.</returns>
public override bool HasData(int count)
{
return sourceStream.HasData(count);
}
private void ReadSamples(byte[] buffer, int start, out double left, out double right)
{
if (bytesPerSample == 4)
{
left = BitConverter.ToSingle(buffer, start);
if (channels > 1)
{
right = BitConverter.ToSingle(buffer, start + bytesPerSample);
}
else
{
right = left;
}
}
else if (bytesPerSample == 2)
{
left = BitConverter.ToInt16(buffer, start)/32768.0;
if (channels > 1)
{
right = BitConverter.ToInt16(buffer, start + bytesPerSample)/32768.0;
}
else
{
right = left;
}
}
else
{
throw new InvalidOperationException(String.Format("Unsupported bytes per sample: {0}", bytesPerSample));
}
}
private void WriteSamples(byte[] buffer, int start, double left, double right)
{
if (bytesPerSample == 4)
{
Array.Copy(BitConverter.GetBytes((float) left), 0, buffer, start, bytesPerSample);
if (channels > 1)
{
Array.Copy(BitConverter.GetBytes((float) right), 0, buffer, start + bytesPerSample, bytesPerSample);
}
}
else if (bytesPerSample == 2)
{
Array.Copy(BitConverter.GetBytes((short) (left*32768.0)), 0, buffer, start, bytesPerSample);
if (channels > 1)
{
Array.Copy(BitConverter.GetBytes((short) (right*32768.0)), 0, buffer, start + bytesPerSample,
bytesPerSample);
}
}
}
/// <summary>
/// Reads bytes from this stream
/// </summary>
/// <param name="array">Buffer to read into</param>
/// <param name="offset">Offset in array to read into</param>
/// <param name="count">Number of bytes to read</param>
/// <returns>Number of bytes read</returns>
public override int Read(byte[] array, int offset, int count)
{
lock (this)
{
if (Enabled)
{
if (sourceBuffer == null || sourceBuffer.Length < count)
sourceBuffer = new byte[count];
int sourceBytesRead = sourceStream.Read(sourceBuffer, 0, count);
int sampleCount = sourceBytesRead/(bytesPerSample*channels);
for (int sample = 0; sample < sampleCount; sample++)
{
int start = sample*bytesPerSample*channels;
double in1;
double in2;
ReadSamples(sourceBuffer, start, out in1, out in2);
simpleCompressor.Process(ref in1, ref in2);
WriteSamples(array, offset + start, in1, in2);
}
return count;
}
return sourceStream.Read(array, offset, count);
}
}
/// <summary>
/// Disposes this stream
/// </summary>
/// <param name="disposing">true if the user called this</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Release managed resources.
if (sourceStream != null)
{
sourceStream.Dispose();
sourceStream = null;
}
}
// Release unmanaged resources.
// Set large fields to null.
// Call Dispose on your base class.
base.Dispose(disposing);
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SlimManualResetEvent.cs
//
//
// An manual-reset event that mixes a little spinning with a true Win32 event.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System.Threading
{
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
// a brief amount of spinning that should, on the average, make using the slim event
// cheaper than using Win32 events directly. This can be reset manually, much like
// a Win32 manual-reset would be.
//
// Notes:
// We lazily allocate the Win32 event internally. Therefore, the caller should
// always call Dispose to clean it up, just in case. This API is a no-op of the
// event wasn't allocated, but if it was, ensures that the event goes away
// eagerly, instead of waiting for finalization.
/// <summary>
/// Provides a slimmed down version of <see cref="T:System.Threading.ManualResetEvent"/>.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="ManualResetEventSlim"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="ManualResetEventSlim"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Set = {IsSet}")]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
private const int DEFAULT_SPIN_MP = 10;
private volatile Lock m_lock;
private volatile Condition m_condition;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting.
// -- State -- //
//For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant.
private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below.
//1-bit for signalled state
private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000
private const int SignalledState_ShiftCount = 31;
//1-bit for disposed state
private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000
//11-bits for m_spinCount
private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000
private const int SpinCountState_ShiftCount = 19;
private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047
//19-bits for m_waiters. This allows support of 512K threads waiting which should be ample
private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111
private const int NumWaitersState_ShiftCount = 0;
private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1
// ----------- //
#if DEBUG
private static int s_nextId; // The next id that will be given out.
private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only.
private long m_lastSetTime;
private long m_lastResetTime;
#endif
/// <summary>
/// Gets the underlying <see cref="T:System.Threading.WaitHandle"/> object for this <see
/// cref="ManualResetEventSlim"/>.
/// </summary>
/// <value>The underlying <see cref="T:System.Threading.WaitHandle"/> event object fore this <see
/// cref="ManualResetEventSlim"/>.</value>
/// <remarks>
/// Accessing this property forces initialization of an underlying event object if one hasn't
/// already been created. To simply wait on this <see cref="ManualResetEventSlim"/>,
/// the public Wait methods should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
if (m_eventObj == null)
{
// Lazily initialize the event object if needed.
LazyInitializeEvent();
}
return m_eventObj;
}
}
/// <summary>
/// Gets whether the event is set.
/// </summary>
/// <value>true if the event has is set; otherwise, false.</value>
public bool IsSet
{
get
{
return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask);
}
private set
{
UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask);
}
}
/// <summary>
/// Gets the number of spin waits that will be occur before falling back to a true wait.
/// </summary>
public int SpinCount
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount);
}
private set
{
Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
}
/// <summary>
/// How many threads are waiting.
/// </summary>
private int Waiters
{
get
{
return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
}
//-----------------------------------------------------------------------------------
// Constructs a new event, optionally specifying the initial state and spin count.
// The defaults are that the event is unsignaled and some reasonable default spin.
//
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with an initial state of nonsignaled.
/// </summary>
public ManualResetEventSlim()
: this(false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
public ManualResetEventSlim(bool initialState)
{
// Specify the defualt spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
Initialize(initialState, DEFAULT_SPIN_MP);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
/// class with a Boolen value indicating whether to set the intial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
/// to nonsignaled.</param>
/// <param name="spinCount">The number of spin waits that will occur before falling back to a true
/// wait.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="spinCount"/> is less than
/// 0 or greater than the maximum allowed value.</exception>
public ManualResetEventSlim(bool initialState, int spinCount)
{
if (spinCount < 0)
{
throw new ArgumentOutOfRangeException("spinCount");
}
if (spinCount > SpinCountState_MaxValue)
{
throw new ArgumentOutOfRangeException(
"spinCount",
String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
Initialize(initialState, spinCount);
}
/// <summary>
/// Initializes the internal state of the event.
/// </summary>
/// <param name="initialState">Whether the event is set initially or not.</param>
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
}
/// <summary>
/// Helper to ensure the lock object is created before first use.
/// </summary>
private void EnsureLockObjectCreated()
{
Contract.Ensures(m_lock != null);
Contract.Ensures(m_condition != null);
if (m_lock == null)
{
Lock newObj = new Lock();
Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign.. someone else won the race.
}
if (m_condition == null)
{
Condition newCond = new Condition(m_lock);
Interlocked.CompareExchange(ref m_condition, newCond, null);
}
}
/// <summary>
/// This method lazily initializes the event object. It uses CAS to guarantee that
/// many threads racing to call this at once don't result in more than one event
/// being stored and used. The event will be signaled or unsignaled depending on
/// the state of the thin-event itself, with synchronization taken into account.
/// </summary>
/// <returns>True if a new event was created and stored, false otherwise.</returns>
private bool LazyInitializeEvent()
{
bool preInitializeIsSet = IsSet;
ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet);
// We have to CAS this in case we are racing with another thread. We must
// guarantee only one event is actually stored in this field.
if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null)
{
// We raced with someone else and lost. Destroy the garbage event.
newEventObj.Dispose();
return false;
}
else
{
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
// the CAS above (in addition to m_state being volatile) prevents this read
// from moving earlier and being collapsed with our original one.
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
Contract.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
lock (newEventObj)
{
// If our event hasn't already been disposed of, we must set it.
if (m_eventObj == newEventObj)
{
newEventObj.Set();
}
}
}
return true;
}
}
/// <summary>
/// Sets the state of the event to signaled, which allows one or more threads waiting on the event to
/// proceed.
/// </summary>
public void Set()
{
Set(false);
}
/// <summary>
/// Private helper to actually perform the Set.
/// </summary>
/// <param name="duringCancellation">Indicates whether we are calling Set() during cancellation.</param>
/// <exception cref="T:System.OperationCanceledException">The object has been canceled.</exception>
private void Set(bool duringCancellation)
{
// We need to ensure that IsSet=true does not get reordered past the read of m_eventObj
// This would be a legal movement according to the .NET memory model.
// The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier.
IsSet = true;
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
Contract.Assert(m_lock != null && m_condition != null); //if waiters>0, then m_lock has already been created.
lock (m_lock)
{
m_condition.SignalAll();
}
}
ManualResetEvent eventObj = m_eventObj;
//Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly
//It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic
if (eventObj != null && !duringCancellation)
{
// We must surround this call to Set in a lock. The reason is fairly subtle.
// Sometimes a thread will issue a Wait and wake up after we have set m_state,
// but before we have gotten around to setting m_eventObj (just below). That's
// because Wait first checks m_state and will only access the event if absolutely
// necessary. However, the coding pattern { event.Wait(); event.Dispose() } is
// quite common, and we must support it. If the waiter woke up and disposed of
// the event object before the setter has finished, however, we would try to set a
// now-disposed Win32 event. Crash! To deal with this race, we use a lock to
// protect access to the event object when setting and disposing of it. We also
// double-check that the event has not become null in the meantime when in the lock.
lock (eventObj)
{
if (m_eventObj != null)
{
// If somebody is waiting, we must set the event.
m_eventObj.Set();
}
}
}
#if DEBUG
m_lastSetTime = Environment.TickCount;
#endif
}
/// <summary>
/// Sets the state of the event to nonsignaled, which causes threads to block.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Reset()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Reset()
{
ThrowIfDisposed();
// If there's an event, reset it.
if (m_eventObj != null)
{
m_eventObj.Reset();
}
// There is a race here. If another thread Sets the event, we will get into a state
// where m_state will be unsignaled, yet the Win32 event object will have been signaled.
// This could cause waiting threads to wake up even though the event is in an
// unsignaled state. This is fine -- those that are calling Reset concurrently are
// responsible for doing "the right thing" -- e.g. rechecking the condition and
// resetting the event manually.
// And finally set our state back to unsignaled.
IsSet = false;
#if DEBUG
m_lastResetTime = DateTime.Now.Ticks;
#endif
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> receives a signal,
/// while observing a <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.OperationCanceledExcepton"><paramref name="cancellationToken"/> was
/// canceled.</exception>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException("timeout");
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="System.TimeSpan"/> that represents the number of milliseconds
/// to wait, or a <see cref="System.TimeSpan"/> that represents -1 milliseconds to wait indefinitely.
/// </param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException("timeout");
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the current <see cref="ManualResetEventSlim"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a <see
/// cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.ManualResetEventSlim"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The maximum number of waiters has been exceeded.
/// </exception>
/// <exception cref="T:System.Threading.OperationCanceledException"><paramref
/// name="cancellationToken"/> was canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested(); // an early convenience check
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout");
}
if (!IsSet)
{
if (millisecondsTimeout == 0)
{
// For 0-timeouts, we just return immediately.
return false;
}
// We spin briefly before falling back to allocating and/or waiting on a true event.
uint startTime = 0;
bool bNeedTimeoutAdjustment = false;
int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary.
if (millisecondsTimeout != Timeout.Infinite)
{
// We will account for time spent spinning, so that we can decrement it from our
// timeout. In most cases the time spent in this section will be negligible. But
// we can't discount the possibility of our thread being switched out for a lengthy
// period of time. The timeout adjustments only take effect when and if we actually
// decide to block in the kernel below.
startTime = TimeoutHelper.GetTime();
bNeedTimeoutAdjustment = true;
}
//spin
int HOW_MANY_SPIN_BEFORE_YIELD = 10;
int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5;
int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20;
int spinCount = SpinCount;
for (int i = 0; i < spinCount; i++)
{
if (IsSet)
{
return true;
}
else if (i < HOW_MANY_SPIN_BEFORE_YIELD)
{
if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2)
{
SpinWait.Yield();
}
else
{
SpinWait.Spin(PlatformHelper.ProcessorCount * (4 << i));
}
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0)
{
Helpers.Sleep(1);
}
else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0)
{
Helpers.Sleep(0);
}
else
{
SpinWait.Yield();
}
if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
// Now enter the lock and wait.
EnsureLockObjectCreated();
// We must register and deregister the token outside of the lock, to avoid deadlocks.
using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this))
{
lock (m_lock)
{
// Loop to cope with spurious wakeups from other waits being canceled
while (!IsSet)
{
// If our token was canceled, we must throw and exit.
cancellationToken.ThrowIfCancellationRequested();
//update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled)
if (bNeedTimeoutAdjustment)
{
realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout);
if (realMillisecondsTimeout <= 0)
return false;
}
// There is a race that Set will fail to see that there are waiters as Set does not take the lock,
// so after updating waiters, we must check IsSet again.
// Also, we must ensure there cannot be any reordering of the assignment to Waiters and the
// read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange
// operation which provides a full memory barrier.
// If we see IsSet=false, then we are guaranteed that Set() will see that we are
// waiting and will pulse the monitor correctly.
Waiters = Waiters + 1;
if (IsSet) //This check must occur after updating Waiters.
{
Waiters--; //revert the increment.
return true;
}
// Now finally perform the wait.
try
{
// ** the actual wait **
if (!m_condition.Wait(realMillisecondsTimeout))
return false; //return immediately if the timeout has expired.
}
finally
{
// Clean up: we're done waiting.
Waiters = Waiters - 1;
}
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
}
}
}
} // automatically disposes (and deregisters) the callback
return true; //done. The wait was satisfied.
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="ManualResetEventSlim"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="ManualResetEventSlim"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="ManualResetEventSlim"/>, <see cref="Dispose(Boolean)"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if ((m_combinedState & Dispose_BitMask) != 0)
return; // already disposed
m_combinedState |= Dispose_BitMask; //set the dispose bit
if (disposing)
{
// We will dispose of the event object. We do this under a lock to protect
// against the race condition outlined in the Set method above.
ManualResetEvent eventObj = m_eventObj;
if (eventObj != null)
{
lock (eventObj)
{
eventObj.Dispose();
m_eventObj = null;
}
}
}
}
/// <summary>
/// Throw ObjectDisposedException if the MRES is disposed
/// </summary>
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed);
}
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
private static Action<object> s_cancellationTokenCallback = new Action<object>(CancellationTokenCallback);
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
Contract.Assert(mre != null, "Expected a ManualResetEventSlim");
Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
lock (mre.m_lock)
{
mre.m_condition.SignalAll(); // awaken all waiters
}
}
/// <summary>
/// Private helper method for updating parts of a bit-string state value.
/// Mainly called from the IsSet and Waiters properties setters
/// </summary>
/// <remarks>
/// Note: the parameter types must be int as CompareExchange cannot take a Uint
/// </remarks>
/// <param name="newBits">The new value</param>
/// <param name="updateBitsMask">The mask used to set the bits</param>
private void UpdateStateAtomically(int newBits, int updateBitsMask)
{
SpinWait sw = new SpinWait();
Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
int oldState = m_combinedState; // cache the old value for testing in CAS
// Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111]
// then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111]
int newState = (oldState & ~updateBitsMask) | newBits;
if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState)
{
return;
}
sw.SpinOnce();
} while (true);
}
/// <summary>
/// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word.
/// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
/// <param name="rightBitShiftCount"></param>
/// <returns></returns>
private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount)
{
//convert to uint before shifting so that right-shift does not replicate the sign-bit,
//then convert back to int.
return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount));
}
/// <summary>
/// Performs a Mask operation, but does not perform the shift.
/// This is acceptable for boolean values for which the shift is unnecessary
/// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using
/// ((val & Mask) >> shiftAmount) == 1
///
/// ?? is there a common place to put this rather than being private to MRES?
/// </summary>
/// <param name="state"></param>
/// <param name="mask"></param>
private static int ExtractStatePortion(int state, int mask)
{
return state & mask;
}
}
}
| |
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 ActivityImageChanges
{
public override string Id
{
get { return "20150717041518_ActivityImageChanges"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta5-13549"; }
}
public override void BuildTargetModel(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");
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Polymorphicrecursive operations.
/// </summary>
public partial class Polymorphicrecursive : IServiceOperations<AutoRestComplexTestService>, IPolymorphicrecursive
{
/// <summary>
/// Initializes a new instance of the Polymorphicrecursive class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Polymorphicrecursive(AutoRestComplexTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Fish>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "fishtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "fishtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace EnumsNET.Analyzer
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ObsoletedMethodMigrationCodeFix)), Shared]
public class ObsoletedMethodMigrationCodeFix : CodeFixProvider
{
private const string s_title = "Migrate obsoleted method calls";
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(ObsoletedMethodMigrationAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider() => BatchFixer.Instance;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var identifierName = (IdentifierNameSyntax)root.FindToken(diagnostic.Location.SourceSpan.Start).Parent;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: s_title,
createChangedDocument: async c =>
{
var syntaxEditor = new SyntaxEditor(root, context.Document.Project.Solution.Workspace);
TryAddUsingDirective(root, syntaxEditor);
var semanticModel = await context.Document.GetSemanticModelAsync(c).ConfigureAwait(false);
UpdateCodeUsage(identifierName, syntaxEditor, semanticModel);
return context.Document.WithSyntaxRoot(syntaxEditor.GetChangedRoot());
},
equivalenceKey: s_title),
diagnostic);
}
private static void TryAddUsingDirective(SyntaxNode root, SyntaxEditor syntaxEditor)
{
UsingDirectiveSyntax firstEnumsNETUsingDirective = null;
foreach (var usingDirective in root.ChildNodes().OfType<UsingDirectiveSyntax>())
{
switch (usingDirective.Name.ToString())
{
case "EnumsNET.NonGeneric":
case "EnumsNET.Unsafe":
if (firstEnumsNETUsingDirective == null)
{
firstEnumsNETUsingDirective = usingDirective;
}
continue;
case "EnumsNET":
firstEnumsNETUsingDirective = null;
break;
default:
continue;
}
break;
}
if (firstEnumsNETUsingDirective != null)
{
syntaxEditor.InsertBefore(firstEnumsNETUsingDirective, SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("EnumsNET")));
}
}
private static void TryReplaceUsingDirectives(SyntaxNode root, SyntaxEditor syntaxEditor)
{
var foundUsingDirective = false;
foreach (var usingDirective in root.ChildNodes().OfType<UsingDirectiveSyntax>())
{
switch (usingDirective.Name.ToString())
{
case "EnumsNET.NonGeneric":
case "EnumsNET.Unsafe":
if (foundUsingDirective)
{
syntaxEditor.RemoveNode(usingDirective);
}
else
{
syntaxEditor.ReplaceNode(usingDirective, SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("EnumsNET")));
foundUsingDirective = true;
}
break;
case "EnumsNET":
if (foundUsingDirective)
{
syntaxEditor.RemoveNode(usingDirective);
}
else
{
foundUsingDirective = true;
}
break;
}
}
}
private static void UpdateCodeUsage(IdentifierNameSyntax identifierName, SyntaxEditor syntaxEditor, SemanticModel semanticModel)
{
SyntaxNode n = identifierName;
var appendUnsafe = false;
INamedTypeSymbol type = null;
switch (identifierName.Identifier.ValueText)
{
case "NonGenericEnums":
type = GetEnumsType(semanticModel);
break;
case "NonGenericFlagEnums":
type = GetFlagEnumsType(semanticModel);
break;
case "UnsafeEnums":
type = GetEnumsType(semanticModel);
appendUnsafe = true;
break;
case "UnsafeFlagEnums":
type = GetFlagEnumsType(semanticModel);
appendUnsafe = true;
break;
default:
while (n.Parent is MemberAccessExpressionSyntax m)
{
n = m;
switch (m.Name.Identifier.ValueText)
{
case "NonGenericEnums":
type = GetEnumsType(semanticModel);
break;
case "NonGenericFlagEnums":
type = GetFlagEnumsType(semanticModel);
break;
case "UnsafeEnums":
type = GetEnumsType(semanticModel);
appendUnsafe = true;
break;
case "UnsafeFlagEnums":
type = GetFlagEnumsType(semanticModel);
appendUnsafe = true;
break;
default:
continue;
}
break;
}
break;
}
if (type == null)
{
throw new InvalidOperationException("Could not find diagnostic source");
}
syntaxEditor.ReplaceNode(n, syntaxEditor.Generator.TypeExpression(type));
if (appendUnsafe)
{
var methodName = ((MemberAccessExpressionSyntax)n.Parent).Name;
var nonGenericName = SyntaxFactory.Identifier(methodName.Identifier.Text + "Unsafe");
var newName = methodName is GenericNameSyntax genericName
? SyntaxFactory.GenericName(nonGenericName, genericName.TypeArgumentList)
: (SimpleNameSyntax)SyntaxFactory.IdentifierName(nonGenericName);
syntaxEditor.ReplaceNode(methodName, newName);
}
}
private static INamedTypeSymbol GetEnumsType(SemanticModel semanticModel) => semanticModel.Compilation.GetTypeByMetadataName("EnumsNET.Enums");
private static INamedTypeSymbol GetFlagEnumsType(SemanticModel semanticModel) => semanticModel.Compilation.GetTypeByMetadataName("EnumsNET.FlagEnums");
private sealed class BatchFixer : FixAllProvider
{
public static BatchFixer Instance { get; } = new BatchFixer();
public override async Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
{
IEnumerable<Task<KeyValuePair<DocumentId, SyntaxNode>>> tasks = null;
switch (fixAllContext.Scope)
{
case FixAllScope.Document:
tasks = new[] { GetDocumentFixAsync(fixAllContext.Document, fixAllContext) };
break;
case FixAllScope.Project:
tasks = fixAllContext.Project.Documents.Select(d => GetDocumentFixAsync(d, fixAllContext));
break;
case FixAllScope.Solution:
tasks = fixAllContext.Solution.Projects.SelectMany(p => p.Documents.Select(d => GetDocumentFixAsync(d, fixAllContext)));
break;
case FixAllScope.Custom:
return null;
}
var currentSolution = fixAllContext.Solution;
foreach (var pair in await Task.WhenAll(tasks).ConfigureAwait(false))
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(pair.Key, pair.Value);
}
return CodeAction.Create(
title: s_title,
createChangedSolution: _ => Task.FromResult(currentSolution),
equivalenceKey: s_title);
}
private static async Task<KeyValuePair<DocumentId, SyntaxNode>> GetDocumentFixAsync(Document document, FixAllContext fixAllContext)
{
var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
var syntaxEditor = new SyntaxEditor(root, document.Project.Solution.Workspace);
TryReplaceUsingDirectives(root, syntaxEditor);
var semanticModel = await document.GetSemanticModelAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var memberAccessNode = (IdentifierNameSyntax)root.FindToken(diagnostic.Location.SourceSpan.Start).Parent;
UpdateCodeUsage(memberAccessNode, syntaxEditor, semanticModel);
}
return new KeyValuePair<DocumentId, SyntaxNode>(document.Id, syntaxEditor.GetChangedRoot());
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Reflection;
using System.Net;
namespace CUDLR {
struct QueuedCommand {
public CommandAttribute command;
public string[] args;
}
public class Console {
// Max number of lines in the console output
const int MAX_LINES = 100;
// Maximum number of commands stored in the history
const int MAX_HISTORY = 50;
// Prefix for user inputted command
const string COMMAND_OUTPUT_PREFIX = "> ";
private static Console instance;
private CommandTree m_commands;
private List<string> m_output;
private List<string> m_history;
private Queue<QueuedCommand> m_commandQueue;
private Console() {
m_commands = new CommandTree();
m_output = new List<string>();
m_history = new List<string>();
m_commandQueue = new Queue<QueuedCommand>();
RegisterAttributes();
}
public static Console Instance {
get {
if (instance == null) instance = new Console();
return instance;
}
}
public static void Update() {
while (Instance.m_commandQueue.Count > 0) {
QueuedCommand cmd = Instance.m_commandQueue.Dequeue();
cmd.command.m_callback( cmd.args );
}
}
/* Queue a command to be executed on update on the main thread */
public static void Queue(CommandAttribute command, string[] args) {
QueuedCommand queuedCommand = new QueuedCommand();
queuedCommand.command = command;
queuedCommand.args = args;
Instance.m_commandQueue.Enqueue( queuedCommand );
}
/* Execute a command */
public static void Run(string str) {
if (str.Length > 0) {
LogCommand(str);
Instance.RecordCommand(str);
Instance.m_commands.Run(str);
}
}
/* Clear all output from console */
[Command("clear", "clears console output", false)]
public static void Clear() {
Instance.m_output.Clear();
}
/* Print a list of all console commands */
[Command("help", "prints commands", false)]
public static void Help() {
string help = "Commands:";
foreach (CommandAttribute cmd in Instance.m_commands.OrderBy(m=>m.m_command)) {
help += string.Format("\n{0} : {1}", cmd.m_command, cmd.m_help);
}
Log("<span class='Help'>" + help + "</span>");
}
/* Find command based on partial string */
public static string Complete(string partialCommand) {
return Instance.m_commands.Complete( partialCommand );
}
/* Logs user input to output */
public static void LogCommand(string cmd) {
Log(COMMAND_OUTPUT_PREFIX+cmd);
}
/* Logs string to output */
public static void Log(string str) {
Instance.m_output.Add(str);
if (Instance.m_output.Count > MAX_LINES)
Instance.m_output.RemoveAt(0);
}
/* Callback for Unity logging */
public static void LogCallback (string logString, string stackTrace, LogType type) {
if (type != LogType.Log) {
Console.Log("<span class='" + type + "'>" + logString);
Console.Log(stackTrace + "</span>");
} else {
Console.Log(logString);
}
}
/* Returns the output */
public static string Output() {
return string.Join("\n", Instance.m_output.ToArray());
}
/* Register a new console command */
public static void RegisterCommand(string command, string desc, CommandAttribute.Callback callback, bool runOnMainThread = true) {
if (command == null || command.Length == 0) {
throw new Exception("Command String cannot be empty");
}
CommandAttribute cmd = new CommandAttribute(command, desc, runOnMainThread);
cmd.m_callback = callback;
Instance.m_commands.Add(cmd);
}
private void RegisterAttributes() {
foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
// HACK: IL2CPP crashes if you attempt to get the methods of some classes in these assemblies.
if (assembly.FullName.StartsWith("System") || assembly.FullName.StartsWith("mscorlib")) {
continue;
}
foreach(Type type in assembly.GetTypes()) {
// FIXME add support for non-static methods (FindObjectByType?)
foreach(MethodInfo method in type.GetMethods(BindingFlags.Public|BindingFlags.Static)) {
CommandAttribute[] attrs = method.GetCustomAttributes(typeof(CommandAttribute), true) as CommandAttribute[];
if (attrs.Length == 0)
continue;
CommandAttribute.Callback cb = Delegate.CreateDelegate(typeof(CommandAttribute.Callback), method, false) as CommandAttribute.Callback;
if (cb == null)
{
CommandAttribute.CallbackSimple cbs = Delegate.CreateDelegate(typeof(CommandAttribute.CallbackSimple), method, false) as CommandAttribute.CallbackSimple;
if (cbs != null) {
cb = delegate(string[] args) {
cbs();
};
}
}
if (cb == null) {
Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console command.", type, method.Name));
continue;
}
// try with a bare action
foreach(CommandAttribute cmd in attrs) {
if (string.IsNullOrEmpty(cmd.m_command)) {
Debug.LogError(string.Format("Method {0}.{1} needs a valid command name.", type, method.Name));
continue;
}
cmd.m_callback = cb;
m_commands.Add(cmd);
}
}
}
}
}
/* Get a previously ran command from the history */
public static string PreviousCommand(int index) {
return index >= 0 && index < Instance.m_history.Count ? Instance.m_history[index] : null;
}
/* Update history with a new command */
private void RecordCommand(string command) {
m_history.Insert(0, command);
if (m_history.Count > MAX_HISTORY)
m_history.RemoveAt(m_history.Count - 1);
}
// Our routes
[Route("^/console/out$")]
public static void Output(RequestContext context) {
context.Response.WriteString(Console.Output());
}
[Route("^/console/run$")]
public static void Run(RequestContext context) {
string command = Uri.UnescapeDataString(context.Request.QueryString.Get("command"));
if (!string.IsNullOrEmpty(command))
Console.Run(command);
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.StatusDescription = "OK";
}
[Route("^/console/commandHistory$")]
public static void History(RequestContext context) {
string index = context.Request.QueryString.Get("index");
string previous = null;
if (!string.IsNullOrEmpty(index))
previous = Console.PreviousCommand(System.Int32.Parse(index));
context.Response.WriteString(previous);
}
[Route("^/console/complete$")]
public static void Complete(RequestContext context) {
string partialCommand = context.Request.QueryString.Get("command");
string found = null;
if (partialCommand != null)
found = Console.Complete(partialCommand);
context.Response.WriteString(found);
}
}
class CommandTree : IEnumerable<CommandAttribute> {
private Dictionary<string, CommandTree> m_subcommands;
private CommandAttribute m_command;
public CommandTree() {
m_subcommands = new Dictionary<string, CommandTree>();
}
public void Add(CommandAttribute cmd) {
_add(cmd.m_command.ToLower().Split(' '), 0, cmd);
}
private void _add(string[] commands, int command_index, CommandAttribute cmd) {
if (commands.Length == command_index) {
m_command = cmd;
return;
}
string token = commands[command_index];
if (!m_subcommands.ContainsKey(token)){
m_subcommands[token] = new CommandTree();
}
m_subcommands[token]._add(commands, command_index + 1, cmd);
}
public IEnumerator<CommandAttribute> GetEnumerator() {
if (m_command != null && m_command.m_command != null)
yield return m_command;
foreach(KeyValuePair<string, CommandTree> entry in m_subcommands) {
foreach(CommandAttribute cmd in entry.Value) {
if (cmd != null && cmd.m_command != null)
yield return cmd;
}
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public string Complete(string partialCommand) {
return _complete(partialCommand.Split(' '), 0, "");
}
public string _complete(string[] partialCommand, int index, string result) {
if (partialCommand.Length == index && m_command != null) {
// this is a valid command... so we do nothing
return result;
} else if (partialCommand.Length == index) {
// This is valid but incomplete.. print all of the subcommands
Console.LogCommand(result);
foreach (string key in m_subcommands.Keys.OrderBy(m=>m)) {
Console.Log(result + " " + key);
}
return result + " ";
} else if (partialCommand.Length == (index+1)) {
string partial = partialCommand[index];
if (m_subcommands.ContainsKey(partial)) {
result += partial;
return m_subcommands[partial]._complete(partialCommand, index+1, result);
}
// Find any subcommands that match our partial command
List<string> matches = new List<string>();
foreach (string key in m_subcommands.Keys.OrderBy(m=>m)) {
if (key.StartsWith(partial)) {
matches.Add(key);
}
}
if (matches.Count == 1) {
// Only one command found, log nothing and return the complete command for the user input
return result + matches[0] + " ";
} else if (matches.Count > 1) {
// list all the options for the user and return partial
Console.LogCommand(result + partial);
foreach (string match in matches) {
Console.Log(result + match);
}
}
return result + partial;
}
string token = partialCommand[index];
if (!m_subcommands.ContainsKey(token)) {
return result;
}
result += token + " ";
return m_subcommands[token]._complete( partialCommand, index + 1, result );
}
public void Run(string commandStr) {
// Split user input on spaces ignoring anything in qoutes
Regex regex = new Regex(@""".*?""|[^\s]+");
MatchCollection matches = regex.Matches(commandStr);
string[] tokens = new string[matches.Count];
for (int i = 0; i < tokens.Length; ++i) {
tokens[i] = matches[i].Value.Replace("\"","");
}
_run(tokens, 0);
}
static string[] emptyArgs = new string[0]{};
private void _run(string[] commands, int index) {
if (commands.Length == index) {
RunCommand(emptyArgs);
return;
}
string token = commands[index].ToLower();
if (!m_subcommands.ContainsKey(token)) {
RunCommand(commands.Skip(index).ToArray());
return;
}
m_subcommands[token]._run(commands, index + 1);
}
private void RunCommand(string[] args) {
if (m_command == null) {
Console.Log("command not found");
} else if (m_command.m_runOnMainThread) {
Console.Queue( m_command, args );
} else {
m_command.m_callback(args);
}
}
}
}
| |
// 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.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
namespace System.Data.ProviderBase
{
internal abstract class DbConnectionInternal
{
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
private readonly bool _allowSetConnectionString;
private readonly bool _hidePassword;
private readonly ConnectionState _state;
private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
private bool _isInStasis;
private DateTime _createTime; // when the connection was created.
private Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
// _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
// However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
// This field should only be assigned a value at the same time _enlistedTransaction is updated.
// Also, this reference should not be disposed, since we aren't taking ownership of it.
private Transaction _enlistedTransactionOriginal;
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in sync.
#endif //DEBUG
protected DbConnectionInternal() : this(ConnectionState.Open, true, false)
{
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString)
{
_allowSetConnectionString = allowSetConnectionString;
_hidePassword = hidePassword;
_state = state;
}
internal bool AllowSetConnectionString
{
get
{
return _allowSetConnectionString;
}
}
internal bool CanBePooled
{
get
{
bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive);
return flag;
}
}
protected internal Transaction EnlistedTransaction
{
get
{
return _enlistedTransaction;
}
set
{
Transaction currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
|| ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
{ // WebData 20000024
// Pay attention to the order here:
// 1) defect from any notifications
// 2) replace the transaction
// 3) re-enlist in notifications for the new transaction
// SQLBUDT #230558 we need to use a clone of the transaction
// when we store it, or we'll end up keeping it past the
// duration of the using block of the TransactionScope
Transaction valueClone = null;
Transaction previousTransactionClone = null;
try
{
if (null != value)
{
valueClone = value.Clone();
}
// NOTE: rather than take locks around several potential round-
// trips to the server, and/or virtual function calls, we simply
// presume that you aren't doing something illegal from multiple
// threads, and check once we get around to finalizing things
// inside a lock.
lock (this)
{
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
// however this should have been handled by the outer
// connection which checks to ensure that it's OK. The
// only case where we have the race condition is multiple
// concurrent enlist requests to the same connection, which
// is a bit out of line with something we should have to
// support.
// enlisted transaction can be nullified in Dispose call without lock
previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
_enlistedTransactionOriginal = value;
value = valueClone;
valueClone = null; // we've stored it, don't dispose it.
}
}
finally
{
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
if (null != previousTransactionClone &&
!Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction))
{
previousTransactionClone.Dispose();
}
if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction))
{
valueClone.Dispose();
}
}
// I don't believe that we need to lock to protect the actual
// enlistment in the transaction; it would only protect us
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
if (null != value)
{
TransactionOutcomeEnlist(value);
}
}
}
}
/// <summary>
/// Get boolean value that indicates whether the enlisted transaction has been disposed.
/// </summary>
/// <value>
/// True if there is an enlisted transaction, and it has been diposed.
/// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null.
/// </value>
/// <remarks>
/// This method must be called while holding a lock on the DbConnectionInternal instance.
/// </remarks>
protected bool EnlistedTransactionDisposed
{
get
{
// Until the Transaction.Disposed property is public it is necessary to access a member
// that throws if the object is disposed to determine if in fact the transaction is disposed.
try
{
bool disposed;
Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
if (currentEnlistedTransactionOriginal != null)
{
disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
}
else
{
// Don't expect to get here in the general case,
// Since this getter is called by CheckEnlistedTransactionBinding
// after checking for a non-null enlisted transaction (and it does so under lock).
disposed = false;
}
return disposed;
}
catch (ObjectDisposedException)
{
return true;
}
}
}
internal bool IsTxRootWaitingForTxEnd
{
get
{
return _isInStasis;
}
}
virtual protected bool UnbindOnTransactionCompletion
{
get
{
return true;
}
}
// Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
virtual protected internal bool IsNonPoolableTransactionRoot
{
get
{
return false; // if you want to have delegated transactions that are non-poolable, you better override this...
}
}
virtual internal bool IsTransactionRoot
{
get
{
return false; // if you want to have delegated transactions, you better override this...
}
}
protected internal bool IsConnectionDoomed
{
get
{
return _connectionIsDoomed;
}
}
internal bool IsEmancipated
{
get
{
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (DbConnectionPool.Clear and ReclaimEmancipatedObjects
// do this for us)
// The functionality is as follows:
//
// _pooledCount is incremented when the connection is pushed into the pool
// _pooledCount is decremented when the connection is popped from the pool
// _pooledCount is set to -1 when the connection is not pooled (just in case...)
//
// That means that:
//
// _pooledCount > 1 connection is in the pool multiple times (This should not happen)
// _pooledCount == 1 connection is in the pool
// _pooledCount == 0 connection is out of the pool
// _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections.
// _pooledCount < -1 connection out of the pool multiple times
//
// Now, our job is to return TRUE when the connection is out
// of the pool and it's owning object is no longer around to
// return it.
bool value = (_pooledCount < 1) && !_owningObject.IsAlive;
return value;
}
}
internal bool IsInPool
{
get
{
Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid");
return (_pooledCount == 1);
}
}
protected internal object Owner
{
// We use a weak reference to the owning object so we can identify when
// it has been garbage collected without thowing exceptions.
get
{
return _owningObject.Target;
}
}
internal DbConnectionPool Pool
{
get
{
return _connectionPool;
}
}
virtual protected bool ReadyToPrepareTransaction
{
get
{
return true;
}
}
protected internal DbReferenceCollection ReferenceCollection
{
get
{
return _referenceCollection;
}
}
abstract public string ServerVersion
{
get;
}
// this should be abstract but until it is added to all the providers virtual will have to do
virtual public string ServerVersionNormalized
{
get
{
throw ADP.NotSupported();
}
}
public bool ShouldHidePassword
{
get
{
return _hidePassword;
}
}
public ConnectionState State
{
get
{
return _state;
}
}
abstract protected void Activate(Transaction transaction);
internal void ActivateConnection(Transaction transaction)
{
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
Activate(transaction);
}
internal void AddWeakReference(object value, int tag)
{
if (null == _referenceCollection)
{
_referenceCollection = CreateReferenceCollection();
if (null == _referenceCollection)
{
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
_referenceCollection.Add(value, tag);
}
abstract public DbTransaction BeginTransaction(IsolationLevel il);
virtual public void ChangeDatabase(string value)
{
throw ADP.MethodNotImplemented();
}
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
// prevent anything funny from happening (like disposing themselves
// or putting them into a connection pool)
//
// Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
// for cleaning up after DbConnection.Close
// protected override void Deactivate() { // override DbConnectionInternal.Close
// // do derived class connection deactivation for both pooled & non-pooled connections
// }
// public override void Dispose() { // override DbConnectionInternal.Close
// // do derived class cleanup
// base.Dispose();
// }
//
// overriding DbConnection.Close is also possible, but must provider for their own synchronization
// public override void Close() { // override DbConnection.Close
// base.Close();
// // do derived class outer connection for both pooled & non-pooled connections
// // user must do their own synchronization here
// }
//
// if the DbConnectionInternal derived class needs to close the connection it should
// delegate to the DbConnection if one exists or directly call dispose
// DbConnection owningObject = (DbConnection)Owner;
// if (null != owningObject) {
// owningObject.Close(); // force the closed state on the outer object.
// }
// else {
// Dispose();
// }
//
////////////////////////////////////////////////////////////////
// DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
////////////////////////////////////////////////////////////////
Debug.Assert(null != owningObject, "null owningObject");
Debug.Assert(null != connectionFactory, "null connectionFactory");
// if an exception occurs after the state change but before the try block
// the connection will be stuck in OpenBusy state. The commented out try-catch
// block doesn't really help because a ThreadAbort during the finally block
// would just revert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this))
{
// Lock to prevent race condition with cancellation
lock (this)
{
object lockToken = ObtainAdditionalLocksForClose();
try
{
PrepareForCloseConnection();
DbConnectionPool connectionPool = Pool;
// Detach from enlisted transactions that are no longer active on close
DetachCurrentTransactionIfEnded();
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
if (null != connectionPool)
{
connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us...
// NOTE: Before we leave the PutObject call, another
// thread may have already popped the connection from
// the pool, so don't expect to be able to verify it.
}
else
{
Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
// To prevent an endless recursion, we need to clear
// the owning object before we call dispose so that
// we can't get here a second time... Ordinarily, I
// would call setting the owner to null a hack, but
// this is safe since we're about to dispose the
// object and it won't have an owner after that for
// certain.
_owningObject.Target = null;
if (IsTransactionRoot)
{
SetInStasis();
}
else
{
Dispose();
}
}
}
finally
{
ReleaseAdditionalLocksForClose(lockToken);
// if a ThreadAbort puts us here then its possible the outer connection will not reference
// this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
}
}
}
virtual internal void PrepareForReplaceConnection()
{
// By default, there is no preparation required
}
virtual protected void PrepareForCloseConnection()
{
// By default, there is no preparation required
}
virtual protected object ObtainAdditionalLocksForClose()
{
return null; // no additional locks in default implementation
}
virtual protected void ReleaseAdditionalLocksForClose(object lockToken)
{
// no additional locks in default implementation
}
virtual protected DbReferenceCollection CreateReferenceCollection()
{
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
abstract protected void Deactivate();
internal void DeactivateConnection()
{
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
#if DEBUG
int activateCount = Interlocked.Decrement(ref _activateCount);
#endif // DEBUG
if (!_connectionIsDoomed && Pool.UseLoadBalancing)
{
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow;
if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks)
{
DoNotPoolThisConnection();
}
}
Deactivate();
}
virtual internal void DelegatedTransactionEnded()
{
// Called by System.Transactions when the delegated transaction has
// completed. We need to make closed connections that are in stasis
// available again, or disposed closed/leaked non-pooled connections.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (1 == _pooledCount)
{
// When _pooledCount is 1, it indicates a closed, pooled,
// connection so it is ready to put back into the pool for
// general use.
TerminateStasis(true);
Deactivate(); // call it one more time just in case
DbConnectionPool pool = Pool;
if (null == pool)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
}
pool.PutObjectFromTransactedPool(this);
}
else if (-1 == _pooledCount && !_owningObject.IsAlive)
{
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
Deactivate(); // call it one more time just in case
// it's a non-pooled connection, we need to dispose of it
// once and for all, or the server will have fits about us
// leaving connections open until the client-side GC kicks
// in.
Dispose();
}
// When _pooledCount is 0, the connection is a pooled connection
// that is either open (if the owning object is alive) or leaked (if
// the owning object is not alive) In either case, we can't muck
// with the connection here.
}
public virtual void Dispose()
{
_connectionPool = null;
_connectionIsDoomed = true;
_enlistedTransactionOriginal = null; // should not be disposed
// Dispose of the _enlistedTransaction since it is a clone
// of the original reference.
// VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
if (enlistedTransaction != null)
{
enlistedTransaction.Dispose();
}
}
protected internal void DoNotPoolThisConnection()
{
_cannotBePooled = true;
}
/// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc>
protected internal void DoomThisConnection()
{
_connectionIsDoomed = true;
}
abstract public void EnlistTransaction(Transaction transaction);
protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions)
{
Debug.Assert(outerConnection != null, "outerConnection may not be null.");
DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null.");
return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions);
}
internal void MakeNonPooledObject(object owningObject)
{
// Used by DbConnectionFactory to indicate that this object IS NOT part of
// a connection pool.
_connectionPool = null;
_owningObject.Target = owningObject;
_pooledCount = -1;
}
internal void MakePooledConnection(DbConnectionPool connectionPool)
{
// Used by DbConnectionFactory to indicate that this object IS part of
// a connection pool.
_createTime = DateTime.UtcNow;
_connectionPool = connectionPool;
}
internal void NotifyWeakReference(int message)
{
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Notify(message);
}
}
internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
{
if (!TryOpenConnection(outerConnection, connectionFactory, null, null))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
/// <devdoc>The default implementation is for the open connection objects, and
/// it simply throws. Our private closed-state connection objects
/// override this and do the correct thing.</devdoc>
// User code should either override DbConnectionInternal.Activate when it comes out of the pool
// or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections
internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
throw ADP.ConnectionAlreadyOpen(State);
}
internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
throw ADP.MethodNotImplemented();
}
protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions)
{
// ?->Connecting: prevent set_ConnectionString during Open
if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this))
{
DbConnectionInternal openConnection = null;
try
{
connectionFactory.PermissionDemand(outerConnection);
if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection))
{
return false;
}
}
catch
{
// This should occur for all exceptions, even ADP.UnCatchableExceptions.
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw;
}
if (null == openConnection)
{
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection);
}
return true;
}
internal void PrePush(object expectedOwner)
{
// Called by DbConnectionPool when we're about to be put into it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null == expectedOwner)
{
if (null != _owningObject.Target)
{
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner
}
}
else if (_owningObject.Target != expectedOwner)
{
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner
}
if (0 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time
}
_pooledCount++;
_owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2%
}
internal void PostPop(object newOwner)
{
// Called by DbConnectionPool right after it pulls this from it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
Debug.Assert(!IsEmancipated, "pooled object not in pool");
// When another thread is clearing this pool, it
// will doom all connections in this pool without prejudice which
// causes the following assert to fire, which really mucks up stress
// against checked bits. The assert is benign, so we're commenting
// it out.
//Debug.Assert(CanBePooled, "pooled object is not poolable");
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (null != _owningObject.Target)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner!
}
_owningObject.Target = newOwner;
_pooledCount--;
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null != Pool)
{
if (0 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
else if (-1 != _pooledCount)
{
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
internal void RemoveWeakReference(object value)
{
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection)
{
referenceCollection.Remove(value);
}
}
// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
// This is a separate method because cleanup can be triggered in multiple ways for a delegated
// transaction.
virtual protected void CleanupTransactionOnCompletion(Transaction transaction)
{
}
internal void DetachCurrentTransactionIfEnded()
{
Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null)
{
bool transactionIsDead;
try
{
transactionIsDead = (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
}
catch (TransactionException)
{
// If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
if (transactionIsDead)
{
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing)
{
// potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
// transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
// be the exception, not the rule.
lock (this)
{
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = (DbConnection)Owner;
if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner)
{
Transaction currentEnlistedTransaction = _enlistedTransaction;
if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
{
EnlistedTransaction = null;
if (IsTxRootWaitingForTxEnd)
{
DelegatedTransactionEnded();
}
}
}
}
}
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
internal void CleanupConnectionOnTransactionCompletion(Transaction transaction)
{
DetachTransaction(transaction, false);
DbConnectionPool pool = Pool;
if (null != pool)
{
pool.TransactionEnded(transaction, this);
}
}
void TransactionCompletedEvent(object sender, TransactionEventArgs e)
{
Transaction transaction = e.Transaction;
CleanupTransactionOnCompletion(transaction);
CleanupConnectionOnTransactionCompletion(transaction);
}
// TODO: Review whether we need the unmanaged code permission when we have the new object model available.
// [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
private void TransactionOutcomeEnlist(Transaction transaction)
{
transaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompletedEvent);
}
internal void SetInStasis()
{
_isInStasis = true;
}
private void TerminateStasis(bool returningToPool)
{
_isInStasis = false;
}
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still actually alive
/// </summary>
/// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false
/// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param>
/// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns>
internal virtual bool IsConnectionAlive(bool throwOnException = false)
{
return true;
}
}
}
| |
--- /dev/null 2016-03-09 11:44:34.000000000 -0500
+++ src/System.IO.FileSystem.Watcher/src/SR.cs 2016-03-09 11:44:46.710093000 -0500
@@ -0,0 +1,294 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.IO.FileSystem.Watcher
+{
+ internal static class SR
+ {
+
+ }
+}
+
+namespace System
+{
+ internal static class SR
+ {
+ private static ResourceManager s_resourceManager;
+
+ private const String s_resourcesName = "FxResources.System.IO.FileSystem.Watcher.SR";
+
+ internal static String Argument_InvalidPathChars
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidPathChars", null);
+ }
+ }
+
+ internal static String ArgumentOutOfRange_FileLengthTooBig
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_FileLengthTooBig", null);
+ }
+ }
+
+ internal static String BufferSizeTooLarge
+ {
+ get
+ {
+ return SR.GetResourceString("BufferSizeTooLarge", null);
+ }
+ }
+
+ internal static String EventStream_FailedToStart
+ {
+ get
+ {
+ return SR.GetResourceString("EventStream_FailedToStart", null);
+ }
+ }
+
+ internal static String FSW_BufferOverflow
+ {
+ get
+ {
+ return SR.GetResourceString("FSW_BufferOverflow", null);
+ }
+ }
+
+ internal static String FSW_IOError
+ {
+ get
+ {
+ return SR.GetResourceString("FSW_IOError", null);
+ }
+ }
+
+ internal static String InvalidDirName
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidDirName", null);
+ }
+ }
+
+ internal static String InvalidEnumArgument
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidEnumArgument", null);
+ }
+ }
+
+ internal static String IO_FileExists_Name
+ {
+ get
+ {
+ return SR.GetResourceString("IO_FileExists_Name", null);
+ }
+ }
+
+ internal static String IO_FileNotFound
+ {
+ get
+ {
+ return SR.GetResourceString("IO_FileNotFound", null);
+ }
+ }
+
+ internal static String IO_FileNotFound_FileName
+ {
+ get
+ {
+ return SR.GetResourceString("IO_FileNotFound_FileName", null);
+ }
+ }
+
+ internal static String IO_PathNotFound_NoPathName
+ {
+ get
+ {
+ return SR.GetResourceString("IO_PathNotFound_NoPathName", null);
+ }
+ }
+
+ internal static String IO_PathNotFound_Path
+ {
+ get
+ {
+ return SR.GetResourceString("IO_PathNotFound_Path", null);
+ }
+ }
+
+ internal static String IO_PathTooLong
+ {
+ get
+ {
+ return SR.GetResourceString("IO_PathTooLong", null);
+ }
+ }
+
+ internal static String IO_SharingViolation_File
+ {
+ get
+ {
+ return SR.GetResourceString("IO_SharingViolation_File", null);
+ }
+ }
+
+ internal static String IO_SharingViolation_NoFileName
+ {
+ get
+ {
+ return SR.GetResourceString("IO_SharingViolation_NoFileName", null);
+ }
+ }
+
+ internal static String IOException_INotifyInstanceSystemLimitExceeded
+ {
+ get
+ {
+ return SR.GetResourceString("IOException_INotifyInstanceSystemLimitExceeded", null);
+ }
+ }
+
+ internal static String IOException_INotifyInstanceUserLimitExceeded
+ {
+ get
+ {
+ return SR.GetResourceString("IOException_INotifyInstanceUserLimitExceeded", null);
+ }
+ }
+
+ internal static String IOException_INotifyInstanceUserLimitExceeded_Value
+ {
+ get
+ {
+ return SR.GetResourceString("IOException_INotifyInstanceUserLimitExceeded_Value", null);
+ }
+ }
+
+ internal static String IOException_INotifyWatchesUserLimitExceeded
+ {
+ get
+ {
+ return SR.GetResourceString("IOException_INotifyWatchesUserLimitExceeded", null);
+ }
+ }
+
+ internal static String IOException_INotifyWatchesUserLimitExceeded_Value
+ {
+ get
+ {
+ return SR.GetResourceString("IOException_INotifyWatchesUserLimitExceeded_Value", null);
+ }
+ }
+
+ internal static String ObjectDisposed_FileClosed
+ {
+ get
+ {
+ return SR.GetResourceString("ObjectDisposed_FileClosed", null);
+ }
+ }
+
+ private static ResourceManager ResourceManager
+ {
+ get
+ {
+ if (SR.s_resourceManager == null)
+ {
+ SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+ }
+ return SR.s_resourceManager;
+ }
+ }
+
+ internal static Type ResourceType
+ {
+ get
+ {
+ return typeof(FxResources.System.IO.FileSystem.Watcher.SR);
+ }
+ }
+
+ internal static String UnauthorizedAccess_IODenied_NoPathName
+ {
+ get
+ {
+ return SR.GetResourceString("UnauthorizedAccess_IODenied_NoPathName", null);
+ }
+ }
+
+ internal static String UnauthorizedAccess_IODenied_Path
+ {
+ get
+ {
+ return SR.GetResourceString("UnauthorizedAccess_IODenied_Path", null);
+ }
+ }
+
+ internal static String Format(String resourceFormat, params Object[] args)
+ {
+ if (args == null)
+ {
+ return resourceFormat;
+ }
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, args);
+ }
+ return String.Concat(resourceFormat, String.Join(", ", args));
+ }
+
+ internal static String Format(String resourceFormat, Object p1)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2, Object p3)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2, p3);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 });
+ }
+
+ internal static String GetResourceString(String resourceKey, String defaultString)
+ {
+ String str = null;
+ try
+ {
+ str = SR.ResourceManager.GetString(resourceKey);
+ }
+ catch (MissingManifestResourceException missingManifestResourceException)
+ {
+ }
+ if (defaultString != null && resourceKey.Equals(str))
+ {
+ return defaultString;
+ }
+ return str;
+ }
+
+ private static Boolean UsingResourceKeys()
+ {
+ return false;
+ }
+ }
+}
| |
//
// System.Data.SQLite.SqliteConnection.cs
//
// Represents an open connection to a Sqlite database file.
//
// Author(s): Vladimir Vukicevic <vladimir@pobox.com>
// Everaldo Canuto <everaldo_canuto@yahoo.com.br>
// Daniel Morgan <monodanmorg@yahoo.com>
// Noah Hart <Noah.Hart@gmail.com>
//
// Copyright (C) 2002 Vladimir Vukicevic
//
// 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.Data;
using System.IO;
using System.Data.Common;
using System.Text;
using System.Collections.Generic;
namespace System.Data.SQLite
{
[System.ComponentModel.DesignerCategory("")]
public class SQLiteConnection : DbConnection, ICloneable
{
#region Fields
private string conn_str;
private string db_file;
private int db_mode;
private int db_version;
private string db_password;
private IntPtr sqlite_handle;
private Sqlite3.sqlite3 sqlite_handle2;
private ConnectionState state;
private Encoding encoding;
private int busy_timeout;
bool disposed;
#endregion
#region Constructors and destructors
public SQLiteConnection()
{
db_file = null;
db_mode = 0644;
db_version = 3;
state = ConnectionState.Closed;
sqlite_handle = IntPtr.Zero;
encoding = null;
busy_timeout = 0;
}
public SQLiteConnection(string connstring)
: this()
{
ConnectionString = connstring;
}
protected override void Dispose(bool disposing)
{
try
{
if(disposing && !disposed)
{
Close();
conn_str = null;
}
}
finally
{
disposed = true;
base.Dispose(disposing);
}
}
#endregion
#region Properties
protected override DbProviderFactory DbProviderFactory
{
get
{
return SQLiteClientFactory.Instance;
}
}
public override string ConnectionString
{
get { return conn_str; }
set { SetConnectionString(value); }
}
public override int ConnectionTimeout
{
get { return 0; }
}
public override string Database
{
get { return db_file; }
}
public override ConnectionState State
{
get { return state; }
}
public Encoding Encoding
{
get { return encoding; }
}
public int Version
{
get { return db_version; }
}
public override string ServerVersion
{
get { return Sqlite3.sqlite3_libversion(); }
}
internal Sqlite3.sqlite3 Handle2
{
get { return sqlite_handle2; }
}
internal IntPtr Handle
{
get { return sqlite_handle; }
}
public override string DataSource
{
get { return db_file; }
}
public int LastInsertRowId
{
get
{
//if (Version == 3)
return (int)Sqlite3.sqlite3_last_insert_rowid(Handle2);
//return (int)Sqlite.sqlite3_last_insert_rowid (Handle);
//else
// return Sqlite.sqlite_last_insert_rowid (Handle);
}
}
public int BusyTimeout
{
get
{
return busy_timeout;
}
set
{
busy_timeout = value < 0 ? 0 : value;
}
}
#endregion
#region Private Methods
private void SetConnectionString(string connstring)
{
if(connstring == null)
{
Close();
conn_str = null;
return;
}
if(connstring != conn_str)
{
Close();
conn_str = connstring;
db_file = null;
db_mode = 0644;
string[] conn_pieces = connstring.Split(';');
for(int i = 0; i < conn_pieces.Length; i++)
{
string piece = conn_pieces[i].Trim();
// ignore empty elements
if(piece.Length == 0)
{
continue;
}
int firstEqual = piece.IndexOf('=');
if(firstEqual == -1)
{
throw new InvalidOperationException("Invalid connection string");
}
string token = piece.Substring(0, firstEqual);
string tvalue = piece.Remove(0, firstEqual + 1).Trim();
string tvalue_lc = tvalue.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
switch(token.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim())
{
case "data source":
case "uri":
if(tvalue_lc.StartsWith("file://"))
{
db_file = tvalue.Substring(7);
}
else if(tvalue_lc.StartsWith("file:"))
{
db_file = tvalue.Substring(5);
}
else if(tvalue_lc.StartsWith("/"))
{
db_file = tvalue;
#if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE)
}
else if(tvalue_lc.StartsWith("|DataDirectory|", StringComparison.InvariantCultureIgnoreCase))
{
AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;
string filePath = String.Format("App_Data{0}{1}", Path.DirectorySeparatorChar, tvalue_lc.Substring(15));
db_file = Path.Combine(ads.ApplicationBase, filePath);
#endif
}
else
db_file = tvalue;
break;
case "mode":
db_mode = Convert.ToInt32(tvalue);
break;
case "version":
db_version = Convert.ToInt32(tvalue);
if(db_version < 3)
throw new InvalidOperationException("Minimum database version is 3");
break;
case "encoding": // only for sqlite2
encoding = Encoding.GetEncoding(tvalue);
break;
case "busy_timeout":
busy_timeout = Convert.ToInt32(tvalue);
break;
case "password":
if(!String.IsNullOrEmpty(db_password) && (db_password.Length != 34 || !db_password.StartsWith("0x")))
throw new InvalidOperationException("Invalid password string: must be 34 hex digits starting with 0x");
db_password = tvalue;
break;
}
}
if(db_file == null)
{
throw new InvalidOperationException("Invalid connection string: no URI");
}
}
}
#endregion
#region Internal Methods
internal void StartExec()
{
// use a mutex here
state = ConnectionState.Executing;
}
internal void EndExec()
{
state = ConnectionState.Open;
}
/// <summary>
/// Looks for a key in the array of key/values of the parameter string. If not found, return the specified default value
/// </summary>
/// <param name="items">The list to look in</param>
/// <param name="key">The key to find</param>
/// <param name="defValue">The default value to return if the key is not found</param>
/// <returns>The value corresponding to the specified key, or the default value if not found.</returns>
static internal string FindKey(System.Collections.Generic.SortedList<string, string> items, string key, string defValue)
{
string ret;
if(items.TryGetValue(key, out ret))
return ret;
return defValue;
}
/// <summary>
/// Parses the connection string into component parts
/// </summary>
/// <param name="connectionString">The connection string to parse</param>
/// <returns>An array of key-value pairs representing each parameter of the connection string</returns>
internal static System.Collections.Generic.SortedList<string, string> ParseConnectionString(string connectionString)
{
string s = connectionString;
int n;
SortedList<string, string> ls = new SortedList<string, string>(StringComparer.OrdinalIgnoreCase);
// First split into semi-colon delimited values. The Split() function of SQLiteBase accounts for and properly
// skips semi-colons in quoted strings
string[] arParts = SQLiteConvert.Split(s, ';');
int x = arParts.Length;
// For each semi-colon piece, split into key and value pairs by the presence of the = sign
for(n = 0; n < x; n++)
{
int indexOf = arParts[n].IndexOf('=');
if(indexOf != -1)
ls.Add(arParts[n].Substring(0, indexOf), arParts[n].Substring(indexOf + 1));
else
throw new ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentCulture, "Invalid ConnectionString format for part \"{0}\"", arParts[n]));
}
return ls;
}
#endregion
#region Public Methods
object ICloneable.Clone()
{
return new SQLiteConnection(ConnectionString);
}
protected override DbTransaction BeginDbTransaction(IsolationLevel il)
{
if(state != ConnectionState.Open)
throw new InvalidOperationException("Invalid operation: The connection is closed");
SQLiteTransaction t = new SQLiteTransaction();
t.SetConnection(this);
SQLiteCommand cmd = (SQLiteCommand)this.CreateCommand();
cmd.CommandText = "BEGIN";
cmd.ExecuteNonQuery();
return t;
}
public new DbTransaction BeginTransaction()
{
return BeginDbTransaction(IsolationLevel.Unspecified);
}
public new DbTransaction BeginTransaction(IsolationLevel il)
{
return BeginDbTransaction(il);
}
public override void Close()
{
if(state != ConnectionState.Open)
{
return;
}
state = ConnectionState.Closed;
if(Version == 3)
//Sqlite3.sqlite3_close()
Sqlite3.sqlite3_close(sqlite_handle2);
//else
//Sqlite.sqlite_close (sqlite_handle);
sqlite_handle = IntPtr.Zero;
this.OnStateChange(new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed));
}
public override void ChangeDatabase(string databaseName)
{
Close();
db_file = databaseName;
Open();
}
protected override DbCommand CreateDbCommand()
{
return new SQLiteCommand(null, this);
}
public override void Open()
{
if(conn_str == null)
throw new InvalidOperationException("No database specified");
if(state != ConnectionState.Closed)
throw new InvalidOperationException("Connection state is not closed.");
if(Version == 3)
{
sqlite_handle = (IntPtr)1;
int flags = Sqlite3.SQLITE_OPEN_NOMUTEX | Sqlite3.SQLITE_OPEN_READWRITE | Sqlite3.SQLITE_OPEN_CREATE;
int err = Sqlite3.sqlite3_open_v2(db_file, out sqlite_handle2, flags, null);
//int err = Sqlite.sqlite3_open16(db_file, out sqlite_handle);
if(err == (int)SQLiteError.ERROR)
throw new ApplicationException(Sqlite3.sqlite3_errmsg(sqlite_handle2));
if(busy_timeout != 0)
Sqlite3.sqlite3_busy_timeout(sqlite_handle2, busy_timeout);
if(!String.IsNullOrEmpty(db_password))
{
SQLiteCommand cmd = (SQLiteCommand)this.CreateCommand();
cmd.CommandText = "pragma hexkey='" + db_password + "'";
cmd.ExecuteNonQuery();
}
}
state = ConnectionState.Open;
this.OnStateChange(new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open));
}
#if !SQLITE_SILVERLIGHT
public override DataTable GetSchema(String collectionName)
{
return GetSchema(collectionName, null);
}
public override DataTable GetSchema(String collectionName, string[] restrictionValues)
{
if(State != ConnectionState.Open)
throw new InvalidOperationException("Invalid operation. The connection is closed.");
int restrictionsCount = 0;
if(restrictionValues != null)
restrictionsCount = restrictionValues.Length;
DataTable metaTable = GetSchemaMetaDataCollections();
foreach(DataRow row in metaTable.Rows)
{
if(String.Compare(row["CollectionName"].ToString(), collectionName, true) == 0)
{
int restrictions = (int)row["NumberOfRestrictions"];
if(restrictionsCount > restrictions)
throw new ArgumentException("More restrictions were provided than needed.");
}
}
switch(collectionName.ToUpper())
{
case "METADATACOLLECTIONS":
return metaTable;
case "DATASOURCEINFORMATION":
return GetSchemaDataSourceInformation();
case "DATATYPES":
return GetSchemaDataTypes();
case "RESTRICTIONS":
return GetSchemaRestrictions();
case "RESERVEDWORDS":
return GetSchemaReservedWords();
case "TABLES":
return GetSchemaTables(restrictionValues);
case "COLUMNS":
return GetSchemaColumns(restrictionValues);
case "VIEWS":
return GetSchemaViews(restrictionValues);
case "INDEXCOLUMNS":
return GetSchemaIndexColumns(restrictionValues);
case "INDEXES":
return GetSchemaIndexes(restrictionValues);
case "UNIQUEKEYS":
throw new NotImplementedException(collectionName);
case "PRIMARYKEYS":
throw new NotImplementedException(collectionName);
case "FOREIGNKEYS":
return GetSchemaForeignKeys(restrictionValues);
case "FOREIGNKEYCOLUMNS":
throw new NotImplementedException(collectionName);
case "TRIGGERS":
return GetSchemaTriggers(restrictionValues);
}
throw new ArgumentException("The requested collection is not defined.");
}
static DataTable metaDataCollections = null;
DataTable GetSchemaMetaDataCollections()
{
if(metaDataCollections != null)
return metaDataCollections;
DataTable dt = new DataTable();
dt.Columns.Add("CollectionName", typeof(System.String));
dt.Columns.Add("NumberOfRestrictions", typeof(System.Int32));
dt.Columns.Add("NumberOfIdentifierParts", typeof(System.Int32));
dt.LoadDataRow(new object[] { "MetaDataCollections", 0, 0 }, true);
dt.LoadDataRow(new object[] { "DataSourceInformation", 0, 0 }, true);
dt.LoadDataRow(new object[] { "DataTypes", 0, 0 }, true);
dt.LoadDataRow(new object[] { "Restrictions", 0, 0 }, true);
dt.LoadDataRow(new object[] { "ReservedWords", 0, 0 }, true);
dt.LoadDataRow(new object[] { "Tables", 1, 1 }, true);
dt.LoadDataRow(new object[] { "Columns", 1, 1 }, true);
dt.LoadDataRow(new object[] { "Views", 1, 1 }, true);
dt.LoadDataRow(new object[] { "IndexColumns", 1, 1 }, true);
dt.LoadDataRow(new object[] { "Indexes", 1, 1 }, true);
//dt.LoadDataRow(new object[] { "UniqueKeys", 1, 1 }, true);
//dt.LoadDataRow(new object[] { "PrimaryKeys", 1, 1 }, true);
dt.LoadDataRow(new object[] { "ForeignKeys", 1, 1 }, true);
//dt.LoadDataRow(new object[] { "ForeignKeyColumns", 1, 1 }, true);
dt.LoadDataRow(new object[] { "Triggers", 1, 1 }, true);
return dt;
}
DataTable GetSchemaRestrictions()
{
DataTable dt = new DataTable();
dt.Columns.Add("CollectionName", typeof(System.String));
dt.Columns.Add("RestrictionName", typeof(System.String));
dt.Columns.Add("ParameterName", typeof(System.String));
dt.Columns.Add("RestrictionDefault", typeof(System.String));
dt.Columns.Add("RestrictionNumber", typeof(System.Int32));
dt.LoadDataRow(new object[] { "Tables", "Table", "TABLENAME", "TABLE_NAME", 1 }, true);
dt.LoadDataRow(new object[] { "Columns", "Table", "TABLENAME", "TABLE_NAME", 1 }, true);
dt.LoadDataRow(new object[] { "Views", "View", "VIEWNAME", "VIEW_NAME", 1 }, true);
dt.LoadDataRow(new object[] { "IndexColumns", "Name", "NAME", "INDEX_NAME", 1 }, true);
dt.LoadDataRow(new object[] { "Indexes", "TableName", "TABLENAME", "TABLE_NAME", 1 }, true);
dt.LoadDataRow(new object[] { "ForeignKeys", "Foreign_Key_Table_Name", "TABLENAME", "TABLE_NAME", 1 }, true);
dt.LoadDataRow(new object[] { "Triggers", "TableName", "TABLENAME", "TABLE_NAME", 1 }, true);
return dt;
}
DataTable GetSchemaTables(string[] restrictionValues)
{
SQLiteCommand cmd = new SQLiteCommand("SELECT type, name, tbl_name, rootpage, sql " +
" FROM sqlite_master " +
" WHERE (name = :pname or (:pname is null)) " +
" AND type = 'table' " +
" ORDER BY name", this);
cmd.Parameters.Add("pname", DbType.String).Value = DBNull.Value;
return GetSchemaDataTable(cmd, restrictionValues);
}
DataTable GetSchemaColumns(string[] restrictionValues)
{
if(restrictionValues == null || restrictionValues.Length == 0)
{
throw new ArgumentException("Columns must contain at least one restriction value for the table name.");
}
ValidateIdentifier(restrictionValues[0]);
SQLiteCommand cmd = (SQLiteCommand)CreateCommand();
cmd.CommandText = string.Format("PRAGMA table_info({0})", restrictionValues[0]);
return GetSchemaDataTable(cmd, restrictionValues);
}
DataTable GetSchemaTriggers(string[] restrictionValues)
{
SQLiteCommand cmd = new SQLiteCommand("SELECT type, name, tbl_name, rootpage, sql " +
" FROM sqlite_master " +
" WHERE (tbl_name = :pname or :pname is null) " +
" AND type = 'trigger' " +
" ORDER BY name", this);
cmd.Parameters.Add("pname", DbType.String).Value = DBNull.Value;
return GetSchemaDataTable(cmd, restrictionValues);
}
DataTable GetSchemaIndexColumns(string[] restrictionValues)
{
if(restrictionValues == null || restrictionValues.Length == 0)
{
throw new ArgumentException("IndexColumns must contain at least one restriction value for the index name.");
}
ValidateIdentifier(restrictionValues[0]);
SQLiteCommand cmd = (SQLiteCommand)CreateCommand();
cmd.CommandText = string.Format("PRAGMA index_info({0})", restrictionValues[0]);
return GetSchemaDataTable(cmd, restrictionValues);
}
DataTable GetSchemaIndexes(string[] restrictionValues)
{
if(restrictionValues == null || restrictionValues.Length == 0)
{
throw new ArgumentException("Indexes must contain at least one restriction value for the table name.");
}
ValidateIdentifier(restrictionValues[0]);
SQLiteCommand cmd = (SQLiteCommand)CreateCommand();
cmd.CommandText = string.Format("PRAGMA index_list({0})", restrictionValues[0]);
return GetSchemaDataTable(cmd, restrictionValues);
}
DataTable GetSchemaForeignKeys(string[] restrictionValues)
{
if(restrictionValues == null || restrictionValues.Length == 0)
{
throw new ArgumentException("Foreign Keys must contain at least one restriction value for the table name.");
}
ValidateIdentifier(restrictionValues[0]);
SQLiteCommand cmd = (SQLiteCommand)CreateCommand();
cmd.CommandText = string.Format("PRAGMA foreign_key_list({0})", restrictionValues[0]);
return GetSchemaDataTable(cmd, restrictionValues);
}
#endif
void ValidateIdentifier(string value)
{
if(value.Contains("'"))
throw new ArgumentException("Identifiers can not contain a single quote.");
}
#if !SQLITE_SILVERLIGHT
DataTable GetSchemaViews(string[] restrictionValues)
{
SQLiteCommand cmd = new SQLiteCommand("SELECT type, name, tbl_name, rootpage, sql " +
" FROM sqlite_master " +
" WHERE (name = :pname or :pname is null) " +
" AND type = 'view' " +
" ORDER BY name", this);
cmd.Parameters.Add("pname", DbType.String).Value = DBNull.Value;
return GetSchemaDataTable(cmd, restrictionValues);
}
DataTable GetSchemaDataSourceInformation()
{
DataTable dt = new DataTable();
dt.Columns.Add("CompositeIdentifierSeparatorPattern", typeof(System.String));
dt.Columns.Add("DataSourceProductName", typeof(System.String));
dt.Columns.Add("DataSourceProductVersion", typeof(System.String));
dt.Columns.Add("DataSourceProductVersionNormalized", typeof(System.String));
#if !WINDOWS_MOBILE
dt.Columns.Add("GroupByBehavior", typeof(System.Data.Common.GroupByBehavior));
#else
dt.Columns.Add("GroupByBehavior", typeof(object));
#endif
dt.Columns.Add("IdentifierPattern", typeof(System.String));
#if !WINDOWS_MOBILE
dt.Columns.Add("IdentifierCase", typeof(System.Data.Common.IdentifierCase));
#else
dt.Columns.Add("IdentifierCase", typeof(object ));
#endif
dt.Columns.Add("OrderByColumnsInSelect", typeof(System.Boolean));
dt.Columns.Add("ParameterMarkerFormat", typeof(System.String));
dt.Columns.Add("ParameterMarkerPattern", typeof(System.String));
dt.Columns.Add("ParameterNameMaxLength", typeof(System.Int32));
dt.Columns.Add("ParameterNamePattern", typeof(System.String));
dt.Columns.Add("QuotedIdentifierPattern", typeof(System.String));
#if !WINDOWS_MOBILE
dt.Columns.Add("QuotedIdentifierCase", typeof(System.Data.Common.IdentifierCase));
#else
dt.Columns.Add("QuotedIdentifierCase", typeof(object));
#endif
dt.Columns.Add("StatementSeparatorPattern", typeof(System.String));
dt.Columns.Add("StringLiteralPattern", typeof(System.String));
#if !WINDOWS_MOBILE
dt.Columns.Add("SupportedJoinOperators", typeof(System.Data.Common.SupportedJoinOperators));
#else
dt.Columns.Add("SupportedJoinOperators", typeof(object ));
#endif
// TODO: set correctly
dt.LoadDataRow(new object[] { "",
"SQLite",
ServerVersion,
ServerVersion,
3,
"",
1,
false,
"",
"",
30,
"",
2,
DBNull.Value,
""
}, true);
return dt;
}
DataTable GetSchemaDataTypes()
{
DataTable dt = new DataTable();
dt.Columns.Add("TypeName", typeof(System.String));
dt.Columns.Add("ProviderDbType", typeof(System.String));
dt.Columns.Add("StorageType", typeof(System.Int32));
dt.Columns.Add("DataType", typeof(System.String));
// TODO: fill the rest of these
/*
dt.Columns.Add("ColumnSize", typeof(System.Int64));
dt.Columns.Add("CreateFormat", typeof(System.String));
dt.Columns.Add("CreateParameters", typeof(System.String));
dt.Columns.Add("IsAutoIncrementable",typeof(System.Boolean));
dt.Columns.Add("IsBestMatch", typeof(System.Boolean));
dt.Columns.Add("IsCaseSensitive", typeof(System.Boolean));
dt.Columns.Add("IsFixedLength", typeof(System.Boolean));
dt.Columns.Add("IsFixedPrecisionScale",typeof(System.Boolean));
dt.Columns.Add("IsLong", typeof(System.Boolean));
dt.Columns.Add("IsNullable", typeof(System.Boolean));
dt.Columns.Add("IsSearchable", typeof(System.Boolean));
dt.Columns.Add("IsSearchableWithLike",typeof(System.Boolean));
dt.Columns.Add("IsUnsigned", typeof(System.Boolean));
dt.Columns.Add("MaximumScale", typeof(System.Int16));
dt.Columns.Add("MinimumScale", typeof(System.Int16));
dt.Columns.Add("IsConcurrencyType",typeof(System.Boolean));
dt.Columns.Add("IsLiteralSupported",typeof(System.Boolean));
dt.Columns.Add("LiteralPrefix", typeof(System.String));
dt.Columns.Add("LiteralSuffix", typeof(System.String));
*/
dt.LoadDataRow(new object[] { "INT", "INTEGER", 1, "System.Int32" }, true);
dt.LoadDataRow(new object[] { "INTEGER", "INTEGER", 1, "System.Int32" }, true);
dt.LoadDataRow(new object[] { "TINYINT", "INTEGER", 1, "System.Byte" }, true);
dt.LoadDataRow(new object[] { "SMALLINT", "INTEGER", 1, "System.Int16" }, true);
dt.LoadDataRow(new object[] { "MEDIUMINT", "INTEGER", 1, "System.Int32" }, true);
dt.LoadDataRow(new object[] { "BIGINT", "INTEGER", 1, "System.Int64" }, true);
dt.LoadDataRow(new object[] { "UNSIGNED BIGINT", "INTEGER", 1, "System.UInt64" }, true);
dt.LoadDataRow(new object[] { "INT2", "INTEGER", 1, "System.Int16" }, true);
dt.LoadDataRow(new object[] { "INT8", "INTEGER", 1, "System.Int64" }, true);
dt.LoadDataRow(new object[] { "CHARACTER", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "VARCHAR", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "VARYING CHARACTER", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "NCHAR", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "NATIVE CHARACTER", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "NVARHCAR", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "TEXT", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "CLOB", "TEXT", 2, "System.String" }, true);
dt.LoadDataRow(new object[] { "BLOB", "NONE", 3, "System.Byte[]" }, true);
dt.LoadDataRow(new object[] { "REAL", "REAL", 4, "System.Double" }, true);
dt.LoadDataRow(new object[] { "DOUBLE", "REAL", 4, "System.Double" }, true);
dt.LoadDataRow(new object[] { "DOUBLE PRECISION", "REAL", 4, "System.Double" }, true);
dt.LoadDataRow(new object[] { "FLOAT", "REAL", 4, "System.Double" }, true);
dt.LoadDataRow(new object[] { "NUMERIC", "NUMERIC", 5, "System.Decimal" }, true);
dt.LoadDataRow(new object[] { "DECIMAL", "NUMERIC", 5, "System.Decimal" }, true);
dt.LoadDataRow(new object[] { "BOOLEAN", "NUMERIC", 5, "System.Boolean" }, true);
dt.LoadDataRow(new object[] { "DATE", "NUMERIC", 5, "System.DateTime" }, true);
dt.LoadDataRow(new object[] { "DATETIME", "NUMERIC", 5, "System.DateTime" }, true);
return dt;
}
DataTable GetSchemaReservedWords()
{
DataTable dt = new DataTable();
dt.Columns.Add("ReservedWord", typeof(System.String));
dt.LoadDataRow(new object[] { "ABORT" }, true);
dt.LoadDataRow(new object[] { "ACTION" }, true);
dt.LoadDataRow(new object[] { "ADD" }, true);
dt.LoadDataRow(new object[] { "AFTER" }, true);
dt.LoadDataRow(new object[] { "ALL" }, true);
dt.LoadDataRow(new object[] { "ANALYZE" }, true);
dt.LoadDataRow(new object[] { "AND" }, true);
dt.LoadDataRow(new object[] { "AS" }, true);
dt.LoadDataRow(new object[] { "ATTACH" }, true);
dt.LoadDataRow(new object[] { "AUTOINCREMENT" }, true);
dt.LoadDataRow(new object[] { "BEFORE" }, true);
dt.LoadDataRow(new object[] { "BEFORE" }, true);
dt.LoadDataRow(new object[] { "BEGIN" }, true);
dt.LoadDataRow(new object[] { "BETWEEN" }, true);
dt.LoadDataRow(new object[] { "BY" }, true);
dt.LoadDataRow(new object[] { "CASCADE" }, true);
dt.LoadDataRow(new object[] { "CASE" }, true);
dt.LoadDataRow(new object[] { "CAST" }, true);
dt.LoadDataRow(new object[] { "CHECK" }, true);
dt.LoadDataRow(new object[] { "COLLATE" }, true);
dt.LoadDataRow(new object[] { "COLUMN" }, true);
dt.LoadDataRow(new object[] { "COMMIT" }, true);
dt.LoadDataRow(new object[] { "CONFLICT" }, true);
dt.LoadDataRow(new object[] { "CONTRAINT" }, true);
dt.LoadDataRow(new object[] { "CREATE" }, true);
dt.LoadDataRow(new object[] { "CROSS" }, true);
dt.LoadDataRow(new object[] { "CURRENT_DATE" }, true);
dt.LoadDataRow(new object[] { "CURRENT_TIME" }, true);
dt.LoadDataRow(new object[] { "CURRENT_TIMESTAMP" }, true);
dt.LoadDataRow(new object[] { "DATABASE" }, true);
dt.LoadDataRow(new object[] { "DEFAULT" }, true);
dt.LoadDataRow(new object[] { "DEFERRABLE" }, true);
dt.LoadDataRow(new object[] { "DEFERRED" }, true);
dt.LoadDataRow(new object[] { "DELETE" }, true);
dt.LoadDataRow(new object[] { "DESC" }, true);
dt.LoadDataRow(new object[] { "DETACH" }, true);
dt.LoadDataRow(new object[] { "DISTINCT" }, true);
dt.LoadDataRow(new object[] { "DROP" }, true);
dt.LoadDataRow(new object[] { "EACH" }, true);
dt.LoadDataRow(new object[] { "ELSE" }, true);
dt.LoadDataRow(new object[] { "END" }, true);
dt.LoadDataRow(new object[] { "ESCAPE" }, true);
dt.LoadDataRow(new object[] { "EXCEPT" }, true);
dt.LoadDataRow(new object[] { "EXCLUSIVE" }, true);
dt.LoadDataRow(new object[] { "EXISTS" }, true);
dt.LoadDataRow(new object[] { "EXPLAIN" }, true);
dt.LoadDataRow(new object[] { "FAIL" }, true);
dt.LoadDataRow(new object[] { "FOR" }, true);
dt.LoadDataRow(new object[] { "FOREIGN" }, true);
dt.LoadDataRow(new object[] { "FROM" }, true);
dt.LoadDataRow(new object[] { "FULL" }, true);
dt.LoadDataRow(new object[] { "GLOB" }, true);
dt.LoadDataRow(new object[] { "GROUP" }, true);
dt.LoadDataRow(new object[] { "HAVING" }, true);
dt.LoadDataRow(new object[] { "IF" }, true);
dt.LoadDataRow(new object[] { "IGNORE" }, true);
dt.LoadDataRow(new object[] { "IMMEDIATE" }, true);
dt.LoadDataRow(new object[] { "IN" }, true);
dt.LoadDataRow(new object[] { "INDEX" }, true);
dt.LoadDataRow(new object[] { "INITIALLY" }, true);
dt.LoadDataRow(new object[] { "INNER" }, true);
dt.LoadDataRow(new object[] { "INSERT" }, true);
dt.LoadDataRow(new object[] { "INSTEAD" }, true);
dt.LoadDataRow(new object[] { "INTERSECT" }, true);
dt.LoadDataRow(new object[] { "INTO" }, true);
dt.LoadDataRow(new object[] { "IS" }, true);
dt.LoadDataRow(new object[] { "ISNULL" }, true);
dt.LoadDataRow(new object[] { "JOIN" }, true);
dt.LoadDataRow(new object[] { "KEY" }, true);
dt.LoadDataRow(new object[] { "LEFT" }, true);
dt.LoadDataRow(new object[] { "LIKE" }, true);
dt.LoadDataRow(new object[] { "LIMIT" }, true);
dt.LoadDataRow(new object[] { "MATCH" }, true);
dt.LoadDataRow(new object[] { "NATURAL" }, true);
dt.LoadDataRow(new object[] { "NO" }, true);
dt.LoadDataRow(new object[] { "NOT" }, true);
dt.LoadDataRow(new object[] { "NOT NULL" }, true);
dt.LoadDataRow(new object[] { "OF" }, true);
dt.LoadDataRow(new object[] { "OFFSET" }, true);
dt.LoadDataRow(new object[] { "ON" }, true);
dt.LoadDataRow(new object[] { "OR" }, true);
dt.LoadDataRow(new object[] { "ORDER" }, true);
dt.LoadDataRow(new object[] { "OUTER" }, true);
dt.LoadDataRow(new object[] { "PLAN" }, true);
dt.LoadDataRow(new object[] { "PRAGMA" }, true);
dt.LoadDataRow(new object[] { "PRIMARY" }, true);
dt.LoadDataRow(new object[] { "QUERY" }, true);
dt.LoadDataRow(new object[] { "RAISE" }, true);
dt.LoadDataRow(new object[] { "REFERENCES" }, true);
dt.LoadDataRow(new object[] { "REGEXP" }, true);
dt.LoadDataRow(new object[] { "REINDEX" }, true);
dt.LoadDataRow(new object[] { "RELEASE" }, true);
dt.LoadDataRow(new object[] { "RENAME" }, true);
dt.LoadDataRow(new object[] { "REPLACE" }, true);
dt.LoadDataRow(new object[] { "RESTRICT" }, true);
dt.LoadDataRow(new object[] { "RIGHT" }, true);
dt.LoadDataRow(new object[] { "ROLLBACK" }, true);
dt.LoadDataRow(new object[] { "ROW" }, true);
dt.LoadDataRow(new object[] { "SAVEPOOINT" }, true);
dt.LoadDataRow(new object[] { "SELECT" }, true);
dt.LoadDataRow(new object[] { "SET" }, true);
dt.LoadDataRow(new object[] { "TABLE" }, true);
dt.LoadDataRow(new object[] { "TEMP" }, true);
dt.LoadDataRow(new object[] { "TEMPORARY" }, true);
dt.LoadDataRow(new object[] { "THEN" }, true);
dt.LoadDataRow(new object[] { "TO" }, true);
dt.LoadDataRow(new object[] { "TRANSACTION" }, true);
dt.LoadDataRow(new object[] { "TRIGGER" }, true);
dt.LoadDataRow(new object[] { "UNION" }, true);
dt.LoadDataRow(new object[] { "UNIQUE" }, true);
dt.LoadDataRow(new object[] { "UPDATE" }, true);
dt.LoadDataRow(new object[] { "USING" }, true);
dt.LoadDataRow(new object[] { "VACUUM" }, true);
dt.LoadDataRow(new object[] { "VALUES" }, true);
dt.LoadDataRow(new object[] { "VIEW" }, true);
dt.LoadDataRow(new object[] { "VIRTUAL" }, true);
dt.LoadDataRow(new object[] { "WHEN" }, true);
dt.LoadDataRow(new object[] { "WHERE" }, true);
return dt;
}
DataTable GetSchemaDataTable(SQLiteCommand cmd, string[] restrictionValues)
{
if(restrictionValues != null && cmd.Parameters.Count > 0)
{
for(int i = 0; i < restrictionValues.Length; i++)
cmd.Parameters[i].Value = restrictionValues[i];
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
#endif
/// <summary>
/// Creates a database file. This just creates a zero-byte file which SQLite
/// will turn into a database when the file is opened properly.
/// </summary>
/// <param name="databaseFileName">The file to create</param>
static public void CreateFile(string databaseFileName)
{
FileStream fs = File.Create(databaseFileName);
fs.Close();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace UTJ.FrameCapturer
{
[AddComponentMenu("UTJ/FrameCapturer/GBuffer Recorder")]
[RequireComponent(typeof(Camera))]
[ExecuteInEditMode]
public class GBufferRecorder : RecorderBase
{
#region inner_types
[Serializable]
public struct FrameBufferConponents
{
public bool frameBuffer;
public bool fbColor;
public bool fbAlpha;
public bool GBuffer;
public bool gbAlbedo;
public bool gbOcclusion;
public bool gbSpecular;
public bool gbSmoothness;
public bool gbNormal;
public bool gbEmission;
public bool gbDepth;
public bool gbVelocity;
public static FrameBufferConponents defaultValue
{
get
{
var ret = new FrameBufferConponents
{
frameBuffer = true,
fbColor = true,
fbAlpha = true,
GBuffer = true,
gbAlbedo = true,
gbOcclusion = true,
gbSpecular = true,
gbSmoothness = true,
gbNormal = true,
gbEmission = true,
gbDepth = true,
gbVelocity = true,
};
return ret;
}
}
}
class BufferRecorder
{
RenderTexture m_rt;
int m_channels;
int m_targetFramerate = 30;
string m_name;
MovieEncoder m_encoder;
public BufferRecorder(RenderTexture rt, int ch, string name, int tf)
{
m_rt = rt;
m_channels = ch;
m_name = name;
}
public bool Initialize(MovieEncoderConfigs c, DataPath p)
{
string path = p.GetFullPath() + "/" + m_name;
c.Setup(m_rt.width, m_rt.height, m_channels, m_targetFramerate);
m_encoder = MovieEncoder.Create(c, path);
return m_encoder != null && m_encoder.IsValid();
}
public void Release()
{
if(m_encoder != null)
{
m_encoder.Release();
m_encoder = null;
}
}
public void Update(double time)
{
if (m_encoder != null)
{
fcAPI.fcLock(m_rt, (data, fmt) =>
{
m_encoder.AddVideoFrame(data, fmt, time);
});
}
}
}
#endregion
#region fields
[SerializeField] MovieEncoderConfigs m_encoderConfigs = new MovieEncoderConfigs(MovieEncoder.Type.Exr);
[SerializeField] FrameBufferConponents m_fbComponents = FrameBufferConponents.defaultValue;
[SerializeField] Shader m_shCopy;
Material m_matCopy;
Mesh m_quad;
CommandBuffer m_cbCopyFB;
CommandBuffer m_cbCopyGB;
CommandBuffer m_cbClearGB;
CommandBuffer m_cbCopyVelocity;
RenderTexture[] m_rtFB;
RenderTexture[] m_rtGB;
List<BufferRecorder> m_recorders = new List<BufferRecorder>();
#endregion
#region properties
public FrameBufferConponents fbComponents
{
get { return m_fbComponents; }
set { m_fbComponents = value; }
}
public MovieEncoderConfigs encoderConfigs { get { return m_encoderConfigs; } }
#endregion
public override bool BeginRecording()
{
if (m_recording) { return false; }
if (m_shCopy == null)
{
Debug.LogError("GBufferRecorder: copy shader is missing!");
return false;
}
m_outputDir.CreateDirectory();
if (m_quad == null) m_quad = fcAPI.CreateFullscreenQuad();
if (m_matCopy == null) m_matCopy = new Material(m_shCopy);
var cam = GetComponent<Camera>();
if (cam.targetTexture != null)
{
m_matCopy.EnableKeyword("OFFSCREEN");
}
else
{
m_matCopy.DisableKeyword("OFFSCREEN");
}
int captureWidth = cam.pixelWidth;
int captureHeight = cam.pixelHeight;
GetCaptureResolution(ref captureWidth, ref captureHeight);
if (m_encoderConfigs.format == MovieEncoder.Type.MP4 ||
m_encoderConfigs.format == MovieEncoder.Type.WebM)
{
captureWidth = (captureWidth + 1) & ~1;
captureHeight = (captureHeight + 1) & ~1;
}
if (m_fbComponents.frameBuffer)
{
m_rtFB = new RenderTexture[2];
for (int i = 0; i < m_rtFB.Length; ++i)
{
m_rtFB[i] = new RenderTexture(captureWidth, captureHeight, 0, RenderTextureFormat.ARGBHalf);
m_rtFB[i].filterMode = FilterMode.Point;
m_rtFB[i].Create();
}
int tid = Shader.PropertyToID("_TmpFrameBuffer");
m_cbCopyFB = new CommandBuffer();
m_cbCopyFB.name = "GBufferRecorder: Copy FrameBuffer";
m_cbCopyFB.GetTemporaryRT(tid, -1, -1, 0, FilterMode.Point);
m_cbCopyFB.Blit(BuiltinRenderTextureType.CurrentActive, tid);
m_cbCopyFB.SetRenderTarget(new RenderTargetIdentifier[] { m_rtFB[0], m_rtFB[1] }, m_rtFB[0]);
m_cbCopyFB.DrawMesh(m_quad, Matrix4x4.identity, m_matCopy, 0, 0);
m_cbCopyFB.ReleaseTemporaryRT(tid);
cam.AddCommandBuffer(CameraEvent.AfterEverything, m_cbCopyFB);
}
if (m_fbComponents.GBuffer)
{
m_rtGB = new RenderTexture[8];
for (int i = 0; i < m_rtGB.Length; ++i)
{
m_rtGB[i] = new RenderTexture(captureWidth, captureHeight, 0, RenderTextureFormat.ARGBHalf);
m_rtGB[i].filterMode = FilterMode.Point;
m_rtGB[i].Create();
}
// clear gbuffer (Unity doesn't clear emission buffer - it is not needed usually)
m_cbClearGB = new CommandBuffer();
m_cbClearGB.name = "GBufferRecorder: Cleanup GBuffer";
if (cam.allowHDR)
{
m_cbClearGB.SetRenderTarget(BuiltinRenderTextureType.CameraTarget);
}
else
{
m_cbClearGB.SetRenderTarget(BuiltinRenderTextureType.GBuffer3);
}
m_cbClearGB.DrawMesh(m_quad, Matrix4x4.identity, m_matCopy, 0, 3);
m_matCopy.SetColor("_ClearColor", cam.backgroundColor);
// copy gbuffer
m_cbCopyGB = new CommandBuffer();
m_cbCopyGB.name = "GBufferRecorder: Copy GBuffer";
m_cbCopyGB.SetRenderTarget(new RenderTargetIdentifier[] {
m_rtGB[0], m_rtGB[1], m_rtGB[2], m_rtGB[3], m_rtGB[4], m_rtGB[5], m_rtGB[6]
}, m_rtGB[0]);
m_cbCopyGB.DrawMesh(m_quad, Matrix4x4.identity, m_matCopy, 0, 2);
cam.AddCommandBuffer(CameraEvent.BeforeGBuffer, m_cbClearGB);
cam.AddCommandBuffer(CameraEvent.BeforeLighting, m_cbCopyGB);
if (m_fbComponents.gbVelocity)
{
m_cbCopyVelocity = new CommandBuffer();
m_cbCopyVelocity.name = "GBufferRecorder: Copy Velocity";
m_cbCopyVelocity.SetRenderTarget(m_rtGB[7]);
m_cbCopyVelocity.DrawMesh(m_quad, Matrix4x4.identity, m_matCopy, 0, 4);
cam.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_cbCopyVelocity);
cam.depthTextureMode = DepthTextureMode.Depth | DepthTextureMode.MotionVectors;
}
}
int framerate = m_targetFramerate;
if (m_fbComponents.frameBuffer) {
if (m_fbComponents.fbColor) m_recorders.Add(new BufferRecorder(m_rtFB[0], 4, "FrameBuffer", framerate));
if (m_fbComponents.fbAlpha) m_recorders.Add(new BufferRecorder(m_rtFB[1], 1, "Alpha", framerate));
}
if (m_fbComponents.GBuffer)
{
if (m_fbComponents.gbAlbedo) { m_recorders.Add(new BufferRecorder(m_rtGB[0], 3, "Albedo", framerate)); }
if (m_fbComponents.gbOcclusion) { m_recorders.Add(new BufferRecorder(m_rtGB[1], 1, "Occlusion", framerate)); }
if (m_fbComponents.gbSpecular) { m_recorders.Add(new BufferRecorder(m_rtGB[2], 3, "Specular", framerate)); }
if (m_fbComponents.gbSmoothness) { m_recorders.Add(new BufferRecorder(m_rtGB[3], 1, "Smoothness", framerate)); }
if (m_fbComponents.gbNormal) { m_recorders.Add(new BufferRecorder(m_rtGB[4], 3, "Normal", framerate)); }
if (m_fbComponents.gbEmission) { m_recorders.Add(new BufferRecorder(m_rtGB[5], 3, "Emission", framerate)); }
if (m_fbComponents.gbDepth) { m_recorders.Add(new BufferRecorder(m_rtGB[6], 1, "Depth", framerate)); }
if (m_fbComponents.gbVelocity) { m_recorders.Add(new BufferRecorder(m_rtGB[7], 2, "Velocity", framerate)); }
}
foreach (var rec in m_recorders)
{
if (!rec.Initialize(m_encoderConfigs, m_outputDir))
{
EndRecording();
return false;
}
}
base.BeginRecording();
Debug.Log("GBufferRecorder: BeginRecording()");
return true;
}
public override void EndRecording()
{
foreach (var rec in m_recorders) { rec.Release(); }
m_recorders.Clear();
var cam = GetComponent<Camera>();
if (m_cbCopyFB != null)
{
cam.RemoveCommandBuffer(CameraEvent.AfterEverything, m_cbCopyFB);
m_cbCopyFB.Release();
m_cbCopyFB = null;
}
if (m_cbClearGB != null)
{
cam.RemoveCommandBuffer(CameraEvent.BeforeGBuffer, m_cbClearGB);
m_cbClearGB.Release();
m_cbClearGB = null;
}
if (m_cbCopyGB != null)
{
cam.RemoveCommandBuffer(CameraEvent.BeforeLighting, m_cbCopyGB);
m_cbCopyGB.Release();
m_cbCopyGB = null;
}
if (m_cbCopyVelocity != null)
{
cam.RemoveCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_cbCopyVelocity);
m_cbCopyVelocity.Release();
m_cbCopyVelocity = null;
}
if (m_rtFB != null)
{
foreach (var rt in m_rtFB) { rt.Release(); }
m_rtFB = null;
}
if (m_rtGB != null)
{
foreach (var rt in m_rtGB) { rt.Release(); }
m_rtGB = null;
}
if (m_recording)
{
Debug.Log("GBufferRecorder: EndRecording()");
}
base.EndRecording();
}
#region impl
#if UNITY_EDITOR
void Reset()
{
m_shCopy = fcAPI.GetFrameBufferCopyShader();
}
#endif // UNITY_EDITOR
IEnumerator OnPostRender()
{
if (m_recording)
{
yield return new WaitForEndOfFrame();
//double timestamp = Time.unscaledTime - m_initialTime;
double timestamp = 1.0 / m_targetFramerate * m_recordedFrames;
foreach (var rec in m_recorders) { rec.Update(timestamp); }
++m_recordedFrames;
}
m_frame++;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using Cottle.Documents.Compiled;
using Cottle.Functions;
namespace Cottle.Documents.Emitted
{
internal class Emitter
{
private static readonly MethodInfo ArgumentsIndex =
Resolver.Method<Func<IReadOnlyList<Value>, Value>>(c => c[default]);
private static readonly MethodInfo FiniteFunctionInvoke0 =
Resolver.Method<Func<FiniteFunction, Value>>(f => f.Invoke0(new(), TextWriter.Null));
private static readonly MethodInfo FiniteFunctionInvoke1 =
Resolver.Method<Func<FiniteFunction, Value>>(f => f.Invoke1(new(), default, TextWriter.Null));
private static readonly MethodInfo FiniteFunctionInvoke2 =
Resolver.Method<Func<FiniteFunction, Value>>(f => f.Invoke2(new(), default, default, TextWriter.Null));
private static readonly MethodInfo FiniteFunctionInvoke3 =
Resolver.Method<Func<FiniteFunction, Value>>(f => f.Invoke3(new(), default, default, default, TextWriter.Null));
private static readonly FieldInfo FrameArguments =
Resolver.Field<Func<Frame, IReadOnlyList<Value>>>(f => f.Arguments);
private static readonly MethodInfo FrameEcho =
Resolver.Method<Func<Frame, string>>(f => f.Echo(default, TextWriter.Null));
private static readonly FieldInfo FrameGlobals = Resolver.Field<Func<Frame, Value[]>>(f => f.Globals);
private static readonly MethodInfo FrameUnwrap = Resolver.Method<Func<Frame, IFunction>>(f => f.Unwrap());
private static readonly MethodInfo FrameWrap = Resolver.Method<Action<Frame>>(f => f.Wrap(Function.Empty));
private static readonly MethodInfo FunctionInvoke =
Resolver.Method<Func<IFunction, Value>>(f => f.Invoke(new(), Array.Empty<Value>(), TextWriter.Null));
private static readonly ConstructorInfo KeyValueConstructor =
Resolver.Constructor<Func<KeyValuePair<Value, Value>>>(() =>
new KeyValuePair<Value, Value>(default, default));
private static readonly IReadOnlyList<OpCode> LoadIntegers = new[]
{
OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5,
OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8
};
private static readonly MethodInfo MapCount =
Resolver.Property<Func<IMap, int>>(m => m.Count).GetMethod!;
private static readonly MethodInfo MapEnumeratorCurrent = Resolver
.Property<Func<IEnumerator<KeyValuePair<Value, Value>>, KeyValuePair<Value, Value>>>(e => e.Current)
.GetMethod!;
private static readonly MethodInfo MapEnumeratorMoveNext =
Resolver.Method<Func<IEnumerator<KeyValuePair<Value, Value>>, bool>>(e => e.MoveNext());
private static readonly MethodInfo MapGetEnumerator =
Resolver.Method<Func<IMap, IEnumerator<KeyValuePair<Value, Value>>>>(m => m.GetEnumerator());
private static readonly MethodInfo MapTryGet =
Resolver.Method<Func<IMap, bool>>(m => m.TryGet(default, out Emitter._value));
private static readonly MethodInfo ObjectToString = Resolver.Method<Func<object, string?>>(o => o.ToString());
private static readonly MethodInfo PairKey =
Resolver.Property<Func<KeyValuePair<Value, Value>, Value>>(p => p.Key).GetMethod!;
private static readonly MethodInfo PairValue =
Resolver.Property<Func<KeyValuePair<Value, Value>, Value>>(p => p.Value).GetMethod!;
private static readonly MethodInfo ReadOnlyListCount =
Resolver.Property<Func<IReadOnlyList<object>, int>>(l => l.Count).GetMethod!;
private static readonly ConstructorInfo StringWriterConstructor =
Resolver.Constructor<Func<StringWriter>>(() => new StringWriter());
private static readonly MethodInfo StringWriterToString =
Resolver.Method<Func<StringWriter, string>>(w => w.ToString());
private static readonly MethodInfo TextWriterWriteObject =
Resolver.Method<Action<TextWriter>>(w => w.Write(default(object)));
private static readonly MethodInfo TextWriterWriteString =
Resolver.Method<Action<TextWriter>>(w => w.Write(default(string)));
private static readonly MethodInfo ValueAsBooleanGet =
Resolver.Property<Func<Value, bool>>(v => v.AsBoolean).GetMethod!;
private static readonly MethodInfo ValueAsFunctionGet =
Resolver.Property<Func<Value, IFunction>>(v => v.AsFunction).GetMethod!;
private static readonly MethodInfo ValueFieldsGet =
Resolver.Property<Func<Value, IMap>>(v => v.Fields).GetMethod!;
private static readonly MethodInfo ValueFromDictionary =
Resolver.Method<Func<IEnumerable<KeyValuePair<Value, Value>>, Value>>(f => Value.FromEnumerable(f));
private static readonly MethodInfo ValueFromString =
Resolver.Method<Func<Value>>(() => Value.FromString(string.Empty));
private static readonly FieldInfo ValueUndefined = Resolver.Field<Func<Value>>(() => Value.Undefined);
private static Value _value;
private readonly Dictionary<Value, int> _constants;
private readonly ILGenerator _generator;
private readonly Dictionary<Type, Stack<LocalBuilder>> _internalLocals;
private readonly Queue<LocalBuilder> _outputs;
private readonly Dictionary<int, LocalBuilder> _symbolLocals;
public Emitter(ILGenerator generator)
{
_constants = new Dictionary<Value, int>();
_generator = generator;
_internalLocals = new Dictionary<Type, Stack<LocalBuilder>>();
_outputs = new Queue<LocalBuilder>();
_symbolLocals = new Dictionary<int, LocalBuilder>();
}
public IReadOnlyList<Value> CreateConstants()
{
var constants = new Value[_constants.Count];
foreach (var pair in _constants)
constants[pair.Value] = pair.Key;
return constants;
}
public Label DeclareLabel()
{
return _generator.DefineLabel();
}
public void EmitBranchAlways(Label label)
{
_generator.Emit(OpCodes.Br, label);
}
public void EmitBranchWhenFalse(Label label)
{
_generator.Emit(OpCodes.Brfalse, label);
}
public void EmitBranchWhenGreaterOrEqual(Label label)
{
_generator.Emit(OpCodes.Bge, label);
}
public void EmitBranchWhenTrue(Label label)
{
_generator.Emit(OpCodes.Brtrue, label);
}
public void EmitCastAs<TValue>()
{
_generator.Emit(OpCodes.Isinst, typeof(TValue));
}
public Local<TValue> EmitDeclareLocalAndLoadAddress<TValue>()
{
return EmitDeclareLocal<TValue>(OpCodes.Ldloca);
}
public Local<TValue> EmitDeclareLocalAndStore<TValue>()
{
return EmitDeclareLocal<TValue>(OpCodes.Stloc);
}
public void EmitDiscard()
{
_generator.Emit(OpCodes.Pop);
}
public void EmitCallFiniteFunctionInvoke0()
{
_generator.Emit(OpCodes.Callvirt, Emitter.FiniteFunctionInvoke0);
}
public void EmitCallFiniteFunctionInvoke1()
{
_generator.Emit(OpCodes.Callvirt, Emitter.FiniteFunctionInvoke1);
}
public void EmitCallFiniteFunctionInvoke2()
{
_generator.Emit(OpCodes.Callvirt, Emitter.FiniteFunctionInvoke2);
}
public void EmitCallFiniteFunctionInvoke3()
{
_generator.Emit(OpCodes.Callvirt, Emitter.FiniteFunctionInvoke3);
}
public void EmitCallFrameEcho()
{
_generator.Emit(OpCodes.Call, Emitter.FrameEcho);
}
public void EmitCallFrameUnwrap()
{
_generator.Emit(OpCodes.Call, Emitter.FrameUnwrap);
}
public void EmitCallFrameWrap()
{
_generator.Emit(OpCodes.Call, Emitter.FrameWrap);
}
public void EmitCallFunctionInvoke()
{
_generator.Emit(OpCodes.Callvirt, Emitter.FunctionInvoke);
}
public void EmitCallMapCount()
{
_generator.Emit(OpCodes.Callvirt, Emitter.MapCount);
}
public void EmitCallMapEnumeratorCurrent()
{
_generator.Emit(OpCodes.Callvirt, Emitter.MapEnumeratorCurrent);
}
public void EmitCallMapEnumeratorMoveNext()
{
_generator.Emit(OpCodes.Callvirt, Emitter.MapEnumeratorMoveNext);
}
public void EmitCallMapGetEnumerator()
{
_generator.Emit(OpCodes.Callvirt, Emitter.MapGetEnumerator);
}
public void EmitCallMapTryGet()
{
_generator.Emit(OpCodes.Callvirt, Emitter.MapTryGet);
}
public void EmitCallObjectToString()
{
_generator.Emit(OpCodes.Constrained, typeof(Value));
_generator.Emit(OpCodes.Callvirt, Emitter.ObjectToString);
}
public void EmitCallPairKey()
{
_generator.Emit(OpCodes.Call, Emitter.PairKey);
}
public void EmitCallPairValue()
{
_generator.Emit(OpCodes.Call, Emitter.PairValue);
}
public void EmitCallStringWriterToString()
{
_generator.Emit(OpCodes.Callvirt, Emitter.StringWriterToString);
}
public void EmitCallTextWriterWriteObject()
{
_generator.Emit(OpCodes.Callvirt, Emitter.TextWriterWriteObject);
}
public void EmitCallTextWriterWriteString()
{
_generator.Emit(OpCodes.Callvirt, Emitter.TextWriterWriteString);
}
public void EmitCallValueAsBoolean()
{
_generator.Emit(OpCodes.Call, Emitter.ValueAsBooleanGet);
}
public void EmitCallValueAsFunction()
{
_generator.Emit(OpCodes.Call, Emitter.ValueAsFunctionGet);
}
public void EmitCallValueFields()
{
_generator.Emit(OpCodes.Call, Emitter.ValueFieldsGet);
}
public void EmitCallValueFromDictionary()
{
_generator.Emit(OpCodes.Call, Emitter.ValueFromDictionary);
}
public void EmitCallValueFromString()
{
_generator.Emit(OpCodes.Call, Emitter.ValueFromString);
}
public void EmitLoadArray<TElement>(int count)
{
EmitLoadInteger(count);
_generator.Emit(OpCodes.Newarr, typeof(TElement));
}
public void EmitLoadBoolean(bool value)
{
EmitLoadInteger(value ? 1 : 0);
}
public void EmitLoadConstant(Value constant)
{
if (!_constants.TryGetValue(constant, out var index))
{
index = _constants.Count;
_constants[constant] = index;
}
_generator.Emit(OpCodes.Ldarg_0);
EmitLoadInteger(index);
_generator.Emit(OpCodes.Callvirt, Emitter.ArgumentsIndex);
}
public void EmitLoadDuplicate()
{
_generator.Emit(OpCodes.Dup);
}
public void EmitLoadElementAddressAtIndex<TElement>()
{
_generator.Emit(OpCodes.Ldelema, typeof(TElement));
}
public void EmitLoadElementValueAtIndex<TElement>()
{
_generator.Emit(OpCodes.Ldelem, typeof(TElement));
}
public void EmitLoadFrame()
{
_generator.Emit(OpCodes.Ldarg_1);
}
public void EmitLoadFrameArgument(int index)
{
_generator.Emit(OpCodes.Ldarg_1);
_generator.Emit(OpCodes.Ldfld, Emitter.FrameArguments);
EmitLoadInteger(index);
_generator.Emit(OpCodes.Ldelem, typeof(Value));
}
public void EmitLoadFrameArgumentLength()
{
_generator.Emit(OpCodes.Ldarg_1);
_generator.Emit(OpCodes.Ldfld, Emitter.FrameArguments);
_generator.Emit(OpCodes.Callvirt, Emitter.ReadOnlyListCount);
}
public void EmitLoadFrameGlobal()
{
_generator.Emit(OpCodes.Ldarg_1);
_generator.Emit(OpCodes.Ldfld, Emitter.FrameGlobals);
}
public void EmitLoadInteger(int value)
{
if (value < Emitter.LoadIntegers.Count)
_generator.Emit(Emitter.LoadIntegers[value]);
else if (value >= sbyte.MinValue && value <= sbyte.MaxValue)
_generator.Emit(OpCodes.Ldc_I4_S, value);
else
_generator.Emit(OpCodes.Ldc_I4, value);
}
public void EmitLoadLocalAddress<TValue>(Local<TValue> local) where TValue : struct
{
_generator.Emit(OpCodes.Ldloca, local.Builder);
}
public void EmitLoadLocalAddressAndRelease<TValue>(Local<TValue> local) where TValue : struct
{
EmitLoadLocalAndRelease(OpCodes.Ldloca, local);
}
public void EmitLoadLocalValue<TValue>(Local<TValue> local)
{
_generator.Emit(OpCodes.Ldloc, local.Builder);
}
public void EmitLoadLocalValueAndRelease<TValue>(Local<TValue> local)
{
EmitLoadLocalAndRelease(OpCodes.Ldloc, local);
}
public void EmitLoadOutput()
{
if (_outputs.Count > 0)
_generator.Emit(OpCodes.Ldloc, _outputs.Peek());
else
_generator.Emit(OpCodes.Ldarg_2);
}
public void EmitLoadResult()
{
_generator.Emit(OpCodes.Ldarg_3);
}
public void EmitLoadString(string value)
{
_generator.Emit(OpCodes.Ldstr, value);
}
public void EmitLoadUndefined()
{
_generator.Emit(OpCodes.Ldsfld, Emitter.ValueUndefined);
}
public void EmitNewKeyValuePair()
{
_generator.Emit(OpCodes.Newobj, Emitter.KeyValueConstructor);
}
public void EmitNewStringWriter()
{
_generator.Emit(OpCodes.Newobj, Emitter.StringWriterConstructor);
}
public void EmitReturn()
{
_generator.Emit(OpCodes.Ret);
}
public void EmitStoreElementAtIndex<TElement>()
{
_generator.Emit(OpCodes.Stelem, typeof(TElement));
}
public void EmitStoreLocal<TValue>(Local<TValue> local)
{
_generator.Emit(OpCodes.Stloc, local.Builder);
}
public void EmitStoreValueAtAddress<TValue>() where TValue : struct
{
_generator.Emit(OpCodes.Stobj, typeof(TValue));
}
public Local<Value> GetOrDeclareLocal(Symbol symbol)
{
if (_symbolLocals.TryGetValue(symbol.Index, out var local))
return new Local<Value>(local);
local = _generator.DeclareLocal(typeof(Value));
_symbolLocals[symbol.Index] = local;
return new Local<Value>(local);
}
public void MarkLabel(Label label)
{
_generator.MarkLabel(label);
}
public void OutputDequeue()
{
_outputs.Dequeue();
}
public void OutputEnqueue(Local<StringWriter> output)
{
_outputs.Enqueue(output.Builder);
}
private Local<TValue> EmitDeclareLocal<TValue>(OpCode opCode)
{
var local = _internalLocals.TryGetValue(typeof(TValue), out var queue) && queue.Count > 0
? queue.Pop()
: _generator.DeclareLocal(typeof(TValue));
_generator.Emit(opCode, local);
return new Local<TValue>(local);
}
private void EmitLoadLocalAndRelease<TValue>(OpCode opCode, Local<TValue> local)
{
_generator.Emit(opCode, local.Builder);
if (!_internalLocals.TryGetValue(typeof(TValue), out var stack))
{
stack = new Stack<LocalBuilder>();
_internalLocals[typeof(TValue)] = stack;
}
stack.Push(local.Builder);
}
}
}
| |
/*
* 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 log4net;
using OpenMetaverse;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Static methods to serialize and deserialize scene objects to and from XML
/// </summary>
public class SceneXmlLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region old xml format
public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
if (fileName.StartsWith("http:") || File.Exists(fileName))
{
XmlTextReader reader = new XmlTextReader(fileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml);
if (newIDS)
{
obj.ResetIDs();
}
//if we want this to be a import method then we need new uuids for the object to avoid any clashes
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
}
}
else
{
throw new Exception("Could not open file " + fileName + " for reading");
}
}
public static void SavePrimsToXml(Scene scene, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
StreamWriter stream = new StreamWriter(file);
int primCount = 0;
stream.WriteLine("<scene>\n");
EntityBase[] entityList = scene.GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Close();
file.Close();
}
#endregion
#region XML2 serialization
// Called by archives (save oar)
public static string SaveGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
//return SceneObjectSerializer.ToXml2Format(grp);
using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, System.Text.Encoding.UTF8))
{
SceneObjectSerializer.SOGToXml2(writer, grp, options);
writer.Flush();
using (StreamReader reader = new StreamReader(mem))
{
mem.Seek(0, SeekOrigin.Begin);
return reader.ReadToEnd();
}
}
}
}
// Called by scene serializer (save xml2)
public static void SavePrimsToXml2(Scene scene, string fileName)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, fileName);
}
// Called by scene serializer (save xml2)
public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
m_log.InfoFormat(
"[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}",
primName, scene.RegionInfo.RegionName, fileName);
EntityBase[] entityList = scene.GetEntities();
List<EntityBase> primList = new List<EntityBase>();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (ent.Name == primName)
{
primList.Add(ent);
}
}
}
SavePrimListToXml2(primList.ToArray(), fileName);
}
// Called by REST Application plugin
public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, stream, min, max);
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
try
{
StreamWriter stream = new StreamWriter(file);
try
{
SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero);
}
finally
{
stream.Close();
}
}
finally
{
file.Close();
}
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
XmlTextWriter writer = new XmlTextWriter(stream);
int primCount = 0;
stream.WriteLine("<scene>\n");
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup g = (SceneObjectGroup)ent;
if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero))
{
Vector3 pos = g.RootPart.WorldPosition;
if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z)
continue;
if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z)
continue;
}
//stream.WriteLine(SceneObjectSerializer.ToXml2Format(g));
SceneObjectSerializer.SOGToXml2(writer, (SceneObjectGroup)ent, new Dictionary<string,object>());
stream.WriteLine();
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Flush();
}
#endregion
#region XML2 deserialization
public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneObjectSerializer.FromXml2Format(xmlString);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="fileName"></param>
public static void LoadPrimsFromXml2(Scene scene, string fileName)
{
LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts);
}
/// <summary>
/// Load prims from the xml2 format. This method will close the reader
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts)
{
XmlDocument doc = new XmlDocument();
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
XmlNode rootNode = doc.FirstChild;
ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = DeserializeGroupFromXml2(aPrimNode.OuterXml);
if (startScripts)
sceneObjects.Add(obj);
}
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using NUnit.Framework;
using Realms;
using Realms.Exceptions;
namespace Tests.Database
{
[TestFixture, Preserve(AllMembers = true)]
#if WINDOWS
[Ignore("ReflectableType is not respected by WPF.")]
#endif
public class ReflectableTypeTests : RealmInstanceTest
{
private const string DogName = "Sharo";
private const string OwnerName = "Peter";
[Test]
public void ReflectableGetRelatedObject_WhenObjectIsValid_ShouldReturnObject()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var topDogProperty = typeInfo.GetDeclaredProperty(nameof(Owner.TopDog));
var getter = topDogProperty.GetMethod;
var topDog = getter.Invoke(owner, null) as Dog;
Assert.That(topDog, Is.Not.Null);
Assert.That(topDog.Name, Is.EqualTo(DogName));
}
[Test]
public void ReflectablePropertyGetValue_WhenObjectIsValid_ShouldReturnObject()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var topDogProperty = typeInfo.GetDeclaredProperty(nameof(Owner.TopDog));
var topDog = topDogProperty.GetValue(owner, null) as Dog;
Assert.That(topDog, Is.Not.Null);
Assert.That(topDog.Name, Is.EqualTo(DogName));
}
[Test]
public void RegularGetRelatedObject_WhenObjectIsValid_ShouldReturnObject()
{
var owner = AddDogAndOwner();
var topDog = owner.TopDog;
Assert.That(topDog, Is.Not.Null);
Assert.That(topDog.Name, Is.EqualTo(DogName));
}
[Test]
public void ReflectableGetRelatedObject_WhenObjectIsRemoved_ShouldReturnNull()
{
var owner = AddDogAndOwner();
_realm.Write(() =>
{
_realm.Remove(owner);
});
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var topDogProperty = typeInfo.GetDeclaredProperty(nameof(Owner.TopDog));
var getter = topDogProperty.GetMethod;
var topDog = getter.Invoke(owner, null);
Assert.That(topDog, Is.Null);
}
[Test]
public void ReflectablePropertyGetValue_WhenObjectIsRemoved_ShouldReturnNull()
{
var owner = AddDogAndOwner();
_realm.Write(() =>
{
_realm.Remove(owner);
});
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var topDogProperty = typeInfo.GetDeclaredProperty(nameof(Owner.TopDog));
var topDog = topDogProperty.GetValue(owner, null);
Assert.That(topDog, Is.Null);
}
[Test]
public void RegularGetRelatedObject_WhenObjectIsRemoved_ShouldThrow()
{
var owner = AddDogAndOwner();
_realm.Write(() =>
{
_realm.Remove(owner);
});
Assert.Throws<RealmInvalidObjectException>(() =>
{
var topDog = owner.TopDog;
});
}
[Test]
public void ReflectableGetTopLevelProperty_WhenObjectIsValid_ShouldReturnValue()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var nameGetter = typeInfo.GetDeclaredProperty(nameof(Owner.Name)).GetMethod;
var name = nameGetter.Invoke(owner, null);
Assert.That(name, Is.EqualTo(OwnerName));
}
[Test]
public void RegularGetTopLevelProperty_WhenObjectIsValid_ShouldReturnValue()
{
var owner = AddDogAndOwner();
Assert.That(owner.Name, Is.EqualTo(OwnerName));
}
[Test]
public void ReflectableGetTopLevelProperty_WhenObjectIsRemoved_ShouldReturnDefault()
{
var owner = AddDogAndOwner();
_realm.Write(() =>
{
_realm.Remove(owner);
});
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var nameGetter = typeInfo.GetDeclaredProperty(nameof(Owner.Name)).GetMethod;
var name = nameGetter.Invoke(owner, null);
Assert.That(name, Is.EqualTo(default(string)));
}
[Test]
public void RegularGetTopLevelProperty_WhenObjectIsRemoved_ShouldReturnDefault()
{
var owner = AddDogAndOwner();
_realm.Write(() =>
{
_realm.Remove(owner);
});
Assert.Throws<RealmInvalidObjectException>(() =>
{
var name = owner.Name;
});
}
[Test]
public void ReflectableSetter_WhenObjectIsValid_ShouldSetValue()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var nameSetter = typeInfo.GetDeclaredProperty(nameof(Owner.Name)).SetMethod;
_realm.Write(() =>
{
nameSetter.Invoke(owner, new[] { "John" });
});
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void ReflectableSetter_WhenNotInTransaction_ShouldCreateTransactionAndCommit()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var nameSetter = typeInfo.GetDeclaredProperty(nameof(Owner.Name)).SetMethod;
nameSetter.Invoke(owner, new[] { "John" });
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void ReflectableSetValue_WhenObjectIsValid_ShouldSetValue()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var pi = typeInfo.GetDeclaredProperty(nameof(Owner.Name));
_realm.Write(() =>
{
pi.SetValue(owner, "John");
});
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void ReflectableSetValue_WhenNotInTransaction_ShouldCreateTransactionAndCommit()
{
var owner = AddDogAndOwner();
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var pi = typeInfo.GetDeclaredProperty(nameof(Owner.Name));
pi.SetValue(owner, "John");
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void Setter_WhenNotInTransaction_ShouldThrow()
{
var owner = AddDogAndOwner();
var setter = owner.GetType().GetProperty(nameof(Owner.Name)).SetMethod;
Assert.That(() =>
{
setter.Invoke(owner, new[] { "John" });
}, Throws.InnerException.TypeOf<RealmInvalidTransactionException>());
}
[Test]
public void Setter_WhenInTransaction_ShouldSetValue()
{
var owner = AddDogAndOwner();
var setter = owner.GetType().GetProperty(nameof(Owner.Name)).SetMethod;
_realm.Write(() =>
{
setter.Invoke(owner, new[] { "John" });
});
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void SetValue_WhenNotInTransaction_ShouldThrow()
{
var owner = AddDogAndOwner();
var pi = owner.GetType().GetProperty(nameof(Owner.Name));
Assert.That(() =>
{
pi.SetValue(owner, "John");
}, Throws.InnerException.TypeOf<RealmInvalidTransactionException>());
}
[Test]
public void SetValue_WhenInTransaction_ShouldSetValue()
{
var owner = AddDogAndOwner();
var pi = owner.GetType().GetProperty(nameof(Owner.Name));
_realm.Write(() =>
{
pi.SetValue(owner, "John");
});
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void ReflectableSetter_WhenObjectIsInvalid_ShouldThrow()
{
var owner = AddDogAndOwner();
_realm.Write(() =>
{
_realm.Remove(owner);
});
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var nameSetter = typeInfo.GetDeclaredProperty(nameof(Owner.Name)).SetMethod;
Assert.That(() =>
{
_realm.Write(() =>
{
nameSetter.Invoke(owner, new[] { "John" });
});
}, Throws.InnerException.TypeOf<RealmInvalidObjectException>());
}
[Test]
public void ReflectableSetter_WhenObjectIsStandalone_ShouldSetValue()
{
var owner = AddDogAndOwner(add: false);
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var pi = typeInfo.GetDeclaredProperty(nameof(Owner.Name));
pi.SetValue(owner, "John");
Assert.That(owner.Name, Is.EqualTo("John"));
}
[Test]
public void ReflectableGetter_WhenObjectIsStandalone_ShouldGetValue()
{
var owner = AddDogAndOwner(add: false);
var typeInfo = ((IReflectableType)owner).GetTypeInfo();
var pi = typeInfo.GetDeclaredProperty(nameof(Owner.Name));
var name = pi.GetValue(owner);
Assert.That(name, Is.EqualTo(OwnerName));
}
private Owner AddDogAndOwner(bool add = true)
{
var owner = new Owner
{
TopDog = new Dog
{
Name = DogName
},
Name = OwnerName
};
if (add)
{
_realm.Write(() =>
{
_realm.Add(owner);
});
}
return owner;
}
}
}
| |
using Lucene.Net.Documents;
namespace Lucene.Net.Search
{
using Lucene.Net.Support;
using NUnit.Framework;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestBooleanOr : LuceneTestCase
{
private static string FIELD_T = "T";
private static string FIELD_C = "C";
private TermQuery T1 = new TermQuery(new Term(FIELD_T, "files"));
private TermQuery T2 = new TermQuery(new Term(FIELD_T, "deleting"));
private TermQuery C1 = new TermQuery(new Term(FIELD_C, "production"));
private TermQuery C2 = new TermQuery(new Term(FIELD_C, "optimize"));
private IndexSearcher Searcher = null;
private Directory Dir;
private IndexReader Reader;
private int Search(Query q)
{
QueryUtils.Check(Random(), q, Searcher);
return Searcher.Search(q, null, 1000).TotalHits;
}
[Test]
public virtual void TestElements()
{
Assert.AreEqual(1, Search(T1));
Assert.AreEqual(1, Search(T2));
Assert.AreEqual(1, Search(C1));
Assert.AreEqual(1, Search(C2));
}
/// <summary>
/// <code>T:files T:deleting C:production C:optimize </code>
/// it works.
/// </summary>
[Test]
public virtual void TestFlat()
{
BooleanQuery q = new BooleanQuery();
q.Add(new BooleanClause(T1, BooleanClause.Occur.SHOULD));
q.Add(new BooleanClause(T2, BooleanClause.Occur.SHOULD));
q.Add(new BooleanClause(C1, BooleanClause.Occur.SHOULD));
q.Add(new BooleanClause(C2, BooleanClause.Occur.SHOULD));
Assert.AreEqual(1, Search(q));
}
/// <summary>
/// <code>(T:files T:deleting) (+C:production +C:optimize)</code>
/// it works.
/// </summary>
[Test]
public virtual void TestParenthesisMust()
{
BooleanQuery q3 = new BooleanQuery();
q3.Add(new BooleanClause(T1, BooleanClause.Occur.SHOULD));
q3.Add(new BooleanClause(T2, BooleanClause.Occur.SHOULD));
BooleanQuery q4 = new BooleanQuery();
q4.Add(new BooleanClause(C1, BooleanClause.Occur.MUST));
q4.Add(new BooleanClause(C2, BooleanClause.Occur.MUST));
BooleanQuery q2 = new BooleanQuery();
q2.Add(q3, BooleanClause.Occur.SHOULD);
q2.Add(q4, BooleanClause.Occur.SHOULD);
Assert.AreEqual(1, Search(q2));
}
/// <summary>
/// <code>(T:files T:deleting) +(C:production C:optimize)</code>
/// not working. results NO HIT.
/// </summary>
[Test]
public virtual void TestParenthesisMust2()
{
BooleanQuery q3 = new BooleanQuery();
q3.Add(new BooleanClause(T1, BooleanClause.Occur.SHOULD));
q3.Add(new BooleanClause(T2, BooleanClause.Occur.SHOULD));
BooleanQuery q4 = new BooleanQuery();
q4.Add(new BooleanClause(C1, BooleanClause.Occur.SHOULD));
q4.Add(new BooleanClause(C2, BooleanClause.Occur.SHOULD));
BooleanQuery q2 = new BooleanQuery();
q2.Add(q3, BooleanClause.Occur.SHOULD);
q2.Add(q4, BooleanClause.Occur.MUST);
Assert.AreEqual(1, Search(q2));
}
/// <summary>
/// <code>(T:files T:deleting) (C:production C:optimize)</code>
/// not working. results NO HIT.
/// </summary>
[Test]
public virtual void TestParenthesisShould()
{
BooleanQuery q3 = new BooleanQuery();
q3.Add(new BooleanClause(T1, BooleanClause.Occur.SHOULD));
q3.Add(new BooleanClause(T2, BooleanClause.Occur.SHOULD));
BooleanQuery q4 = new BooleanQuery();
q4.Add(new BooleanClause(C1, BooleanClause.Occur.SHOULD));
q4.Add(new BooleanClause(C2, BooleanClause.Occur.SHOULD));
BooleanQuery q2 = new BooleanQuery();
q2.Add(q3, BooleanClause.Occur.SHOULD);
q2.Add(q4, BooleanClause.Occur.SHOULD);
Assert.AreEqual(1, Search(q2));
}
[SetUp]
public override void SetUp()
{
base.SetUp();
//
Dir = NewDirectory();
//
RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir);
//
Document d = new Document();
d.Add(NewField(FIELD_T, "Optimize not deleting all files", TextField.TYPE_STORED));
d.Add(NewField(FIELD_C, "Deleted When I run an optimize in our production environment.", TextField.TYPE_STORED));
//
writer.AddDocument(d);
Reader = writer.Reader;
//
Searcher = NewSearcher(Reader);
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
Reader.Dispose();
Dir.Dispose();
base.TearDown();
}
[Test]
public virtual void TestBooleanScorerMax()
{
Directory dir = NewDirectory();
RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
int docCount = AtLeast(10000);
for (int i = 0; i < docCount; i++)
{
Document doc = new Document();
doc.Add(NewField("field", "a", TextField.TYPE_NOT_STORED));
riw.AddDocument(doc);
}
riw.ForceMerge(1);
IndexReader r = riw.Reader;
riw.Dispose();
IndexSearcher s = NewSearcher(r);
BooleanQuery bq = new BooleanQuery();
bq.Add(new TermQuery(new Term("field", "a")), BooleanClause.Occur.SHOULD);
bq.Add(new TermQuery(new Term("field", "a")), BooleanClause.Occur.SHOULD);
Weight w = s.CreateNormalizedWeight(bq);
Assert.AreEqual(1, s.IndexReader.Leaves.Count);
BulkScorer scorer = w.BulkScorer(s.IndexReader.Leaves[0], false, null);
FixedBitSet hits = new FixedBitSet(docCount);
AtomicInteger end = new AtomicInteger();
Collector c = new CollectorAnonymousInnerClassHelper(this, scorer, hits, end);
while (end.Get() < docCount)
{
int inc = TestUtil.NextInt(Random(), 1, 1000);
end.AddAndGet(inc);
scorer.Score(c, end.Get());
}
Assert.AreEqual(docCount, hits.Cardinality());
r.Dispose();
dir.Dispose();
}
private class CollectorAnonymousInnerClassHelper : Collector
{
private readonly TestBooleanOr OuterInstance;
private BulkScorer scorer;
private FixedBitSet Hits;
private AtomicInteger End;
public CollectorAnonymousInnerClassHelper(TestBooleanOr outerInstance, BulkScorer scorer, FixedBitSet hits, AtomicInteger end)
{
this.OuterInstance = outerInstance;
this.scorer = scorer;
this.Hits = hits;
this.End = end;
}
public override AtomicReaderContext NextReader
{
set
{
}
}
public override void Collect(int doc)
{
Assert.IsTrue(doc < End.Get(), "collected doc=" + doc + " beyond max=" + End);
Hits.Set(doc);
}
public override Scorer Scorer
{
set
{
}
}
public override bool AcceptsDocsOutOfOrder()
{
return true;
}
}
}
}
| |
// 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.Search
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Client that can be used to manage and query indexes and documents, as
/// well as manage other resources, on an Azure Search service.
/// </summary>
public partial class SearchServiceClient : ServiceClient<SearchServiceClient>, ISearchServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IDataSourcesOperations.
/// </summary>
public virtual IDataSourcesOperations DataSources { get; private set; }
/// <summary>
/// Gets the IIndexersOperations.
/// </summary>
public virtual IIndexersOperations Indexers { get; private set; }
/// <summary>
/// Gets the IIndexesOperations.
/// </summary>
public virtual IIndexesOperations Indexes { get; private set; }
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SearchServiceClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SearchServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SearchServiceClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SearchServiceClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchServiceClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchServiceClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchServiceClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SearchServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SearchServiceClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.DataSources = new DataSourcesOperations(this);
this.Indexers = new IndexersOperations(this);
this.Indexes = new IndexesOperations(this);
this.BaseUri = new Uri("http://localhost");
this.ApiVersion = "2015-02-28-Preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Analyzer>("@odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Analyzer>("@odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Tokenizer>("@odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Tokenizer>("@odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<TokenFilter>("@odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<TokenFilter>("@odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<CharFilter>("@odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<CharFilter>("@odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DataChangeDetectionPolicy>("@odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DataChangeDetectionPolicy>("@odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DataDeletionDetectionPolicy>("@odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DataDeletionDetectionPolicy>("@odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ScoringFunction>("type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ScoringFunction>("type"));
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
/*-----------------------------------------------------------------------------------------
C#Prolog -- Copyright (C) 2007-2009 John Pool -- j.pool@ision.nl
Contributions 2009 by Lars Iwer -- lars.iwer@inf.tu-dresden.de
This library is free software; you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation; either version
2 of the License, or any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for details, or enter 'license.' at the command prompt.
-------------------------------------------------------------------------------------------*/
using System;
using System.Text;
namespace Prolog
{
/*
--------
TermNode
--------
A TermNode serves two purposes: to store the goals of a query (the TermNode proper)
and to store predicates (clauses)
A goal list is constructed as a simple chained list of TermNodes. This makes it easy
(and also more efficient in terms of GC) to revert to a previous state upon backtracking
(in contrast to e.g. an ArrayList).
A predicate consists of one or more clauses. A clause consist of a head and optionally a
body. A head is a term, the body is a sequence of terms. A predicate is stored as a chain
of TermNodes, where each TermNode represents a clause. These TermNodes are linked via the
nextClause field. In each clause/TermNode the clause head is stored in term, and the
clause body (which may be null) in nextNode.
*/
public class TermNode
{
#region private fields
private BI builtinId = BI.none;
#endregion
#region protected properties
protected Term term; // for a ClauseNode: predicate head
protected TermNode nextNode = null; // next node in the chain
protected ClauseNode nextClause = null; // next predicate clause (for a TermNode: advanced upon backtracking)
protected PredicateDescr predDescr;
protected int level = 0; // debugging (for indentation)
#endregion
#region public properties
public int Level { get { return level; } set { level = value; } }
public Term Term { get { return term; } }
public TermNode NextNode { get { return nextNode; } set { nextNode = value; } }
public virtual ClauseNode NextClause { get { return nextClause; } set { nextClause = value; } }
#if persistent
public bool IsPersistent { get { return PredDescr == null ? false : PredDescr is PersistentPredDescr; } }
#endif
public bool Spied { get { return PredDescr == null ? false : PredDescr.Spied; } }
public SpyPort SpyPort { get { return PredDescr == null ? SpyPort.none : PredDescr.SpyPort; } }
public BI BuiltinId { get { return builtinId; } set { builtinId = value; } }
public PredicateDescr PredDescr { get { return predDescr; } set { predDescr = value; } }
#endregion
public TermNode()
{
}
public TermNode(Term t)
{
term = t;
}
public TermNode(Term t, int l)
{
term = t;
level = l;
}
public TermNode(string tag) // builtin predicates
{
try
{
builtinId = (BI)Enum.Parse(typeof(BI), tag, false);
}
catch
{
PrologIO.Error("Unknown builtin-tag {0}", tag);
}
}
public TermNode(Term t, TermNode n)
{
term = t;
nextNode = n;
}
public bool FindPredicateDefinition(PredicateStorage predicateStorage)
{
return FindPredicateDefinition(predicateStorage, null);
}
// put the predicate definition (if found) into the TermNode if it is not already there
public bool FindPredicateDefinition(PredicateStorage predicateStorage, Term whereTerm) // whereTerm != null : for persistent predicates only
{
if (predDescr == null) predDescr = predicateStorage[term.KbKey];
if (predDescr == null) return false;
#if arg1index
Term arg;
if (predDescr.IsFirstArgIndexed)
{
if ((arg = term.Arg (0)).IsVar)
nextClause = predDescr.FirstArgVarClause ();
else // not a variable
{
nextClause = predDescr.FirstArgNonvarClause (arg.Functor);
// check whether there is an indexed var clause
if (nextClause == null) nextClause = predDescr.FirstArgVarClause ();
// if the above failed, the entire predicate fails (no unification possible)
if (nextClause == null) nextClause = ClauseNode.FAIL; // "fail."
}
if (nextClause == null)
nextClause = predDescr.GetClauseList (term, whereTerm); // GetClauseList: in PredicateStorage
}
else // not indexed
#endif
nextClause = predDescr.GetClauseList(term, whereTerm); // GetClauseList: in PredicateStorage
return true;
}
public void Append(Term t)
{
if (term == null) { term = t; return; } // empty list
TermNode tail = this;
TermNode next = nextNode;
while (next != null)
{
tail = next;
next = next.nextNode;
}
tail.nextNode = new TermNode(t);
}
public virtual TermNode Append(TermNode t)
{
TermNode tail = this;
TermNode next = nextNode;
while (next != null) // get the last TermNode
{
tail = next;
next = next.nextNode;
}
tail.nextNode = t;
return this;
}
public void Clear()
{
term = null;
nextNode = null;
nextClause = null;
level = 0;
}
public Term ToList()
{
if (term == null) // last Term of TermNode
return Term.NULLLIST; // [];
else if (nextNode == null)
return new Term(Parser.DOT, term, Term.NULLLIST, FType.comp, OType.xfy, 100); // [];
else
return new Term(Parser.DOT, term, nextNode.ToList(), FType.comp, OType.xfy, 100);
}
public override string ToString()
{
return ToString(2);
}
public virtual string ToString(int indent)
{
return (term == null) ? null : new String(' ', 2 * indent) + term.ToString() +
(nextNode == null ? null : ",\n" + nextNode.ToString(indent));
}
}
/*
----------
ClauseNode
----------
*/
public class ClauseNode : TermNode
{
protected double prob = 1.0d;
public double Prob { get { return prob; } }
private long timestamp = 0L;
public long Timestamp {get { return timestamp; }}
public ClauseNode(Term t, TermNode body, double p) :
this(t, body)
{
timestamp = DateTime.Now.Ticks;
prob = p;
}
public ClauseNode(Term t, TermNode body, double p, long ts) :
this(t, body)
{
timestamp = ts;
prob = p;
}
public ClauseNode(Term t, TermNode body)
: base(t, body)
{
}
public ClauseNode CleanUp() // renumbers all terms
{
return this;
}
public override string ToString() // list the terms (connected by NextNode) of a single clause
{
StringBuilder sb = new StringBuilder("\n" + term.ToString());
bool first = true;
TermNode tl = nextNode;
if (tl == null) return sb.ToString() + " (Prob: " + prob + ").\n";
while (true)
{
if (first) sb.Append(" :-");
sb.Append ("\n " + tl.Term + " (Prob: " + prob + ")");
if ((tl = tl.NextNode) == null)
return sb.ToString() + ".\n";
else if (!first)
sb.AppendFormat(",");
first = false;
}
}
public static ClauseNode FAIL = new ClauseNode(Term.FAIL, null);
}
#if persistent
public class PersistentClauseNode : ClauseNode
{
private DataRowCollection dataRowCollection;
private int rowNo;
private int rowNoMax;
public PersistentClauseNode (DataRowCollection drc, int clauseNo, PredicateDescr pd) : base (null, null)
{
dataRowCollection = drc;
rowNo = clauseNo;
rowNoMax = drc.Count-1;
nextClause = null;
term = DataRowAsTerm (rowNo);
predDescr = pd;
}
private Term DataRowAsTerm (int rowNo)
{
DataRow row = dataRowCollection [rowNo];
// caching does not work !!!!!!!!!!!!!!!!! (Conversion to Term fails for unknown reason)
//if (row [0] != DBNull.Value) return (Term)row [0.Value]; // return cached value, else construct value into row[0]
PersistentPredDescr ppd = (PersistentPredDescr)predDescr;
DbMetaDataCollection mdc = ppd.MetaDataCollection;
// construct the term, by inspecting each argument of the input term.
// If it is a Var: take the corresponding value from the result set row, otherwise: simply copy the argument
int colNo = 0;
int nCols = ppd.Query.Arity;
Term[] args = new Term [nCols];
for (int i = 0; i < nCols; i++)
{
Term a = ppd.Query.Args [i];
if (a.IsVar)
args [i] = DbAccess.DbScalarToTerm (row[1+colNo++], mdc [i].DbType, a.FType, ppd.DbEntity);
else
args [i] = a;
}
Term rowTerm = new Term (ppd.Name, args);
row [0] = rowTerm; // cache /// BUT DOES NOT WORK
return rowTerm;
}
public override ClauseNode NextClause
{
get
{
if (nextClause == null)
return (rowNo == rowNoMax) ? null : (nextClause = new PersistentClauseNode (dataRowCollection, rowNo+1, predDescr));
else
return nextClause; // cached
}
}
}
#endif
/*
--------
SpyPoint
--------
*/
// pushed on the VarStack to detect failure, inserted in the goalNode to detect exit.
class SpyPoint : TermNode // TermNode only used as type-compatible vehicle for port and saveGoal
{
private SpyPort port;
public SpyPort Port { get { return port; } }
private TermNode saveGoal;
public TermNode SaveGoal { get { return saveGoal; } }
public SpyPoint(SpyPort p, TermNode g)
: base()
{
port = p;
saveGoal = g;
level = g.Level;
}
public void Kill()
{
port = SpyPort.none;
}
public override string ToString()
{
return "[" + port + "-spypoint] " + saveGoal.Term.ToString() + " ...";
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.Shell;
using Microsoft.Win32;
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.VisualStudio;
using System.Globalization;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
namespace Microsoft.VisualStudio.FSharp.LanguageService {
internal enum IndentingStyle {
None,
Block,
Smart
}
/// <summary>
/// LanguagePreferences encapsulates the standard General and Tab settings for a language service
/// and provides a way of getting and setting the values. It is expected that you
/// will have one global LanguagePreferences created by your package. The General and Tabs
/// settings are automatically persisted in .vssettings files by the core editor package.
/// All you need to do is register your language under AutomationProperties/TextEditor
/// and specify:
/// <code>
/// YourLanguage = s '%YourLocalizedName%'
/// {
/// val Name = s 'YourLanguage'
/// val Package = s '{F5E7E720-1401-11D1-883B-0000F87579D2}'
/// val ProfileSave = d 1
/// val ResourcePackage = s '%YourPackage%'
/// }
/// </code>
/// Therefore this class hides all it's properties from user setting persistence using
/// DesignerSerializationVisibility.Hidden. This is so that if you give this object
/// to the Package.ExportSettings method as the AutomationObject then it will only
/// write out your new settings which is what you want, otherwise the General and Tab
/// settings will appear in two places in the .vsssettings file.
/// </summary>
[CLSCompliant(false), ComVisible(true), Guid("934a92fd-b63a-49c7-9284-11aec8c1e03f")]
public class LanguagePreferences : IVsTextManagerEvents2, IDisposable {
IServiceProvider site;
Guid langSvc;
LANGPREFERENCES2 prefs;
NativeMethods.ConnectionPointCookie connection;
bool enableCodeSense;
bool enableMatchBraces;
bool enableQuickInfo;
bool enableShowMatchingBrace;
bool enableMatchBracesAtCaret;
bool enableFormatSelection;
bool enableCommenting;
int maxErrorMessages;
int codeSenseDelay;
bool enableAsyncCompletion;
bool autoOutlining;
int maxRegionTime;
_HighlightMatchingBraceFlags braceFlags;
string name;
/// <summary>
/// Gets the language preferences.
/// </summary>
internal LanguagePreferences(IServiceProvider site, Guid langSvc, string name) {
this.site = site;
this.langSvc = langSvc;
this.name = name;
}
internal LanguagePreferences() { }
protected string LanguageName {
get { return this.name; }
set { this.name = value; }
}
/// <summary>
/// This property is not public for a reason. If it were public it would
/// get called during LoadSettingsFromStorage which will break it.
/// Instead use GetSite().
/// </summary>
protected IServiceProvider Site {
get { return this.site; }
set { this.site = value; }
}
public IServiceProvider GetSite() {
return this.site;
}
// Our base language service perferences (from Babel originally)
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableCodeSense {
get { return this.enableCodeSense; }
set { this.enableCodeSense = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableMatchBraces {
get {
return this.enableMatchBraces;
}
set { this.enableMatchBraces = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableQuickInfo {
get { return this.enableQuickInfo; }
set { this.enableQuickInfo = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableShowMatchingBrace {
get { return this.enableShowMatchingBrace; }
set { this.enableShowMatchingBrace = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableMatchBracesAtCaret {
get { return this.enableMatchBracesAtCaret; }
set { this.enableMatchBracesAtCaret = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int MaxErrorMessages {
get { return this.maxErrorMessages; }
set { this.maxErrorMessages = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int CodeSenseDelay {
get { return this.codeSenseDelay; }
set { this.codeSenseDelay = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableAsyncCompletion {
get { return this.enableAsyncCompletion; }
set { this.enableAsyncCompletion = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableFormatSelection {
get { return this.enableFormatSelection; }
set { this.enableFormatSelection = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableCommenting {
get { return this.enableCommenting; }
set { this.enableCommenting = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int MaxRegionTime {
get { return this.maxRegionTime; }
set { this.maxRegionTime = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public _HighlightMatchingBraceFlags HighlightMatchingBraceFlags {
get { return this.braceFlags; }
set { this.braceFlags = value; }
}
public virtual void Init() {
ILocalRegistry3 localRegistry = site.GetService(typeof(SLocalRegistry)) as ILocalRegistry3;
string root = null;
if (localRegistry != null) {
NativeMethods.ThrowOnFailure(localRegistry.GetLocalRegistryRoot(out root));
}
if (root != null) {
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(root, false)) {
if (key != null) {
InitMachinePreferences(key, name);
}
}
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(root, false)) {
if (key != null) {
InitUserPreferences(key, name);
}
}
}
Connect();
localRegistry = null;
}
public virtual void InitUserPreferences(RegistryKey key, string name) {
this.GetLanguagePreferences();
}
public int GetIntegerValue(RegistryKey key, string name, int def) {
object o = key.GetValue(name);
if (o is int) return (int)o;
if (o is string) return int.Parse((string)o, CultureInfo.InvariantCulture);
return def;
}
public bool GetBooleanValue(RegistryKey key, string name, bool def) {
object o = key.GetValue(name);
if (o is int) return ((int)o != 0);
if (o is string) return bool.Parse((string)o);
return def;
}
public virtual void InitMachinePreferences(RegistryKey key, string name) {
using (RegistryKey keyLanguage = key.OpenSubKey("languages\\language services\\" + name, false)) {
if (keyLanguage != null) {
this.EnableCodeSense = GetBooleanValue(keyLanguage, "CodeSense", true);
this.EnableMatchBraces = GetBooleanValue(keyLanguage, "MatchBraces", true);
this.EnableQuickInfo = GetBooleanValue(keyLanguage, "QuickInfo", true);
this.EnableShowMatchingBrace = GetBooleanValue(keyLanguage, "ShowMatchingBrace", true);
this.EnableMatchBracesAtCaret = GetBooleanValue(keyLanguage, "MatchBracesAtCaret", true);
this.MaxErrorMessages = GetIntegerValue(keyLanguage, "MaxErrorMessages", 10);
this.CodeSenseDelay = GetIntegerValue(keyLanguage, "CodeSenseDelay", 1000);
this.EnableAsyncCompletion = GetBooleanValue(keyLanguage, "EnableAsyncCompletion", true);
this.EnableFormatSelection = GetBooleanValue(keyLanguage, "EnableFormatSelection", false);
this.EnableCommenting = GetBooleanValue(keyLanguage, "EnableCommenting", true);
this.AutoOutlining = GetBooleanValue(keyLanguage, "AutoOutlining", true);
this.MaxRegionTime = GetIntegerValue(keyLanguage, "MaxRegionTime", 2000); // 2 seconds
this.braceFlags = (_HighlightMatchingBraceFlags)GetIntegerValue(keyLanguage, "HighlightMatchingBraceFlags", (int)_HighlightMatchingBraceFlags.HMB_USERECTANGLEBRACES);
}
}
}
public virtual void Dispose() {
Disconnect();
site = null;
}
// General tab
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AutoListMembers {
get { return prefs.fAutoListMembers != 0; }
set { prefs.fAutoListMembers = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool HideAdvancedMembers {
get { return prefs.fHideAdvancedAutoListMembers != 0; }
set { prefs.fHideAdvancedAutoListMembers = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ParameterInformation {
get { return prefs.fAutoListParams != 0; }
set { prefs.fAutoListParams = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool VirtualSpace {
get { return prefs.fVirtualSpace != 0; }
set { prefs.fVirtualSpace = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool WordWrap {
get { return prefs.fWordWrap != 0; }
set { prefs.fWordWrap = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool WordWrapGlyphs {
get { return (int)prefs.fWordWrapGlyphs != 0; }
set { prefs.fWordWrapGlyphs = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CutCopyBlankLines {
get { return (int)prefs.fCutCopyBlanks != 0; }
set { prefs.fCutCopyBlanks = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool LineNumbers {
get { return prefs.fLineNumbers != 0; }
set { prefs.fLineNumbers = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool EnableLeftClickForURLs {
get { return prefs.fHotURLs != 0; }
set { prefs.fHotURLs = (uint)(value ? 1 : 0); }
}
// Tabs tab
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal IndentingStyle IndentStyle {
get { return (IndentingStyle)prefs.IndentStyle; }
set { prefs.IndentStyle = (vsIndentStyle)value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int TabSize {
get { return (int)prefs.uTabSize; }
set { prefs.uTabSize = (uint)value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int IndentSize {
get { return (int)prefs.uIndentSize; }
set { prefs.uIndentSize = (uint)value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool InsertTabs {
get { return prefs.fInsertTabs != 0; }
set { prefs.fInsertTabs = (uint)(value ? 1 : 0); }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ShowNavigationBar {
get { return (int)prefs.fDropdownBar != 0; }
set { prefs.fDropdownBar = (uint)(value ? 1 : 0); }
}
public bool AutoOutlining {
get { return this.autoOutlining; }
set { this.autoOutlining = value; }
}
public virtual void GetLanguagePreferences() {
IVsTextManager textMgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager;
if (textMgr != null) {
this.prefs.guidLang = langSvc;
IVsTextManager2 textMgr2 = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
if (textMgr2 != null) {
LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1];
langPrefs2[0] = this.prefs;
if (NativeMethods.Succeeded(textMgr2.GetUserPreferences2(null, null, langPrefs2, null))) {
this.prefs = langPrefs2[0];
} else {
Debug.Assert(false, "textMgr2.GetUserPreferences2");
}
}
}
}
public virtual void Apply() {
IVsTextManager2 textMgr2 = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
if (textMgr2 != null) {
this.prefs.guidLang = langSvc;
LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1];
langPrefs2[0] = this.prefs;
if (!NativeMethods.Succeeded(textMgr2.SetUserPreferences2(null, null, langPrefs2, null))) {
Debug.Assert(false, "textMgr2.SetUserPreferences2");
}
}
}
private void Connect() {
if (this.connection == null && this.site != null) {
IVsTextManager2 textMgr2 = this.site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
if (textMgr2 != null) {
this.connection = new NativeMethods.ConnectionPointCookie(textMgr2, (IVsTextManagerEvents2)this, typeof(IVsTextManagerEvents2));
}
}
}
private void Disconnect() {
if (this.connection != null) {
this.connection.Dispose();
this.connection = null;
}
}
public virtual int OnRegisterMarkerType(int iMarkerType) {
return NativeMethods.S_OK;
}
public virtual int OnRegisterView(IVsTextView view) {
return NativeMethods.S_OK;
}
public virtual int OnUnregisterView(IVsTextView view) {
return NativeMethods.S_OK;
}
public virtual int OnReplaceAllInFilesBegin() {
return NativeMethods.S_OK;
}
public virtual int OnReplaceAllInFilesEnd() {
return NativeMethods.S_OK;
}
public virtual int OnUserPreferencesChanged2(VIEWPREFERENCES2[] viewPrefs, FRAMEPREFERENCES2[] framePrefs, LANGPREFERENCES2[] langPrefs, FONTCOLORPREFERENCES2[] fontColorPrefs) {
if (langPrefs != null && langPrefs.Length > 0 && langPrefs[0].guidLang == this.langSvc) {
this.prefs = langPrefs[0];
}
return NativeMethods.S_OK;
}
}
}
| |
// 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.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientHandler_ServerCertificates_Test
{
[Fact]
public async Task NoCallback_ValidCertificate_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { HttpTestServers.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
HttpTestServers.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:HttpTestServers.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer)));
}
}
[Theory]
[InlineData(HttpTestServers.ExpiredCertRemoteServer)]
[InlineData(HttpTestServers.SelfSignedCertRemoteServer)]
[InlineData(HttpTestServers.WrongHostNameCertRemoteServer)]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[Fact]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.RevokedCertRemoteServer));
}
}
[ActiveIssue(7812, PlatformID.Windows)]
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[InlineData(HttpTestServers.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors)]
[InlineData(HttpTestServers.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors)]
[InlineData(HttpTestServers.WrongHostNameCertRemoteServer, SslPolicyErrors.RemoteCertificateNameMismatch)]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[PlatformSpecific(PlatformID.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
private static bool BackendSupportsCustomCertificateHandling =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
(CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.List.Contains(T)
/// </summary>
public class ListContains
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");
try
{
int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 };
List<int> listObject = new List<int>(iArray);
int i = this.GetInt32(0, 10);
if (!listObject.Contains(i))
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,The i is: " + i);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is a referece type of string");
try
{
string[] strArray = { "apple", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
if (!listObject.Contains("dog"))
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is custom type");
try
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();
MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 };
List<MyClass> listObject = new List<MyClass>(mc);
if (!listObject.Contains(myclass1))
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: The list does not contain the element");
try
{
char[] chArray = { '1', '9', '3', '6', '5', '8', '7', '2', '4' };
List<char> listObject = new List<char>(chArray);
if (listObject.Contains('t'))
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: The argument is a null reference");
try
{
string[] strArray = { "apple", "banana", "chocolate", null, "food" };
List<string> listObject = new List<string>(strArray);
if (!listObject.Contains(null))
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
#endregion
#endregion
public static int Main()
{
ListContains test = new ListContains();
TestLibrary.TestFramework.BeginTestCase("ListContains");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
public class MyClass
{
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebConfigurationHost.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
#define YES
namespace System.Web.Configuration {
using System.Collections;
using System.Configuration.Internal;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Web;
using System.Web.Compilation;
using System.Web.Configuration.Internal;
using System.Web.Hosting;
using System.Web.Util;
using System.Xml;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Build.Utilities;
//
// Configuration host for web applications.
//
internal sealed class WebConfigurationHost : DelegatingConfigHost, IInternalConfigWebHost {
const string InternalHostTypeName = "System.Configuration.Internal.InternalConfigHost, " + AssemblyRef.SystemConfiguration;
const string InternalConfigConfigurationFactoryTypeName = "System.Configuration.Internal.InternalConfigConfigurationFactory, " + AssemblyRef.SystemConfiguration;
internal const string MachineConfigName = "machine";
internal const string MachineConfigPath = "machine";
internal const string RootWebConfigName = "webroot";
internal const string RootWebConfigPath = "machine/webroot";
internal const char PathSeparator = '/';
internal const string DefaultSiteID = "1";
private static readonly string RootWebConfigPathAndPathSeparator = RootWebConfigPath + PathSeparator;
private static readonly string RootWebConfigPathAndDefaultSiteID = RootWebConfigPathAndPathSeparator + DefaultSiteID;
internal static readonly char[] s_slashSplit;
private static IInternalConfigConfigurationFactory s_configurationFactory;
private static string s_defaultSiteName;
private Hashtable _fileChangeCallbacks; // filename -> arraylist of filechangecallbacks
private IConfigMapPath _configMapPath; // mappath implementation
private IConfigMapPath2 _configMapPath2; // mappath implementation that supports VirtualPath
private VirtualPath _appPath; // the application's path
private string _appSiteName; // the application's site name
private string _appSiteID; // the application's site ID
private string _appConfigPath; // the application's configPath
private string _machineConfigFile;
private string _rootWebConfigFile;
#if DBG
private bool _inited;
#endif
static WebConfigurationHost() {
s_slashSplit = new char[PathSeparator];
}
static internal string DefaultSiteName {
get {
if (s_defaultSiteName == null) {
s_defaultSiteName = SR.GetString(SR.DefaultSiteName);
}
return s_defaultSiteName;
}
}
internal WebConfigurationHost() {
Type type = Type.GetType(InternalHostTypeName, true);
Host = (IInternalConfigHost) Activator.CreateInstance(type, true);
}
// Not used in runtime because in runtime we have all the siteid, appPath, etc. already.
static internal void GetConfigPaths(IConfigMapPath configMapPath, WebLevel webLevel, VirtualPath virtualPath, string site, string locationSubPath,
out VirtualPath appPath, out string appSiteName, out string appSiteID, out string configPath, out string locationConfigPath) {
appPath = null;
appSiteName = null;
appSiteID = null;
if (webLevel == WebLevel.Machine || virtualPath == null) {
// Site is meaningless at machine and root web.config level
// However, we allow a site parameter if the caller is opening
// a location tag. See VSWhidbey 548361.
if (!String.IsNullOrEmpty(site) && String.IsNullOrEmpty(locationSubPath)) {
throw ExceptionUtil.ParameterInvalid("site");
}
if (webLevel == WebLevel.Machine) {
configPath = MachineConfigPath;
}
else {
configPath = RootWebConfigPath;
}
}
else {
// Get the site name and ID
if (!String.IsNullOrEmpty(site)) {
configMapPath.ResolveSiteArgument(site, out appSiteName, out appSiteID);
if (String.IsNullOrEmpty(appSiteID)) {
throw new InvalidOperationException(SR.GetString(SR.Config_failed_to_resolve_site_id, site));
}
}
else {
// If site not supplied, try hosting environment first
if (HostingEnvironment.IsHosted) {
appSiteName = HostingEnvironment.SiteNameNoDemand;
appSiteID = HostingEnvironment.SiteID;
}
// Rely on defaults if not provided in hosting environment
if (String.IsNullOrEmpty(appSiteID)) {
configMapPath.GetDefaultSiteNameAndID(out appSiteName, out appSiteID);
}
Debug.Assert(!String.IsNullOrEmpty(appSiteID), "No appSiteID found when site argument is null");
}
configPath = GetConfigPathFromSiteIDAndVPath(appSiteID, virtualPath);
}
// get locationConfigPath
locationConfigPath = null;
string locationSite = null;
VirtualPath locationVPath = null;
if (locationSubPath != null) {
locationConfigPath = GetConfigPathFromLocationSubPathBasic(configPath, locationSubPath);
GetSiteIDAndVPathFromConfigPath(locationConfigPath, out locationSite, out locationVPath);
// If we're at machine or root web.config level and a location path is given,
// handle the site part of the location path.
if (String.IsNullOrEmpty(appSiteID) && !String.IsNullOrEmpty(locationSite)) {
configMapPath.ResolveSiteArgument(locationSite, out appSiteName, out appSiteID);
if (!String.IsNullOrEmpty(appSiteID)) {
// Recompose the location config path based on new appSiteID
locationConfigPath = GetConfigPathFromSiteIDAndVPath(appSiteID, locationVPath);
}
else {
// If there is no path, then allow the location to be edited,
// as we don't need to map elements of the path.
if (locationVPath == null || locationVPath.VirtualPathString == "/") {
appSiteName = locationSite;
appSiteID = locationSite;
}
// Otherwise, the site argument is ambiguous.
else {
//
appSiteName = null;
appSiteID = null;
}
}
}
}
// get appPath
string appPathString = null;
if (locationVPath != null) {
appPathString = configMapPath.GetAppPathForPath(appSiteID, locationVPath.VirtualPathString);
}
else if (virtualPath != null) {
appPathString = configMapPath.GetAppPathForPath(appSiteID, virtualPath.VirtualPathString);
}
if (appPathString != null) {
appPath = VirtualPath.Create(appPathString);
}
}
// Choose the implementation of IConfigMapPath to use
// in cases where it is not provided to us.
void ChooseAndInitConfigMapPath(bool useConfigMapPath, IConfigMapPath configMapPath, ConfigurationFileMap fileMap) {
if (useConfigMapPath) {
_configMapPath = configMapPath;
}
else if (fileMap != null) {
_configMapPath = new UserMapPath(fileMap);
}
else if (HostingEnvironment.IsHosted) {
_configMapPath = HostingPreferredMapPath.GetInstance();
}
else {
_configMapPath = IISMapPath.GetInstance();
}
// see if it supports IConfigMapPath2
_configMapPath2 = _configMapPath as IConfigMapPath2;
}
public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams) {
bool useConfigMapPath = (bool) hostInitParams[0];
IConfigMapPath configMapPath = (IConfigMapPath) hostInitParams[1];
ConfigurationFileMap fileMap = (ConfigurationFileMap) hostInitParams[2];
string appPath = (string) hostInitParams[3];
string appSiteName = (string) hostInitParams[4];
string appSiteID = (string) hostInitParams[5];
if (hostInitParams.Length > 6) {
// If VS sent a 7th param, it is the .Net Framwework Target version moniker
string fxMoniker = hostInitParams[6] as string;
_machineConfigFile = GetMachineConfigPathFromTargetFrameworkMoniker(fxMoniker);
if (!string.IsNullOrEmpty(_machineConfigFile)) {
_rootWebConfigFile = Path.Combine(Path.GetDirectoryName(_machineConfigFile), "web.config");
}
}
Debug.Assert(configMapPath == null || useConfigMapPath, "non-null configMapPath without useConfigMapPath == true");
Host.Init(configRoot, hostInitParams);
ChooseAndInitConfigMapPath(useConfigMapPath, configMapPath, fileMap);
appPath = UrlPath.RemoveSlashFromPathIfNeeded(appPath);
_appPath = VirtualPath.CreateAbsoluteAllowNull(appPath);
_appSiteName = appSiteName;
_appSiteID = appSiteID;
if (!String.IsNullOrEmpty(_appSiteID) && _appPath != null) {
_appConfigPath = GetConfigPathFromSiteIDAndVPath(_appSiteID, _appPath);
}
#if DBG
_inited = true;
#endif
}
public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath,
IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) {
WebLevel webLevel = (WebLevel) hostInitConfigurationParams[0];
ConfigurationFileMap fileMap = (ConfigurationFileMap) hostInitConfigurationParams[1];
VirtualPath path = VirtualPath.CreateAbsoluteAllowNull((string)hostInitConfigurationParams[2]);
string site = (string) hostInitConfigurationParams[3];
if (locationSubPath == null) {
locationSubPath = (string) hostInitConfigurationParams[4];
}
Host.Init(configRoot, hostInitConfigurationParams);
// Choose the implementation of IConfigMapPath.
ChooseAndInitConfigMapPath(false, null, fileMap);
// Get the configuration paths and application information
GetConfigPaths(_configMapPath, webLevel, path, site, locationSubPath, out _appPath, out _appSiteName, out _appSiteID, out configPath, out locationConfigPath);
_appConfigPath = GetConfigPathFromSiteIDAndVPath(_appSiteID, _appPath);
// Verify that the site and path arguments represent a valid name
// For example, in Cassini app, which is running on \myApp, a page can
// ask for the config for "\", which can't map to anything. We want
// to catch this kind of error. Another example is if we're given
// an invalid site id.
if (IsVirtualPathConfigPath(configPath)) {
string finalSiteID;
VirtualPath finalPath;
GetSiteIDAndVPathFromConfigPath(configPath, out finalSiteID, out finalPath);
string physicalPath;
// attempt to use IConfigMapPath2 if provider supports it
if (null != _configMapPath2) {
physicalPath = _configMapPath2.MapPath(finalSiteID, finalPath);
}
else {
physicalPath = _configMapPath.MapPath(finalSiteID, finalPath.VirtualPathString);
}
if (String.IsNullOrEmpty(physicalPath)) {
throw new ArgumentOutOfRangeException("site");
}
}
#if DBG
_inited = true;
#endif
}
//
// Utilities to parse config path
//
// In both WHIDBEY and ORCAS, Path has the format:
// MACHINE/WEBROOT/[Site ID]/[Path Component]/[Path Component]/...
//
static internal bool IsMachineConfigPath(string configPath) {
return configPath.Length == MachineConfigPath.Length;
}
static internal bool IsRootWebConfigPath(string configPath) {
return configPath.Length == RootWebConfigPath.Length;
}
// Does the configPath represent a virtual path?
static internal bool IsVirtualPathConfigPath(string configPath) {
return configPath.Length > RootWebConfigPath.Length;
}
// A site argument that begins or ends in slashes will prevent
// us from using it in a configPath
static internal bool IsValidSiteArgument(string site) {
if (!String.IsNullOrEmpty(site)) {
char first = site[0];
char last = site[site.Length - 1];
if (first == '/' || first == '\\' || last == '/' || last == '\\') {
return false;
}
}
return true;
}
// Return the virtual path from the configPath.
static internal string VPathFromConfigPath(string configPath) {
if (!IsVirtualPathConfigPath(configPath))
return null;
// Return the path part after [SiteName]
int indexStart = RootWebConfigPath.Length + 1;
int indexVPath = configPath.IndexOf(PathSeparator, indexStart);
if (indexVPath == -1) {
return "/";
}
return configPath.Substring(indexVPath);
}
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
void IInternalConfigWebHost.GetSiteIDAndVPathFromConfigPath(string configPath, out string siteID, out string vpath) {
VirtualPath virtualPath;
WebConfigurationHost.GetSiteIDAndVPathFromConfigPath(configPath, out siteID, out virtualPath);
vpath = VirtualPath.GetVirtualPathString(virtualPath);
}
static internal void GetSiteIDAndVPathFromConfigPath(string configPath, out string siteID, out VirtualPath vpath) {
if (!IsVirtualPathConfigPath(configPath)) {
siteID = null;
vpath = null;
return;
}
int indexStart = RootWebConfigPath.Length + 1;
int indexVPath = configPath.IndexOf(PathSeparator, indexStart);
int length;
if (indexVPath == -1) {
length = configPath.Length - indexStart;
}
else {
length = indexVPath - indexStart;
}
siteID = configPath.Substring(indexStart, length);
if (indexVPath == -1) {
vpath = VirtualPath.RootVirtualPath;
}
else {
vpath = VirtualPath.CreateAbsolute(configPath.Substring(indexVPath));
}
}
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
string IInternalConfigWebHost.GetConfigPathFromSiteIDAndVPath(string siteID, string vpath) {
return WebConfigurationHost.GetConfigPathFromSiteIDAndVPath(
siteID, VirtualPath.CreateAbsoluteAllowNull(vpath));
}
static internal string GetConfigPathFromSiteIDAndVPath(string siteID, VirtualPath vpath) {
#if DBG
// Do not inadverte expand app-relative paths using appdomain
Debug.Assert(vpath == null || vpath.VirtualPathStringIfAvailable != null || vpath.AppRelativeVirtualPathStringIfAvailable == null,
"vpath == null || vpath.VirtualPathStringIfAvailable != null || vpath.AppRelativeVirtualPathStringIfAvailable == null");
#endif
if (vpath == null || string.IsNullOrEmpty(siteID)) {
return RootWebConfigPath;
}
string virtualPath = vpath.VirtualPathStringNoTrailingSlash.ToLower(CultureInfo.InvariantCulture);
string configPath = (siteID == DefaultSiteID) ? RootWebConfigPathAndDefaultSiteID : RootWebConfigPathAndPathSeparator + siteID;
if (virtualPath.Length > 1) {
configPath += virtualPath;
}
return configPath;
}
static internal string CombineConfigPath(string parentConfigPath, string childConfigPath) {
if (String.IsNullOrEmpty(parentConfigPath)) {
return childConfigPath;
}
if (String.IsNullOrEmpty(childConfigPath)) {
return parentConfigPath;
}
return parentConfigPath + PathSeparator + childConfigPath;
}
public override bool IsConfigRecordRequired(string configPath) {
// machine.config and root web.config are required records
if (!IsVirtualPathConfigPath(configPath))
return true;
// find the physical translation
string siteID;
VirtualPath path;
GetSiteIDAndVPathFromConfigPath(configPath, out siteID, out path);
string physicalPath;
// attempt to use fast path VirtualPath interface
if (null != _configMapPath2) {
physicalPath = _configMapPath2.MapPath(siteID, path);
}
else {
physicalPath = _configMapPath.MapPath(siteID, path.VirtualPathString);
}
// If the mapping doesn't exist, it may contain children.
// For example, a Cassini server running application
// "/myApp" will not have a mapping for "/".
if (physicalPath == null)
return true;
// vpaths that correspond to directories are required
return FileUtil.DirectoryExists(physicalPath, true);
}
// stream support
public override string GetStreamName(string configPath) {
if (IsMachineConfigPath(configPath)) {
return !string.IsNullOrEmpty(_machineConfigFile) ? _machineConfigFile : _configMapPath.GetMachineConfigFilename();
}
if (IsRootWebConfigPath(configPath)) {
return !string.IsNullOrEmpty(_rootWebConfigFile) ? _rootWebConfigFile : _configMapPath.GetRootWebConfigFilename();
}
else {
string siteID;
VirtualPath path;
GetSiteIDAndVPathFromConfigPath(configPath, out siteID, out path);
string directory, baseName;
// attempt to use fast path interface that takes a VirtualPath
// to avoid conversion
if (null != _configMapPath2) {
_configMapPath2.GetPathConfigFilename(siteID, path, out directory, out baseName);
}
else {
_configMapPath.GetPathConfigFilename(siteID, path.VirtualPathString, out directory, out baseName);
}
if (directory == null)
return null;
bool exists, isDirectory;
FileUtil.PhysicalPathStatus(directory, true, false, out exists, out isDirectory);
if (exists && isDirectory) {
// DevDiv Bugs 152256: Illegal characters {",|} in path prevent configuration system from working.
// We need to catch this exception and return null as System.IO.Path.Combine fails to combine paths
// containing these characters.
// We return null when we have an ArgumentException because we have characters in the parameters
// that cannot be part of a filename in Windows. So it is impossible to get a stream name for paths
// with these characters. We fallback to the default GetStreamName failure behavior which is to
// return null.
// Dev10 Bug 835901: '?' (%3F), '*' (%2A), and ':' (%3A) are valid in a URL. We need to return null
// if the path contains one of these characters. Instead of explicitly checking for these characters,
// we will rely on Path.Combine and Path.GetFullPath to throw when the path is invalid.
return CombineAndValidatePath(directory, baseName);
}
return null;
}
}
[FileIOPermissionAttribute(SecurityAction.Assert, AllFiles=FileIOPermissionAccess.PathDiscovery)]
private string CombineAndValidatePath(string directory, string baseName) {
try {
string path = Path.Combine(directory, baseName);
// validate path by calling GetFullPath, but return the result of Path.Combine so as
// not to change what was being returned previously (Dev10 835901).
Path.GetFullPath(path);
return path;
}
catch (PathTooLongException) {
return null;
}
catch (NotSupportedException) {
return null;
}
catch (ArgumentException) {
return null;
}
}
// change notification support - runtime only
public override bool SupportsChangeNotifications {
get {return true;}
}
private Hashtable FileChangeCallbacks {
get {
if (_fileChangeCallbacks == null) {
_fileChangeCallbacks = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
return _fileChangeCallbacks;
}
}
public override object StartMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) {
WebConfigurationHostFileChange wrapper;
// Note: in theory it's possible for multiple config records to monitor the same stream.
// That's why we use the arraylist to store the callbacks.
lock (this) {
wrapper = new WebConfigurationHostFileChange(callback);
ArrayList list = (ArrayList) FileChangeCallbacks[streamName];
if (list == null) {
list = new ArrayList(1);
FileChangeCallbacks.Add(streamName, list);
}
list.Add(wrapper);
}
HttpRuntime.FileChangesMonitor.StartMonitoringFile(
streamName, new FileChangeEventHandler(wrapper.OnFileChanged));
return wrapper;
}
public override void StopMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) {
WebConfigurationHostFileChange wrapper = null;
lock (this) {
ArrayList list = (ArrayList) FileChangeCallbacks[streamName];
for (int i = 0; i < list.Count; i++) {
WebConfigurationHostFileChange item = (WebConfigurationHostFileChange) list[i];
if (object.ReferenceEquals(item.Callback, callback)) {
wrapper = item;
list.RemoveAt(i);
if (list.Count == 0) {
FileChangeCallbacks.Remove(streamName);
}
break;
}
}
}
HttpRuntime.FileChangesMonitor.StopMonitoringFile(streamName, wrapper);
}
public override bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) {
switch (allowDefinition) {
case ConfigurationAllowDefinition.MachineOnly:
return configPath.Length <= MachineConfigPath.Length;
case ConfigurationAllowDefinition.MachineToWebRoot:
return configPath.Length <= RootWebConfigPath.Length;
case ConfigurationAllowDefinition.MachineToApplication:
// In some scenarios the host does not have an application path.
// Allow all definitions in this case.
return String.IsNullOrEmpty(_appConfigPath) ||
(configPath.Length <= _appConfigPath.Length) ||
IsApplication(configPath);
// MachineToLocalUser does not current have any definition restrictions
case ConfigurationAllowDefinition.Everywhere:
return true;
default:
// If we have extended ConfigurationAllowDefinition
// make sure to update this switch accordingly
throw ExceptionUtil.UnexpectedError("WebConfigurationHost::IsDefinitionAllowed");
}
}
public override void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) {
if (!IsDefinitionAllowed(configPath, allowDefinition, allowExeDefinition)) {
switch (allowDefinition) {
case ConfigurationAllowDefinition.MachineOnly:
throw new ConfigurationErrorsException(SR.GetString(SR.Config_allow_definition_error_machine), errorInfo.Filename, errorInfo.LineNumber);
case ConfigurationAllowDefinition.MachineToWebRoot:
throw new ConfigurationErrorsException(SR.GetString(SR.Config_allow_definition_error_webroot), errorInfo.Filename, errorInfo.LineNumber);
case ConfigurationAllowDefinition.MachineToApplication:
throw new ConfigurationErrorsException(SR.GetString(SR.Config_allow_definition_error_application), errorInfo.Filename, errorInfo.LineNumber);
default:
// If we have extended ConfigurationAllowDefinition
// make sure to update this switch accordingly
throw ExceptionUtil.UnexpectedError("WebConfigurationHost::VerifyDefinitionAllowed");
}
}
}
private WebApplicationLevel GetPathLevel(string configPath) {
if (!IsVirtualPathConfigPath(configPath))
return WebApplicationLevel.AboveApplication;
#if DBG
Debug.Assert(_inited, "_inited");
#endif
// Disable handling of path level when we don't have an application path.
if (_appPath == null)
return WebApplicationLevel.AboveApplication;
string siteID;
VirtualPath path;
GetSiteIDAndVPathFromConfigPath(configPath, out siteID, out path);
if (!StringUtil.EqualsIgnoreCase(_appSiteID, siteID))
return WebApplicationLevel.AboveApplication;
if (_appPath == path)
return WebApplicationLevel.AtApplication;
if (UrlPath.IsEqualOrSubpath(_appPath.VirtualPathString, path.VirtualPathString))
return WebApplicationLevel.BelowApplication;
return WebApplicationLevel.AboveApplication;
}
// path support
public override bool SupportsPath {
get {
return true;
}
}
public override bool SupportsLocation {
get {
return true;
}
}
public override bool IsAboveApplication(string configPath) {
return GetPathLevel(configPath) == WebApplicationLevel.AboveApplication;
}
static internal string GetConfigPathFromLocationSubPathBasic(string configPath, string locationSubPath) {
string locationConfigPath;
if (IsVirtualPathConfigPath(configPath)) {
locationConfigPath = CombineConfigPath(configPath, locationSubPath);
}
else {
// Location subpaths only apply to virtual paths, not config file roots.
locationConfigPath = CombineConfigPath(RootWebConfigPath, locationSubPath);
}
return locationConfigPath;
}
public override string GetConfigPathFromLocationSubPath(string configPath, string locationSubPath) {
#if DBG
Debug.Assert(_inited, "_inited");
#endif
string locationConfigPath;
if (IsVirtualPathConfigPath(configPath)) {
locationConfigPath = CombineConfigPath(configPath, locationSubPath);
}
else {
string siteID = null;
// First part of path is the site.
// If it matches this app's site, use the proper site id,
// otherwise just use the site as it is given, which will
// result in it being ignored as desired.
string site;
VirtualPath virtualPath;
int firstSlash = locationSubPath.IndexOf(PathSeparator);
if (firstSlash < 0) {
site = locationSubPath;
virtualPath = VirtualPath.RootVirtualPath;
}
else {
site = locationSubPath.Substring(0, firstSlash);
virtualPath = VirtualPath.CreateAbsolute(locationSubPath.Substring(firstSlash));
}
if (StringUtil.EqualsIgnoreCase(site, _appSiteID) || StringUtil.EqualsIgnoreCase(site, _appSiteName)) {
siteID = _appSiteID;
}
else {
siteID = site;
}
locationConfigPath = GetConfigPathFromSiteIDAndVPath(siteID, virtualPath);
}
return locationConfigPath;
}
public override bool IsLocationApplicable(string configPath) {
return IsVirtualPathConfigPath(configPath);
}
internal static void StaticGetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady) {
isHostReady = HttpRuntime.IsTrustLevelInitialized;
permissionSet = null;
if (isHostReady && IsVirtualPathConfigPath(configRecord.ConfigPath)) {
permissionSet = HttpRuntime.NamedPermissionSet;
}
}
// we trust root config files - admins settings do not have security restrictions.
public override bool IsTrustedConfigPath(string configPath) {
return !IsVirtualPathConfigPath(configPath);
}
public override bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord) {
if (HostingEnvironment.IsHosted) {
return HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted);
}
else {
return Host.IsFullTrustSectionWithoutAptcaAllowed(configRecord);
}
}
public override void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady) {
StaticGetRestrictedPermissions(configRecord, out permissionSet, out isHostReady);
}
public override IDisposable Impersonate() {
return new ApplicationImpersonationContext();
}
// prefetch support
public override bool PrefetchAll(string configPath, string streamName) {
return !IsMachineConfigPath(configPath);
}
const string SysWebName = "system.web";
public override bool PrefetchSection(string sectionGroupName, string sectionName) {
if ( StringUtil.StringStartsWith(sectionGroupName, SysWebName)
&& (sectionGroupName.Length == SysWebName.Length || sectionGroupName[SysWebName.Length] == '/')) {
return true;
}
if (String.IsNullOrEmpty(sectionGroupName) && sectionName == "system.codedom")
return true;
return false;
}
// context support
public override object CreateDeprecatedConfigContext(string configPath) {
return new HttpConfigurationContext(VPathFromConfigPath(configPath));
}
// CreateConfigurationContext
//
// Create the ConfigurationContext for ConfigurationElement's
//
// Parameters:
// configPath - Config Path we are quering for
// locationSubPath - Location SubPath
//
public override object CreateConfigurationContext(string configPath, string locationSubPath)
{
string path;
WebApplicationLevel pathLevel;
path = VPathFromConfigPath(configPath);
pathLevel = GetPathLevel(configPath);
return new WebContext( pathLevel, // PathLevel
_appSiteName, // Site
VirtualPath.GetVirtualPathString(_appPath), // AppPath
path, // Path
locationSubPath, // LocationSubPath
_appConfigPath); // e.g., "machine/webroot/2/approot"
}
// Type name support
public override Type GetConfigType(string typeName, bool throwOnError) {
// Go through BuildManager to allow simple references to types in the
// code directory (VSWhidbey 284498)
return BuildManager.GetType(typeName, throwOnError);
}
public override string GetConfigTypeName(Type t) {
return BuildManager.GetNormalizedTypeName(t);
}
// IsApplication
//
// Given a config Path, is it the Path for an application?
//
private bool IsApplication(string configPath) {
VirtualPath appPath;
string siteID;
VirtualPath vpath;
// Break up into siteID and vpath
GetSiteIDAndVPathFromConfigPath(configPath, out siteID, out vpath);
// Retrieve appPath for this
if (null != _configMapPath2) {
appPath = _configMapPath2.GetAppPathForPath(siteID, vpath);
}
else {
appPath = VirtualPath.CreateAllowNull(_configMapPath.GetAppPathForPath(siteID, vpath.VirtualPathString));
}
return (appPath == vpath);
}
// Get the factory used to create and initialize Configuration objects.
static internal IInternalConfigConfigurationFactory ConfigurationFactory {
[ReflectionPermission(SecurityAction.Assert, Flags=ReflectionPermissionFlag.MemberAccess)]
get {
if (s_configurationFactory == null) {
Type type = Type.GetType(InternalConfigConfigurationFactoryTypeName, true);
s_configurationFactory = (IInternalConfigConfigurationFactory) Activator.CreateInstance(type, true);
}
return s_configurationFactory;
}
}
// Create an instance of a Configuration object.
// Used by design-time API to open a Configuration object.
static internal Configuration OpenConfiguration(
WebLevel webLevel, ConfigurationFileMap fileMap, VirtualPath path, string site, string locationSubPath,
string server, string userName, string password, IntPtr tokenHandle) {
Configuration configuration;
if (!IsValidSiteArgument(site)) {
throw ExceptionUtil.ParameterInvalid("site");
}
locationSubPath = ConfigurationFactory.NormalizeLocationSubPath(locationSubPath, null);
bool isRemote = !String.IsNullOrEmpty(server)
&& server != "."
&& !StringUtil.EqualsIgnoreCase(server, "127.0.0.1")
&& !StringUtil.EqualsIgnoreCase(server, "::1")
&& !StringUtil.EqualsIgnoreCase(server, "localhost")
&& !StringUtil.EqualsIgnoreCase(server, Environment.MachineName);
if (isRemote) {
configuration = ConfigurationFactory.Create(typeof(RemoteWebConfigurationHost),
webLevel, null, VirtualPath.GetVirtualPathString(path), site, locationSubPath, server, userName, password, tokenHandle);
}
else {
if (String.IsNullOrEmpty(server)) {
if (!String.IsNullOrEmpty(userName))
throw ExceptionUtil.ParameterInvalid("userName");
if (!String.IsNullOrEmpty(password))
throw ExceptionUtil.ParameterInvalid("password");
if (tokenHandle != (IntPtr) 0)
throw ExceptionUtil.ParameterInvalid("tokenHandle");
}
// Create a copy of the fileMap, so that it cannot be altered by
// its creator once we start using it.
if (fileMap != null) {
fileMap = (ConfigurationFileMap) fileMap.Clone();
}
WebConfigurationFileMap webFileMap = fileMap as WebConfigurationFileMap;
if (webFileMap != null && !String.IsNullOrEmpty(site)) {
webFileMap.Site = site;
}
configuration = ConfigurationFactory.Create(typeof(WebConfigurationHost),
webLevel, fileMap, VirtualPath.GetVirtualPathString(path), site, locationSubPath );
}
return configuration;
}
private static string GetMachineConfigPathFromTargetFrameworkMoniker(string moniker) {
TargetDotNetFrameworkVersion ver = GetTargetFrameworkVersionEnumFromMoniker(moniker);
if (ver == TargetDotNetFrameworkVersion.VersionLatest)
return null;
string machineConfig = ToolLocationHelper.GetPathToDotNetFrameworkFile(@"config\machine.config", ver);
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, machineConfig).Demand();
return machineConfig;
}
private static TargetDotNetFrameworkVersion GetTargetFrameworkVersionEnumFromMoniker(string moniker)
{
//
if (moniker.Contains("3.5") || moniker.Contains("3.0") || moniker.Contains("2.0") ) {
return TargetDotNetFrameworkVersion.Version20;
}
return TargetDotNetFrameworkVersion.VersionLatest;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Types Rule : Interface Methods (Compiler)
// CLS-compliant language compilers must have syntax for the situation where a single type implements
// two interfaces and each of those interfaces requires the definition of a method with the same name and signature.
// Such methods must be considered distinct and need not have the same implementation.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public interface MyInterface1
{
dynamic Method01(int n);
T Method02<T>(dynamic n);
dynamic Method03(byte b, ref dynamic n);
}
public interface MyInterface2
{
dynamic Method01(int n);
T Method02<T>(dynamic n);
dynamic Method03(byte b, ref dynamic n);
}
public class MyClass : MyInterface1, MyInterface2
{
dynamic MyInterface1.Method01(int n)
{
return default(dynamic);
}
T MyInterface1.Method02<T>(dynamic n)
{
return default(T);
}
dynamic MyInterface1.Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
dynamic MyInterface2.Method01(int n)
{
return default(dynamic);
}
T MyInterface2.Method02<T>(dynamic n)
{
return default(T);
}
dynamic MyInterface2.Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
}
public struct MyStruct : MyInterface1, MyInterface2
{
public dynamic Method01(int n)
{
return default(dynamic);
}
public T Method02<T>(dynamic n)
{
return default(T);
}
public dynamic Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(79,55\).*CS3022</Expects>
//<Expects Status=warning>\(80,55\).*CS3022</Expects>
//<Expects Status=warning>\(47,29\).*CS3026.*vd1</Expects>
//<Expects Status=warning>\(50,23\).*CS3002.*RefMethod01\<T\>\(ref dynamic, T\)</Expects>
//<Expects Status=warning>\(51,23\).*CS3002.*refMethod01\<T\></Expects>
//<Expects Status=warning>\(51,23\).*CS3005</Expects>
//<Expects Status=warning>\(65,13\).*CS3010.*MyInterface\<T,U,V\>.Method01</Expects>
//<Expects Status=warning>\(69,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects>
//<Expects Status=warning>\(72,13\).*CS3005.*method03\<X,Y\></Expects>
//<Expects Status=warning>\(75,27\).*CS3010.*MyInterface\<T,U,V\>.MyEvent</Expects>
//<Expects Status=warning>\(75,27\).*CS3010</Expects>
//<Expects Status=warning>\(75,27\).*CS3010</Expects>
//<Expects Status=warning>\(80,22\).*CS3005.*myDelegate01\<T\></Expects>
//<Expects Status=success></Expects>
// <Code>
// <Expects Status=notin>CS3005.*outMethod01\<X\></Expects>
// <Expects Status=notin>CS3005.*method01\<X\></Expects>
// <Expects Status=notin>CS3005.*myDelegate02\<U,V\></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
[type: System.CLSCompliant(false)]
public class MyClass<T>
{
public volatile dynamic vd;
public static T OutMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
public static T outMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
}
[type: System.CLSCompliant(true)]
public struct MyStruct<U, V>
{
public volatile dynamic vd1;
[method: System.CLSCompliant(true)]
public MyClass<T> RefMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
public MyClass<T> refMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
[property: System.CLSCompliant(false)]
public dynamic Prop
{
get;
set;
}
public dynamic prop
{
get;
set;
}
[field: System.CLSCompliant(false)]
public dynamic field;
public dynamic fielD;
}
public interface MyInterface<T, U, V>
{
[method: System.CLSCompliant(false)]
dynamic Method01<X>(X n);
dynamic method01<X>(X n);
T Method02(dynamic n, U u);
T method02(dynamic n, U u);
[method: System.CLSCompliant(true)]
dynamic Method03<X, Y>(out X x, ref Y y, dynamic n);
dynamic method03<X, Y>(out X x, ref Y y, dynamic n);
[event: System.CLSCompliant(false)]
event MyDelegate01<T> MyEvent;
event MyDelegate01<T> Myevent;
}
public delegate void MyDelegate01<T>(ref T t, [param: System.CLSCompliant(false)]
dynamic d, int n);
public delegate void myDelegate01<T>(ref T t, [param: System.CLSCompliant(true)]
dynamic d, int n);
[System.CLSCompliantAttribute(false)]
public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary);
public delegate V myDelegate02<U, V>(U u, params dynamic[] ary);
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(30,14\).*CS3005.*outMethod01\<X\></Expects>
//<Expects Status=warning>\(36,23\).*CS3005.*refMethod01\<T\></Expects>
//<Expects Status=warning>\(42,13\).*CS3005.*method01\<X\></Expects>
//<Expects Status=warning>\(45,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects>
//<Expects Status=warning>\(48,13\).*CS3005.*method03\<X,Y\></Expects>
//<Expects Status=warning>\(52,22\).*CS3005.*myDelegate01\<T\></Expects>
//<Expects Status=warning>\(55,19\).*CS3005.*myDelegate02\<U,V\></Expects>
//<Expects Status=success></Expects>
// <Code>
// <Code>
//[assembly: System.CLSCompliant(true)]
public class MyClass<T>
{
public T OutMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
public T outMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
}
public struct MyStruct<U, V>
{
public MyClass<T> RefMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
public MyClass<T> refMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
}
public interface MyInterface<T, U, V>
{
dynamic Method01<X>(X n);
dynamic method01<X>(X n);
T Method02(dynamic n, U u);
T method02(dynamic n, U u);
dynamic Method03<X, Y>(out X x, ref Y y, dynamic n);
dynamic method03<X, Y>(out X x, ref Y y, dynamic n);
}
public delegate void MyDelegate01<T>(ref T t, dynamic d, int n);
public delegate void myDelegate01<T>(ref T t, dynamic d, int n);
public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary);
public delegate V myDelegate02<U, V>(U u, params dynamic[] ary);
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(57,24\).*CS0108</Expects>
//<Expects Status=warning>\(41,24\).*CS3005.*method01</Expects>
//<Expects Status=warning>\(42,18\).*CS3005.*method02\<T\></Expects>
//<Expects Status=warning>\(49,24\).*CS3005.*classIdentifier</Expects>
//<Expects Status=warning>\(50,24\).*CS3005.*MEthod01</Expects>
//<Expects Status=warning>\(51,18\).*CS3005.*mEthod02\<T\></Expects>
//<Expects Status=warning>\(52,24\).*CS3005.*method03\<X,Y></Expects>
//<Expects Status=warning>\(57,24\).*CS3005</Expects>
//<Expects Status=warning>\(58,24\).*CS3005.*MyClass3\<U,V\>\.Method01</Expects>
//<Expects Status=warning>\(59,24\).*CS3005.*MyClass3\<U,V\>\.Method03</Expects>
//<Expects Status=success></Expects>
// <Code>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyBase
{
public dynamic Method01(int n, ref dynamic d)
{
return default(object);
}
public T Method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
}
public class MyClass : MyBase
{
public dynamic ClassIdentifier;
public dynamic method01(int n, ref dynamic d)
{
return default(object);
}
public T method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
public dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass2 : MyClass
{
public dynamic classIdentifier;
public dynamic MEthod01(int n, ref dynamic d)
{
return default(object);
}
public T mEthod02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
public dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass3<U, V> : MyClass2
{
public dynamic ClassIdentifier;
public dynamic Method01(long n, ref dynamic d)
{
return default(object);
}
public dynamic Method03(U x, ref V y, params dynamic[] ary)
{
return default(object);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Visibility - CLS rules apply only to those parts of a type that are exposed outside the defining assembly.
// Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(31,17\).*CS0169</Expects>
//<Expects Status=warning>\(43,25\).*CS0169</Expects>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyBase
{
public dynamic[][][] array; //jagged array
private dynamic Method01(int n, ref dynamic d)
{
return default(object);
}
private T Method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
}
public class MyClass : MyBase
{
private dynamic _classIdentifier;
internal dynamic method01(int n, ref dynamic d)
{
return default(object);
}
protected T method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
private dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass2 : MyClass
{
//public static dynamic[,,,] array1; //cube array
private dynamic _classIdentifier;
private dynamic MEthod01(int n, ref dynamic d)
{
return default(object);
}
private T mEthod02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
protected dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass3<U, V> : MyClass2
{
protected dynamic ClassIdentifier;
private dynamic Method01(long n, ref dynamic d)
{
return default(object);
}
protected internal dynamic method03(U x, ref V y, params dynamic[] ary)
{
return default(object);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Keywords (Compiler)
// CLS-compliant language compilers supply a mechanism for referencing identifiers that coincide with keywords.
// CLS-compliant language compilers provide a mechanism for defining and overriding virtual methods
// with names that are keywords in the language.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyClass
{
public dynamic @dynamic;
public dynamic Method01(ref int @dynamic)
{
return default(dynamic);
}
}
public struct MyStruct
{
public dynamic @dynamic;
public void Method02(out dynamic @dynamic)
{
@dynamic = default(dynamic);
}
}
public interface MyInterface
{
dynamic Method01(int n, dynamic @dynamic);
dynamic @dynamic(string n, dynamic d);
}
public delegate void myDelegate02(params dynamic[] @dynamic);
public delegate int @dynamic(int n);
namespace MyNamespace11
{
public enum @dynamic
{
}
}
}
namespace MyNamespace1
{
public class @dynamic
{
private dynamic Method01(out int n, dynamic d)
{
n = 0;
return default(dynamic);
}
}
namespace MyNamespace2
{
public struct @dynamic
{
private dynamic Method01(int n, ref dynamic d)
{
return default(dynamic);
}
}
namespace MyNamespace3
{
public interface @dynamic
{
dynamic Method01(int n, ref dynamic d);
}
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01;
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Types Rule : Interface Methods (Compiler)
// CLS-compliant language compilers must have syntax for the situation where a single type implements
// two interfaces and each of those interfaces requires the definition of a method with the same name and signature.
// Such methods must be considered distinct and need not have the same implementation.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyClass
{
public dynamic Method01(int x, int y = 0, int z = 1)
{
return default(dynamic);
}
//
public T Method02<T>(dynamic d = default(dynamic), string s = "QQQ")
{
return default(T);
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MyClass c = new MyClass();
c.Method01(999);
c.Method01(9, 8);
c.Method01(9, 8, 7);
c.Method01(999, z: 888);
c.Method01(999, z: 888, y: 666);
c.Method02<byte>();
c.Method02<int>(default(dynamic));
c.Method02<long>(default(dynamic), "CCC");
var v = new MyStruct<dynamic>();
v.Method11();
v.Method11(default(dynamic));
v.Method11(default(object), default(object), default(object));
v.Method12<int, dynamic>();
v.Method12<int, dynamic>(100);
v.Method12<int, dynamic>(-9999, default(dynamic));
return 0;
}
}
public struct MyStruct<T>
{
public dynamic Method11(T t = default(T), params dynamic[] ary)
{
return default(dynamic);
}
public T Method12<U, V>(U u = default(U), V v = default(V))
{
return default(T);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a;
// <Title> regression test</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Foo
{
public static void Method(string s)
{
if (s == "abc")
Test.Result++;
}
public string Prop
{
get;
set;
}
}
public class Test
{
public Foo Foo
{
get;
set;
}
public static void DoExample(dynamic d)
{
Foo.Method(d.Prop);
}
public static int Result = -1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
try
{
DoExample(new Foo()
{
Prop = "abc"
}
);
}
catch (System.Exception)
{
Test.Result--;
}
return Test.Result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using ScriptCs.Dnx.Contracts;
namespace ScriptCs.Dnx.Core
{
public class ScriptExecutor : IScriptExecutor
{
private readonly ILog _log;
//todo
public static readonly string[] DefaultReferences =
{
"System",
//"System.Core",
//"System.Data",
//"System.Data.DataSetExtensions",
//"System.Xml",
//"System.Xml.Linq",
//"System.Net.Http",
//"Microsoft.CSharp",
//todo: no location available anymore
//typeof(ScriptExecutor).Assembly.Location,
//typeof(IScriptEnvironment).Assembly.Location
};
//todo
public static readonly string[] DefaultNamespaces =
{
"System",
//"System.Collections.Generic",
//"System.Linq",
//"System.Text",
//"System.Threading.Tasks",
//"System.IO",
//"System.Net.Http",
//"System.Dynamic"
};
private const string ScriptLibrariesInjected = "ScriptLibrariesInjected";
public IFileSystem FileSystem { get; private set; }
public IFilePreProcessor FilePreProcessor { get; private set; }
public IScriptEngine ScriptEngine { get; private set; }
public AssemblyReferences References { get; private set; }
public ICollection<string> Namespaces { get; private set; }
public ScriptPackSession ScriptPackSession { get; protected set; }
public IScriptLibraryComposer ScriptLibraryComposer { get; protected set; }
public ScriptExecutor(
IFileSystem fileSystem, IFilePreProcessor filePreProcessor, IScriptEngine scriptEngine, ILogProvider logProvider)
: this(fileSystem, filePreProcessor, scriptEngine, logProvider, new NullScriptLibraryComposer())
{
}
public ScriptExecutor(
IFileSystem fileSystem,
IFilePreProcessor filePreProcessor,
IScriptEngine scriptEngine,
ILogProvider logProvider,
IScriptLibraryComposer composer)
{
if (fileSystem == null) throw new ArgumentNullException(nameof(fileSystem));
if (filePreProcessor == null) throw new ArgumentNullException(nameof(filePreProcessor));
if (scriptEngine == null) throw new ArgumentNullException(nameof(scriptEngine));
if (logProvider == null) throw new ArgumentNullException(nameof(logProvider));
if (composer == null) throw new ArgumentNullException(nameof(composer));
References = new AssemblyReferences(DefaultReferences);
Namespaces = new Collection<string>();
ImportNamespaces(DefaultNamespaces);
FileSystem = fileSystem;
FilePreProcessor = filePreProcessor;
ScriptEngine = scriptEngine;
_log = logProvider.ForCurrentType();
ScriptLibraryComposer = composer;
}
public void ImportNamespaces(params string[] namespaces)
{
if (namespaces == null) throw new ArgumentNullException(nameof(namespaces));
foreach (var @namespace in namespaces)
{
Namespaces.Add(@namespace);
}
}
public void RemoveNamespaces(params string[] namespaces)
{
if (namespaces == null) throw new ArgumentNullException(nameof(namespaces));
foreach (var @namespace in namespaces)
{
Namespaces.Remove(@namespace);
}
}
public virtual void AddReferences(params Assembly[] assemblies)
{
if (assemblies == null) throw new ArgumentNullException(nameof(assemblies));
References = References.Union(assemblies);
}
public virtual void RemoveReferences(params Assembly[] assemblies)
{
if (assemblies == null) throw new ArgumentNullException(nameof(assemblies));
References = References.Except(assemblies);
}
public virtual void AddReferences(params string[] paths)
{
if (paths == null) throw new ArgumentNullException(nameof(paths));
References = References.Union(paths);
}
public virtual void RemoveReferences(params string[] paths)
{
if (paths == null) throw new ArgumentNullException(nameof(paths));
References = References.Except(paths);
}
public virtual void Initialize(
IEnumerable<string> paths, IEnumerable<IScriptPack> scriptPacks, params string[] scriptArgs)
{
AddReferences(paths.ToArray());
var bin = Path.Combine(FileSystem.CurrentDirectory, FileSystem.BinFolder);
var cache = Path.Combine(FileSystem.CurrentDirectory, FileSystem.DllCacheFolder);
ScriptEngine.BaseDirectory = bin;
ScriptEngine.CacheDirectory = cache;
_log.Debug("Initializing script packs");
var scriptPackSession = new ScriptPackSession(scriptPacks, scriptArgs);
ScriptPackSession = scriptPackSession;
scriptPackSession.InitializePacks();
}
public virtual void Reset()
{
References = new AssemblyReferences(DefaultReferences);
Namespaces.Clear();
ImportNamespaces(DefaultNamespaces);
ScriptPackSession.State.Clear();
}
public virtual void Terminate()
{
_log.Debug("Terminating packs");
ScriptPackSession.TerminatePacks();
}
public virtual ScriptResult Execute(string script, params string[] scriptArgs)
{
var path = Path.IsPathRooted(script) ? script : Path.Combine(FileSystem.CurrentDirectory, script);
var result = FilePreProcessor.ProcessFile(path);
ScriptEngine.FileName = Path.GetFileName(path);
return EngineExecute(Path.GetDirectoryName(path), scriptArgs, result);
}
public virtual ScriptResult ExecuteScript(string script, params string[] scriptArgs)
{
var result = FilePreProcessor.ProcessScript(script);
return EngineExecute(FileSystem.CurrentDirectory, scriptArgs, result);
}
protected internal virtual ScriptResult EngineExecute(
string workingDirectory,
string[] scriptArgs,
FilePreProcessorResult result
)
{
InjectScriptLibraries(workingDirectory, result, ScriptPackSession.State);
var namespaces = Namespaces.Union(result.Namespaces);
var references = References.Union(result.References);
_log.Debug("Starting execution in engine");
return ScriptEngine.Execute(result.Code, scriptArgs, references, namespaces, ScriptPackSession);
}
protected internal virtual void InjectScriptLibraries(
string workingDirectory,
FilePreProcessorResult result,
IDictionary<string, object> state
)
{
if (result == null) throw new ArgumentNullException(nameof(result));
if (state == null) throw new ArgumentNullException(nameof(state));
if (state.ContainsKey(ScriptLibrariesInjected))
{
return;
}
var scriptLibrariesPreProcessorResult = LoadScriptLibraries(workingDirectory);
if (scriptLibrariesPreProcessorResult != null)
{
result.Code = scriptLibrariesPreProcessorResult.Code + Environment.NewLine + result.Code;
result.References.AddRange(scriptLibrariesPreProcessorResult.References);
result.Namespaces.AddRange(scriptLibrariesPreProcessorResult.Namespaces);
}
state.Add(ScriptLibrariesInjected, null);
}
protected internal virtual FilePreProcessorResult LoadScriptLibraries(string workingDirectory)
{
if (string.IsNullOrWhiteSpace(ScriptLibraryComposer.ScriptLibrariesFile))
{
return null;
}
var scriptLibrariesPath = Path.Combine(workingDirectory, FileSystem.PackagesFolder,
ScriptLibraryComposer.ScriptLibrariesFile);
if (FileSystem.FileExists(scriptLibrariesPath))
{
_log.DebugFormat("Found Script Library at {0}", scriptLibrariesPath);
return FilePreProcessor.ProcessFile(scriptLibrariesPath);
}
return null;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace GpBufferLayer
{
partial class BufferDlg
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnBuffer = new System.Windows.Forms.Button();
this.btnOutputLayer = new System.Windows.Forms.Button();
this.txtOutputPath = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.cboUnits = new System.Windows.Forms.ComboBox();
this.txtBufferDistance = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.lblLayers = new System.Windows.Forms.Label();
this.cboLayers = new System.Windows.Forms.ComboBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.btnCancel = new System.Windows.Forms.Button();
this.txtMessages = new System.Windows.Forms.TextBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnBuffer);
this.groupBox1.Controls.Add(this.btnOutputLayer);
this.groupBox1.Controls.Add(this.txtOutputPath);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.cboUnits);
this.groupBox1.Controls.Add(this.txtBufferDistance);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.lblLayers);
this.groupBox1.Controls.Add(this.cboLayers);
this.groupBox1.Location = new System.Drawing.Point(2, -1);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(356, 166);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
//
// btnBuffer
//
this.btnBuffer.Location = new System.Drawing.Point(133, 130);
this.btnBuffer.Name = "btnBuffer";
this.btnBuffer.Size = new System.Drawing.Size(88, 23);
this.btnBuffer.TabIndex = 8;
this.btnBuffer.Text = "Buffer";
this.btnBuffer.UseVisualStyleBackColor = true;
this.btnBuffer.Click += new System.EventHandler(this.btnBuffer_Click);
//
// btnOutputLayer
//
this.btnOutputLayer.Location = new System.Drawing.Point(319, 86);
this.btnOutputLayer.Name = "btnOutputLayer";
this.btnOutputLayer.Size = new System.Drawing.Size(24, 23);
this.btnOutputLayer.TabIndex = 7;
this.btnOutputLayer.Text = ">";
this.btnOutputLayer.UseVisualStyleBackColor = true;
this.btnOutputLayer.Click += new System.EventHandler(this.btnOutputLayer_Click);
//
// txtOutputPath
//
this.txtOutputPath.Location = new System.Drawing.Point(93, 88);
this.txtOutputPath.Name = "txtOutputPath";
this.txtOutputPath.ReadOnly = true;
this.txtOutputPath.Size = new System.Drawing.Size(224, 20);
this.txtOutputPath.TabIndex = 6;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 88);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(67, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Output layer:";
//
// cboUnits
//
this.cboUnits.FormattingEnabled = true;
this.cboUnits.Items.AddRange(new object[] {
"Unknown",
"Inches",
"Points",
"Feet",
"Yards",
"Miles",
"NauticalMiles",
"Millimeters",
"Centimeters",
"Meters",
"Kilometers",
"DecimalDegrees",
"Decimeters"});
this.cboUnits.Location = new System.Drawing.Point(158, 51);
this.cboUnits.Name = "cboUnits";
this.cboUnits.Size = new System.Drawing.Size(118, 21);
this.cboUnits.TabIndex = 4;
//
// txtBufferDistance
//
this.txtBufferDistance.Location = new System.Drawing.Point(93, 51);
this.txtBufferDistance.Name = "txtBufferDistance";
this.txtBufferDistance.Size = new System.Drawing.Size(55, 20);
this.txtBufferDistance.TabIndex = 3;
this.txtBufferDistance.Text = "0.1";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 54);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(81, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Buffer distance:";
//
// lblLayers
//
this.lblLayers.AutoSize = true;
this.lblLayers.Location = new System.Drawing.Point(7, 19);
this.lblLayers.Name = "lblLayers";
this.lblLayers.Size = new System.Drawing.Size(36, 13);
this.lblLayers.TabIndex = 1;
this.lblLayers.Text = "Layer:";
//
// cboLayers
//
this.cboLayers.FormattingEnabled = true;
this.cboLayers.Location = new System.Drawing.Point(93, 19);
this.cboLayers.Name = "cboLayers";
this.cboLayers.Size = new System.Drawing.Size(250, 21);
this.cboLayers.TabIndex = 0;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.txtMessages);
this.groupBox2.Location = new System.Drawing.Point(2, 167);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(356, 146);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Messages";
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(135, 319);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(88, 23);
this.btnCancel.TabIndex = 2;
this.btnCancel.Text = "Dismiss";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtMessages
//
this.txtMessages.Location = new System.Drawing.Point(6, 15);
this.txtMessages.Multiline = true;
this.txtMessages.Name = "txtMessages";
this.txtMessages.ReadOnly = true;
this.txtMessages.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtMessages.Size = new System.Drawing.Size(344, 125);
this.txtMessages.TabIndex = 0;
//
// BufferDlg
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(361, 347);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "BufferDlg";
this.ShowInTaskbar = false;
this.Text = "Buffer";
this.TopMost = true;
this.Load += new System.EventHandler(this.bufferDlg_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ComboBox cboLayers;
private System.Windows.Forms.ComboBox cboUnits;
private System.Windows.Forms.TextBox txtBufferDistance;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblLayers;
private System.Windows.Forms.Button btnOutputLayer;
private System.Windows.Forms.TextBox txtOutputPath;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnBuffer;
private System.Windows.Forms.TextBox txtMessages;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Volte.Utils;
namespace Volte.Data.Json
{
[Serializable]
public class JSONArray {
const string ZFILE_NAME = "JSONArray";
// Methods
public JSONArray()
{
_JSONObjects = new List<JSONObject>();
_JSONArrays = new List<JSONArray>();
}
public JSONArray(string cData)
{
_JSONObjects = new List<JSONObject>();
_JSONArrays = new List<JSONArray>();
if (!string.IsNullOrEmpty(cData)) {
Parser(cData);
}
}
internal JSONArray(Lexer _Lexer)
{
_JSONObjects = new List<JSONObject>();
_JSONArrays = new List<JSONArray>();
this.Read(_Lexer);
}
internal void Read(Lexer _Lexer)
{
_Lexer.SkipWhiteSpace();
if (_Lexer.Current == '[') {
_Lexer.NextToken();
if (_Lexer.Current == ']')
{
_Lexer.NextToken();
return;
}
for (;;) {
if (_Lexer.Current == '[') {
JSONArray variable2 = new JSONArray();
variable2.Read(_Lexer);
this.Add(variable2);
} else if (_Lexer.Current == '{') {
JSONObject variable1 = new JSONObject();
variable1.Read(_Lexer);
this.Add(variable1);
}else{
string _s="";
if (char.IsDigit(_Lexer.Current) || _Lexer.Current == '-') {
_s= _Lexer.ParseValue();
}else if (_Lexer.Current == 'f' || _Lexer.Current == 't') {
_s= _Lexer.ParseValue();
}else{
_s= _Lexer.ParseValue();
}
this.Add(_s);
}
_Lexer.SkipWhiteSpace();
if (_Lexer.Current == ',') {
_Lexer.NextToken();
} else {
break;
}
}
_Lexer.NextToken();
}
}
internal void Write(StringBuilder writer)
{
writer.AppendLine("[");
int i = 0;
if (_Object.Count > 0) {
foreach (object sValue in _Object) {
if (i > 0) {
writer.Append(",");
writer.AppendLine("");
}
if (sValue is decimal || sValue is int || sValue is double || sValue is float){
writer.Append(sValue.ToString());
}else{
writer.Append("\"");
Util.EscapeString(writer, sValue.ToString());
writer.AppendLine("\"");
}
i++;
}
}
if (_JSONObjects.Count > 0) {
foreach (JSONObject name in _JSONObjects) {
if (i > 0) {
writer.Append(",");
writer.AppendLine("");
}
name.Write(writer);
i++;
}
}
if (_JSONArrays.Count > 0) {
foreach (JSONArray name in _JSONArrays) {
if (i > 0) {
writer.Append(",");
writer.AppendLine("");
}
name.Write(writer);
i++;
}
}
writer.AppendLine("");
writer.Append("]");
}
public void Parser(string cString)
{
if (string.IsNullOrEmpty(cString)) {
return;
}
Lexer oLexer = new Lexer(cString);
this.Read(oLexer);
}
public override string ToString()
{
return _ToString();
}
public JSONObject JSONObject(int index)
{
if (index<_JSONObjects.Count){
return _JSONObjects[index];
}else{
return new JSONObject();
}
}
public JSONArray Select(string name , string value)
{
JSONArray _JSONArray = new JSONArray();
foreach (JSONObject _record in _JSONObjects) {
if (_record.GetValue(name)==value){
_JSONArray.Add(_record);
}
}
return _JSONArray;
}
public JSONObject Lookup(string name , string value)
{
foreach (JSONObject _record in _JSONObjects) {
if (_record.GetValue(name)==value){
return _record;
}
}
return new JSONObject();
}
private string _ToString()
{
s.Length = 0;
this.Write(s);
return s.ToString();
}
public void Add(JSONArray value)
{
_JSONArrays.Add(value);
}
public void Remove(JSONArray value)
{
_JSONArrays.Remove(value);
}
public void Add(JSONObject value)
{
_JSONObjects.Add(value);
}
public void Add(object value)
{
_Object.Add(value);
}
public void Remove(JSONObject value)
{
_JSONObjects.Remove(value);
}
public void Remove(object value)
{
_Object.Remove(value);
}
public void Clear()
{
_JSONObjects = new List<JSONObject>();
_JSONArrays = new List<JSONArray>();
}
public List<JSONArray> JSONArrays
{
get {
return _JSONArrays;
}
}
public List<object> Names
{
get {
return _Object;
}
}
public List<JSONObject> JSONObjects
{
get {
return _JSONObjects;
}
}
public int Count
{
get {
return _JSONObjects.Count + _JSONArrays.Count + _Object.Count;
}
}
// JSONArray
private readonly StringBuilder s = new StringBuilder();
private List<JSONObject> _JSONObjects = new List<JSONObject>();
private List<JSONArray> _JSONArrays = new List<JSONArray>();
private List<object> _Object = new List<object>();
}
}
| |
// StreamManipulator.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// This class allows us to retrieve a specified number of bits from
/// the input buffer, as well as copy big byte blocks.
///
/// It uses an int buffer to store up to 31 bits for direct
/// manipulation. This guarantees that we can get at least 16 bits,
/// but we only need at most 15, so this is all safe.
///
/// There are some optimizations in this class, for example, you must
/// never peek more than 8 bits more than needed, and you must first
/// peek bits before you may drop them. This is not a general purpose
/// class but optimized for the behaviour of the Inflater.
///
/// authors of the original java version : John Leuner, Jochen Hoenicke
/// </summary>
public class StreamManipulator
{
private byte[] window;
private int window_start = 0;
private int window_end = 0;
private uint buffer = 0;
private int bits_in_buffer = 0;
/// <summary>
/// Get the next n bits but don't increase input pointer. n must be
/// less or equal 16 and if this call succeeds, you must drop
/// at least n - 8 bits in the next call.
/// </summary>
/// <returns>
/// the value of the bits, or -1 if not enough bits available. */
/// </returns>
public int PeekBits(int n)
{
if (bits_in_buffer < n) {
if (window_start == window_end) {
return -1; // ok
}
buffer |= (uint)((window[window_start++] & 0xff |
(window[window_start++] & 0xff) << 8) << bits_in_buffer);
bits_in_buffer += 16;
}
return (int)(buffer & ((1 << n) - 1));
}
/// <summary>
/// Drops the next n bits from the input. You should have called PeekBits
/// with a bigger or equal n before, to make sure that enough bits are in
/// the bit buffer.
/// </summary>
public void DropBits(int n)
{
buffer >>= n;
bits_in_buffer -= n;
}
/// <summary>
/// Gets the next n bits and increases input pointer. This is equivalent
/// to PeekBits followed by dropBits, except for correct error handling.
/// </summary>
/// <returns>
/// the value of the bits, or -1 if not enough bits available.
/// </returns>
public int GetBits(int n)
{
int bits = PeekBits(n);
if (bits >= 0) {
DropBits(n);
}
return bits;
}
/// <summary>
/// Gets the number of bits available in the bit buffer. This must be
/// only called when a previous PeekBits() returned -1.
/// </summary>
/// <returns>
/// the number of bits available.
/// </returns>
public int AvailableBits {
get {
return bits_in_buffer;
}
}
/// <summary>
/// Gets the number of bytes available.
/// </summary>
/// <returns>
/// The number of bytes available.
/// </returns>
public int AvailableBytes {
get {
return window_end - window_start + (bits_in_buffer >> 3);
}
}
/// <summary>
/// Skips to the next byte boundary.
/// </summary>
public void SkipToByteBoundary()
{
buffer >>= (bits_in_buffer & 7);
bits_in_buffer &= ~7;
}
/// <summary>
/// Returns true when SetInput can be called
/// </summary>
public bool IsNeedingInput {
get {
return window_start == window_end;
}
}
/// <summary>
/// Copies length bytes from input buffer to output buffer starting
/// at output[offset]. You have to make sure, that the buffer is
/// byte aligned. If not enough bytes are available, copies fewer
/// bytes.
/// </summary>
/// <param name="output">
/// The buffer to copy bytes to.
/// </param>
/// <param name="offset">
/// The offset in the buffer at which copying starts
/// </param>
/// <param name="length">
/// The length to copy, 0 is allowed.
/// </param>
/// <returns>
/// The number of bytes copied, 0 if no bytes were available.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Length is less than zero
/// </exception>
/// <exception cref="InvalidOperationException">
/// Bit buffer isnt byte aligned
/// </exception>
public int CopyBytes(byte[] output, int offset, int length)
{
if (length < 0) {
throw new ArgumentOutOfRangeException("length", "negative");
}
if ((bits_in_buffer & 7) != 0) {
/* bits_in_buffer may only be 0 or a multiple of 8 */
throw new InvalidOperationException("Bit buffer is not byte aligned!");
}
int count = 0;
while (bits_in_buffer > 0 && length > 0) {
output[offset++] = (byte) buffer;
buffer >>= 8;
bits_in_buffer -= 8;
length--;
count++;
}
if (length == 0) {
return count;
}
int avail = window_end - window_start;
if (length > avail) {
length = avail;
}
System.Array.Copy(window, window_start, output, offset, length);
window_start += length;
if (((window_start - window_end) & 1) != 0) {
/* We always want an even number of bytes in input, see peekBits */
buffer = (uint)(window[window_start++] & 0xff);
bits_in_buffer = 8;
}
return count + length;
}
/// <summary>
/// Constructs a default StreamManipulator with all buffers empty
/// </summary>
public StreamManipulator()
{
}
/// <summary>
/// resets state and empties internal buffers
/// </summary>
public void Reset()
{
buffer = (uint)(window_start = window_end = bits_in_buffer = 0);
}
/// <summary>
/// Add more input for consumption.
/// Only call when IsNeedingInput returns true
/// </summary>
/// <param name="buf">data to be input</param>
/// <param name="off">offset of first byte of input</param>
/// <param name="len">length of input</param>
public void SetInput(byte[] buf, int off, int len)
{
if (window_start < window_end) {
throw new InvalidOperationException("Old input was not completely processed");
}
int end = off + len;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if (0 > off || off > end || end > buf.Length) {
throw new ArgumentOutOfRangeException();
}
if ((len & 1) != 0) {
/* We always want an even number of bytes in input, see peekBits */
buffer |= (uint)((buf[off++] & 0xff) << bits_in_buffer);
bits_in_buffer += 8;
}
window = buf;
window_start = off;
window_end = end;
}
}
}
| |
/*
* NPlot - A charting library for .NET
*
* DateTimeAxis.cs
* Copyright (C) 2003-2006 Matt Howlett and others.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Drawing;
// TODO: More control over how labels are displayed.
// TODO: SkipWeekends property.
// TODO: Make a relative (as opposed to absolute) TimeAxis.
namespace NPlot
{
/// <summary>
/// The DateTimeAxis class
/// </summary>
public class DateTimeAxis : Axis
{
#region Clone implementation
/// <summary>
/// Deep copy of DateTimeAxis.
/// </summary>
/// <returns>A copy of the DateTimeAxis Class.</returns>
public override object Clone()
{
DateTimeAxis a = new DateTimeAxis();
// ensure that this isn't being called on a derived type. If it is, then oh no!
if (GetType() != a.GetType())
{
throw new NPlotException("Clone not defined in derived type. Help!");
}
DoClone(this, a);
return a;
}
/// <summary>
/// Helper method for Clone.
/// </summary>
/// <param name="a">The original object to clone.</param>
/// <param name="b">The cloned object.</param>
protected static void DoClone(DateTimeAxis b, DateTimeAxis a)
{
Axis.DoClone(b, a);
}
#endregion
/// <summary>
/// this gets set after a get LargeTickPositions.
/// </summary>
protected LargeTickLabelType LargeTickLabelType_;
private TimeSpan largeTickStep_ = TimeSpan.Zero;
/// <summary>
/// Constructor
/// </summary>
/// <param name="a">Axis to construct from</param>
public DateTimeAxis(Axis a)
: base(a)
{
Init();
NumberFormat = null;
}
/// <summary>
/// Default Constructor
/// </summary>
public DateTimeAxis()
{
Init();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="worldMin">World min of axis</param>
/// <param name="worldMax">World max of axis</param>
public DateTimeAxis(double worldMin, double worldMax)
: base(worldMin, worldMax)
{
Init();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="worldMin">World min of axis</param>
/// <param name="worldMax">World max of axis</param>
public DateTimeAxis(long worldMin, long worldMax)
: base(worldMin, worldMax)
{
Init();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="worldMin">World min of axis</param>
/// <param name="worldMax">World max of axis</param>
public DateTimeAxis(DateTime worldMin, DateTime worldMax)
: base(worldMin.Ticks, worldMax.Ticks)
{
Init();
}
/// <summary>
/// The distance between large ticks. If this is set to Zero [default],
/// this distance will be calculated automatically.
/// </summary>
public TimeSpan LargeTickStep
{
set { largeTickStep_ = value; }
get { return largeTickStep_; }
}
private void Init()
{
}
/// <summary>
/// Draw the ticks.
/// </summary>
/// <param name="g">The drawing surface on which to draw.</param>
/// <param name="physicalMin">The minimum physical extent of the axis.</param>
/// <param name="physicalMax">The maximum physical extent of the axis.</param>
/// <param name="boundingBox">out: smallest box that completely encompasses all of the ticks and tick labels.</param>
/// <param name="labelOffset">out: a suitable offset from the axis to draw the axis label.</param>
protected override void DrawTicks(
Graphics g,
Point physicalMin,
Point physicalMax,
out object labelOffset,
out object boundingBox)
{
// TODO: Look at offset and bounding box logic again here. why temp and other vars?
Point tLabelOffset;
Rectangle tBoundingBox;
labelOffset = getDefaultLabelOffset(physicalMin, physicalMax);
boundingBox = null;
ArrayList largeTicks;
ArrayList smallTicks;
WorldTickPositions(physicalMin, physicalMax, out largeTicks, out smallTicks);
// draw small ticks.
for (int i = 0; i < smallTicks.Count; ++i)
{
DrawTick(g, (double) smallTicks[i],
SmallTickSize, "", new Point(0, 0),
physicalMin, physicalMax,
out tLabelOffset, out tBoundingBox);
// assume label offset and bounding box unchanged by small tick bounds.
}
// draw large ticks.
for (int i = 0; i < largeTicks.Count; ++i)
{
DateTime tickDate = new DateTime((long) ((double) largeTicks[i]));
string label = LargeTickLabel(tickDate);
DrawTick(g, (double) largeTicks[i],
LargeTickSize, label, new Point(0, 0),
physicalMin, physicalMax, out tLabelOffset, out tBoundingBox);
UpdateOffsetAndBounds(ref labelOffset, ref boundingBox, tLabelOffset, tBoundingBox);
}
}
/// <summary>
/// Get the label corresponding to the provided date time
/// </summary>
/// <param name="tickDate">the date time to get the label for</param>
/// <returns>label for the provided DateTime</returns>
protected virtual string LargeTickLabel(DateTime tickDate)
{
string label = "";
if (NumberFormat == null || NumberFormat == String.Empty)
{
if (LargeTickLabelType_ == LargeTickLabelType.year)
{
label = tickDate.Year.ToString();
}
else if (LargeTickLabelType_ == LargeTickLabelType.month)
{
label = tickDate.ToString("MMM");
label += " ";
label += tickDate.Year.ToString().Substring(2, 2);
}
else if (LargeTickLabelType_ == LargeTickLabelType.day)
{
label = (tickDate.Day).ToString();
label += " ";
label += tickDate.ToString("MMM");
}
else if (LargeTickLabelType_ == LargeTickLabelType.hourMinute)
{
string minutes = tickDate.Minute.ToString();
if (minutes.Length == 1)
{
minutes = "0" + minutes;
}
label = tickDate.Hour.ToString() + ":" + minutes;
}
else if (LargeTickLabelType_ == LargeTickLabelType.hourMinuteSeconds)
{
string minutes = tickDate.Minute.ToString();
string seconds = tickDate.Second.ToString();
if (seconds.Length == 1)
{
seconds = "0" + seconds;
}
if (minutes.Length == 1)
{
minutes = "0" + minutes;
}
label = tickDate.Hour.ToString() + ":" + minutes + "." + seconds;
}
}
else
{
label = tickDate.ToString(NumberFormat);
}
return label;
}
/// <summary>
/// Determines the positions, in world coordinates, of the large ticks. No
/// small tick marks are currently calculated by this method.
/// </summary>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="largeTickPositions">ArrayList containing the positions of the large ticks.</param>
/// <param name="smallTickPositions">null</param>
internal override void WorldTickPositions_FirstPass(
Point physicalMin,
Point physicalMax,
out ArrayList largeTickPositions,
out ArrayList smallTickPositions
)
{
smallTickPositions = null;
largeTickPositions = new ArrayList();
const int daysInMonth = 30;
TimeSpan timeLength = new TimeSpan((long) (WorldMax - WorldMin));
DateTime worldMinDate = new DateTime((long) WorldMin);
DateTime worldMaxDate = new DateTime((long) WorldMax);
if (largeTickStep_ == TimeSpan.Zero)
{
// if less than 10 minutes, then large ticks on second spacings.
if (timeLength < new TimeSpan(0, 0, 2, 0, 0))
{
LargeTickLabelType_ = LargeTickLabelType.hourMinuteSeconds;
double secondsSkip;
if (timeLength < new TimeSpan(0, 0, 0, 10, 0))
secondsSkip = 1.0;
else if (timeLength < new TimeSpan(0, 0, 0, 20, 0))
secondsSkip = 2.0;
else if (timeLength < new TimeSpan(0, 0, 0, 50, 0))
secondsSkip = 5.0;
else if (timeLength < new TimeSpan(0, 0, 2, 30, 0))
secondsSkip = 15.0;
else
secondsSkip = 30.0;
int second = worldMinDate.Second;
second -= second%(int) secondsSkip;
DateTime currentTickDate = new DateTime(
worldMinDate.Year,
worldMinDate.Month,
worldMinDate.Day,
worldMinDate.Hour,
worldMinDate.Minute,
second, 0);
while (currentTickDate < worldMaxDate)
{
double world = currentTickDate.Ticks;
if (world >= WorldMin && world <= WorldMax)
{
largeTickPositions.Add(world);
}
currentTickDate = currentTickDate.AddSeconds(secondsSkip);
}
}
// Less than 2 hours, then large ticks on minute spacings.
else if (timeLength < new TimeSpan(0, 2, 0, 0, 0))
{
LargeTickLabelType_ = LargeTickLabelType.hourMinute;
double minuteSkip;
if (timeLength < new TimeSpan(0, 0, 10, 0, 0))
minuteSkip = 1.0;
else if (timeLength < new TimeSpan(0, 0, 20, 0, 0))
minuteSkip = 2.0;
else if (timeLength < new TimeSpan(0, 0, 50, 0, 0))
minuteSkip = 5.0;
else if (timeLength < new TimeSpan(0, 2, 30, 0, 0))
minuteSkip = 15.0;
else //( timeLength < new TimeSpan( 0,5,0,0,0) )
minuteSkip = 30.0;
int minute = worldMinDate.Minute;
minute -= minute%(int) minuteSkip;
DateTime currentTickDate = new DateTime(
worldMinDate.Year,
worldMinDate.Month,
worldMinDate.Day,
worldMinDate.Hour,
minute, 0, 0);
while (currentTickDate < worldMaxDate)
{
double world = currentTickDate.Ticks;
if (world >= WorldMin && world <= WorldMax)
{
largeTickPositions.Add(world);
}
currentTickDate = currentTickDate.AddMinutes(minuteSkip);
}
}
// Less than 2 days, then large ticks on hour spacings.
else if (timeLength < new TimeSpan(2, 0, 0, 0, 0))
{
LargeTickLabelType_ = LargeTickLabelType.hourMinute;
double hourSkip;
if (timeLength < new TimeSpan(0, 10, 0, 0, 0))
hourSkip = 1.0;
else if (timeLength < new TimeSpan(0, 20, 0, 0, 0))
hourSkip = 2.0;
else
hourSkip = 6.0;
int hour = worldMinDate.Hour;
hour -= hour%(int) hourSkip;
DateTime currentTickDate = new DateTime(
worldMinDate.Year,
worldMinDate.Month,
worldMinDate.Day,
hour, 0, 0, 0);
while (currentTickDate < worldMaxDate)
{
double world = currentTickDate.Ticks;
if (world >= WorldMin && world <= WorldMax)
{
largeTickPositions.Add(world);
}
currentTickDate = currentTickDate.AddHours(hourSkip);
}
}
// less than 5 months, then large ticks on day spacings.
else if (timeLength < new TimeSpan(daysInMonth*4, 0, 0, 0, 0))
{
LargeTickLabelType_ = LargeTickLabelType.day;
double daySkip;
if (timeLength < new TimeSpan(10, 0, 0, 0, 0))
daySkip = 1.0;
else if (timeLength < new TimeSpan(20, 0, 0, 0, 0))
daySkip = 2.0;
else if (timeLength < new TimeSpan(7*10, 0, 0, 0, 0))
daySkip = 7.0;
else
daySkip = 14.0;
DateTime currentTickDate = new DateTime(
worldMinDate.Year,
worldMinDate.Month,
worldMinDate.Day);
if (daySkip == 2.0)
{
TimeSpan timeSinceBeginning = currentTickDate - DateTime.MinValue;
if (timeSinceBeginning.Days%2 == 1)
currentTickDate = currentTickDate.AddDays(-1.0);
}
if (daySkip == 7 || daySkip == 14.0)
{
DayOfWeek dow = currentTickDate.DayOfWeek;
switch (dow)
{
case DayOfWeek.Monday:
break;
case DayOfWeek.Tuesday:
currentTickDate = currentTickDate.AddDays(-1.0);
break;
case DayOfWeek.Wednesday:
currentTickDate = currentTickDate.AddDays(-2.0);
break;
case DayOfWeek.Thursday:
currentTickDate = currentTickDate.AddDays(-3.0);
break;
case DayOfWeek.Friday:
currentTickDate = currentTickDate.AddDays(-4.0);
break;
case DayOfWeek.Saturday:
currentTickDate = currentTickDate.AddDays(-5.0);
break;
case DayOfWeek.Sunday:
currentTickDate = currentTickDate.AddDays(-6.0);
break;
}
}
if (daySkip == 14.0f)
{
TimeSpan timeSinceBeginning = currentTickDate - DateTime.MinValue;
if ((timeSinceBeginning.Days/7)%2 == 1)
{
currentTickDate = currentTickDate.AddDays(-7.0);
}
}
while (currentTickDate < worldMaxDate)
{
double world = currentTickDate.Ticks;
if (world >= WorldMin && world <= WorldMax)
{
largeTickPositions.Add(world);
}
currentTickDate = currentTickDate.AddDays(daySkip);
}
}
// else ticks on month or year spacings.
else if (timeLength >= new TimeSpan(daysInMonth*4, 0, 0, 0, 0))
{
int monthSpacing = 0;
if (timeLength.Days < daysInMonth*(12*3 + 6))
{
LargeTickLabelType_ = LargeTickLabelType.month;
if (timeLength.Days < daysInMonth*10)
monthSpacing = 1;
else if (timeLength.Days < daysInMonth*(12*2))
monthSpacing = 3;
else // if ( timeLength.Days < daysInMonth*(12*3+6) )
monthSpacing = 6;
}
else
{
LargeTickLabelType_ = LargeTickLabelType.year;
if (timeLength.Days < daysInMonth*(12*6))
monthSpacing = 12;
else if (timeLength.Days < daysInMonth*(12*12))
monthSpacing = 24;
else if (timeLength.Days < daysInMonth*(12*30))
monthSpacing = 60;
else
monthSpacing = 120;
//LargeTickLabelType_ = LargeTickLabelType.none;
}
// truncate start
DateTime currentTickDate = new DateTime(
worldMinDate.Year,
worldMinDate.Month,
1);
if (monthSpacing > 1)
{
currentTickDate = currentTickDate.AddMonths(
-(currentTickDate.Month - 1)%monthSpacing);
}
// Align on 2 or 5 year boundaries if necessary.
if (monthSpacing >= 24)
{
currentTickDate = currentTickDate.AddYears(
-(currentTickDate.Year)%(monthSpacing/12));
}
//this.firstLargeTick_ = (double)currentTickDate.Ticks;
if (LargeTickLabelType_ != LargeTickLabelType.none)
{
while (currentTickDate < worldMaxDate)
{
double world = currentTickDate.Ticks;
if (world >= WorldMin && world <= WorldMax)
{
largeTickPositions.Add(world);
}
currentTickDate = currentTickDate.AddMonths(monthSpacing);
}
}
}
}
else
{
for (DateTime date = worldMinDate; date < worldMaxDate; date += largeTickStep_)
{
largeTickPositions.Add((double) date.Ticks);
}
}
}
/// <summary>
/// Compute the small tick positions for largetick size of one or more years.
/// - inside the domain or the large tick positons, is take the mid-point of pairs of large ticks
/// - outside the large tick range, check if a half tick is inside the world min/max
/// This method works only if there are atleast 2 large ticks,
/// since we don't know if its minutes, hours, month, or yearly divisor.
/// </summary>
/// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param>
/// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param>
/// <param name="largeTickPositions">Read in the large tick positions</param>
/// <param name="smallTickPositions">Fill in the corresponding small tick positions</param>
/// <remarks>Added by Rosco Hill</remarks>
internal override void WorldTickPositions_SecondPass(
Point physicalMin,
Point physicalMax,
ArrayList largeTickPositions,
ref ArrayList smallTickPositions
)
{
if (largeTickPositions.Count < 2 || !(LargeTickLabelType_.Equals(LargeTickLabelType.year)))
{
smallTickPositions = new ArrayList();
;
}
else
{
smallTickPositions = new ArrayList();
double diff = 0.5*(((double) largeTickPositions[1]) - ((double) largeTickPositions[0]));
if (((double) largeTickPositions[0] - diff) > WorldMin)
{
smallTickPositions.Add((double) largeTickPositions[0] - diff);
}
for (int i = 0; i < largeTickPositions.Count - 1; i++)
{
smallTickPositions.Add(((double) largeTickPositions[i]) + diff);
}
if (((double) largeTickPositions[largeTickPositions.Count - 1] + diff) < WorldMax)
{
smallTickPositions.Add((double) largeTickPositions[largeTickPositions.Count - 1] + diff);
}
}
}
/// <summary>
/// Enumerates the different types of tick label possible.
/// </summary>
protected enum LargeTickLabelType
{
/// <summary>
/// default - no tick labels.
/// </summary>
none = 0,
/// <summary>
/// tick labels should be years
/// </summary>
year = 1,
/// <summary>
/// Tick labels should be month names
/// </summary>
month = 2,
/// <summary>
/// Tick labels should be day names
/// </summary>
day = 3,
/// <summary>
/// Tick labels should be hour / minutes.
/// </summary>
hourMinute = 4,
/// <summary>
/// tick labels should be hour / minute / second.
/// </summary>
hourMinuteSeconds = 5
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
using System.Collections.Generic;
/*! \The Heatmap class is responsible for creating the "heat" and textures.
*
* Contains all methods necessary for creating a Heatmap.
*/
public class Heatmap : ScriptableObject {
#if UNITY_EDITOR
[MenuItem("Window/Heatmap Documentation")]
public static void OpenDocs()
{
Application.OpenURL("http://paraboxstudios.com/heatmap/docs/annotated.html");
}
#endif
public static GameObject projectionPlane; //!< A static reference to the plane which is used to display a heatmap.
public static int RED_THRESHOLD = 235; //!< Red threshold.
/// Minimum alpha a point must have to be red.
public static int GREEN_THRESHOLD = 200; //!< Green threshold.
/// Minimum alpha a point must have to be green.
public static int BLUE_THRESHOLD = 150; //!< Blue threshold.
/// Minimum alpha a point must have to be Blue.
public static int MINIMUM_THRESHOLD = 100; //!< Minimum threshold.
/// Minimum alpha a point must have to be rendered at all.
/*! <summary>
* Creates a Heatmap image given a set of world points.
* </summary>
* <remarks>
* This method accepts a series of world points, and returns a transparent overlay of the heatmap. Usually you will want to pair this call with CreateRenderPlane() to actually view the heatmap.
* </remarks>
* <param name="worldPoints">An array of Vector3 points to be translated into heatmap points.</param>
* <param name="cam">The camera to render from. If passed a null value, CreateHeatmap() attempts to use Camera.main.</param>
* <param name="radius">Raidus in pixels that each point should create. Larger radii produce denser heatmaps, and vice-versa.</param>
* <returns>Returns a new Texture2D containing a transparent overlay of the heatmap.</returns>
*/
public static Texture2D CreateHeatmap(Vector3[] worldPoints, Camera cam, int radius) {
if(cam == null) {
if(Camera.main == null) {
Debug.LogWarning("No camera found. Returning an empty texture.");
return new Texture2D(0, 0);
}
else
cam = Camera.main;
}
// Create new texture
// Texture2D map = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
Texture2D map = new Texture2D( (int)cam.pixelWidth, (int)cam.pixelHeight, TextureFormat.ARGB32, false);
// Set texture to alpha-fied state
map.SetPixels(Heatmap.ColorArray(new Color(1f, 1f, 1f, 0f), map.width*map.height), 0);
// Convert world to screen points
Vector2[] points = new Vector2[worldPoints.Length];
for(int i = 0; i < worldPoints.Length; i++) {
points[i] = cam.WorldToScreenPoint(worldPoints[i]);
}
/*** Generate Grayscale Values ***/
{
int x2; // the offset x val in img coordinates
int y2; // the offset y val in img coordinates (0,0) - (maxX, maxY)
float pointAlpha = .9f; // The alpha that the darkest pixel will be in a poitn.
Color color = new Color(1f, 1f, 1f, pointAlpha);
int lineWidth = 1;//(int)(radius * .05f);
Dictionary<Vector2, Color> pixelAlpha = new Dictionary<Vector2, Color>();
for(int i = 0; i < points.Length; i++) // generate alpha add for each point and a specified circumference
{
pixelAlpha.Clear();
for(int r = 0; r < radius; r+=lineWidth) // draw and fill them circles
{
for(int angle=0; angle<360; angle++)
{
x2 = (int)(r * Mathf.Cos(angle))+(int)points[i].x;
y2 = (int)(r * Mathf.Sin(angle))+(int)points[i].y;
// This could be sped up
for(int y = y2; y > y2-lineWidth; y--) {
for(int x = x2; x < x2+lineWidth; x++) {
Vector2 coord = new Vector2(x, y);
if(pixelAlpha.ContainsKey(coord))
pixelAlpha[coord] = color;
else
pixelAlpha.Add(new Vector2(x, y), color);
}
}
}
color = new Color(color.r, color.g, color.b, color.a - (pointAlpha/( (float)radius/lineWidth)) );
}
// Since the radial fill code overwrites it's own pixels, make sure to only add finalized alpha to
// old values.
foreach (KeyValuePair<Vector2, Color> keyval in pixelAlpha)
{
Vector2 coord = keyval.Key;
Color previousColor = map.GetPixel((int)coord.x, (int)coord.y);
Color newColor = keyval.Value;
map.SetPixel((int)coord.x, (int)coord.y, new Color(newColor.r, newColor.b, newColor.g, newColor.a + previousColor.a));
}
// Reset color for next point
color = new Color(color.r, color.g, color.b, pointAlpha);
}
}
map.Apply();
map.SetPixels( Colorize(map.GetPixels(0)), 0);
map.Apply();
return map;
}
/*! <summary>
* Creates a gameObject in front of the camera, and applies the supplied texture.
* </summary>
* <remarks>
* Works best with an orthographic camera. It builds the mesh using camera dimensions translated into world space. Use this in conjunction with CreateHeatmap() to create a heatmap and capture a screenshot with the heatmap texture overlaying the world.
* </remarks>
* <param name="map">The heatmap image.</param>
*/
public static void CreateRenderPlane(Texture2D map)
{
CreateRenderPlane(map, null);
}
/*! <summary>
* Creates a gameObject in front of the camera, and applies the supplied texture.
* </summary>
* <remarks>
* Works best with an orthographic camera. It builds the mesh using camera dimensions translated into world space. Use this in conjunction with CreateHeatmap() to create a heatmap and capture a screenshot with the heatmap texture overlaying the world.
* </remarks>
* <param name="map">The heatmap image.</param>
* <param name="cam">The camera to render from. If passed a null value, CreateRenderPlane() attempts to use Camera.main.</param>
*/
public static void CreateRenderPlane(Texture2D map, Camera cam)
{
if(cam == null) {
if(Camera.main == null) {
Debug.LogWarning("No camera found. Plane not created.");
return;
}
else
cam = Camera.main;
}
// Create Plane to project Heatmap
Mesh m = new Mesh();
Vector3[] vertices = new Vector3[4];
int[] triangles = new int[6] {
2, 1, 0,
2, 3, 1
};
vertices[0] = cam.ScreenToWorldPoint(new Vector2(0f, 0f));
vertices[1] = cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, 0f));
vertices[2] = cam.ScreenToWorldPoint(new Vector2(0f, cam.pixelHeight));
vertices[3] = cam.ScreenToWorldPoint(new Vector2(cam.pixelWidth, cam.pixelHeight));
Vector2[] uvs = new Vector2[4];
uvs[0] = new Vector2(0f, 0f);
uvs[1] = new Vector2(1f, 0f);
uvs[2] = new Vector2(0f, 1f);
uvs[3] = new Vector2(1f, 1f);
m.vertices = vertices;
m.triangles = triangles;
m.uv = uvs;
m.RecalculateNormals();
m.Optimize();
// Hook it all up
if(projectionPlane == null) {
projectionPlane = new GameObject();
projectionPlane.AddComponent<MeshFilter>();
projectionPlane.AddComponent<MeshRenderer>();
} else {
DestroyImmediate(projectionPlane.GetComponent<MeshFilter>().sharedMesh);
DestroyImmediate(projectionPlane.GetComponent<MeshRenderer>().sharedMaterial.mainTexture);
}
projectionPlane.GetComponent<MeshFilter>().sharedMesh = m;
MeshRenderer mr = projectionPlane.GetComponent<MeshRenderer>();
Material mat = (Material)Resources.Load("UnlitMaterial");
mat.mainTexture = map;
mr.sharedMaterial = mat;
projectionPlane.name = "Heatmap Render Plane";
// Move the heatmap gameobject in front of the camera
projectionPlane.transform.position = new Vector3(0f, 0f, 0f);
projectionPlane.transform.Translate(Vector3.forward, cam.transform);
}
/*! <summary>
* Creates and saves a screenshot.
* </summary>
* <remarks>
* Call this to take a screenshot with the current camera. Will not overwrite images if path already exists.
* </remarks>
* <param name="map">The path to save screenshot image to. Path is relative to Unity project. Ex: "Assets/MyScreenshot.png"</param>
* <returns>
* Returns a string containing the actual path image was saved to. This may be different than passed string if the path previously existed.
* </returns>
*/
public static string Screenshot(string path)
{
return Heatmap.Screenshot(path, (Camera)null);
}
/*! <summary>
* Creates and saves a screenshot.
* </summary>
* <remarks>
* Call this to take a screenshot with the current camera. Will not overwrite images if path already exists.
* </remarks>
* <param name="path">The path to save screenshot image to. Path is relative to Unity project. Ex: "Assets/MyScreenshot.png"</param>
* <param name="cam">The camera to render from. If passed a null value, CreateRenderPlane() attempts to use Camera.main.</param>
* <returns>
* Returns a string containing the actual path image was saved to. This may be different than passed string if the path previously existed.
* </returns>
*/
public static string Screenshot(string path, Camera cam)
{
if(cam == null) {
if(Camera.main == null)
return "Error! No camera found.";
else
cam = Camera.main;
}
foreach(Camera c in Camera.allCameras)
c.enabled = false;
cam.enabled = true;
int i = 0;
while(System.IO.File.Exists(path))
path = path.Replace(".png", ++i + ".png");
Application.CaptureScreenshot(path, 4);
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif
return path;
}
/*! \brief Destroy any temporary objects created by the Heatmap class.
*
* By default, CreateHeatmap() creates a plane situated in front of the
* camera to display the resulting heatmap. Call Release() to destroy
* the heatmap image and mesh.
*/
public static void DestroyHeatmapObjects()
{
if(projectionPlane) {
if(projectionPlane.GetComponent<MeshRenderer>().sharedMaterial.mainTexture != null)
DestroyImmediate(projectionPlane.GetComponent<MeshRenderer>().sharedMaterial.mainTexture);
DestroyImmediate(projectionPlane);
}
}
public static Color[] ColorArray(Color col, int arraySize)
{
Color[] colArr = new Color[arraySize];
for(int i = 0; i < colArr.Length; i++)
{
colArr[i] = col;
}
return colArr;
}
/*
* !!!
* The Colorize() function is a modified version of the Colorize() method found
* in the Mapex library. This is the license associated with it. This license
* does not apply to the rest of the codebase included in this project, as it is
* covered by the Unity Asset Store EULA.
*
* Copyright (C) 2011 by Vinicius Carvalho (vinnie@androidnatic.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.
*/
public static Color[] Colorize(Color[] pixels) {
for (int i = 0; i < pixels.Length; i++) {
float r = 0, g = 0, b = 0, tmp = 0;
pixels[i] *= 255f;
float alpha = pixels[i].a;
if (alpha == 0) {
continue;
}
if (alpha <= 255 && alpha >= RED_THRESHOLD) {
tmp = 255 - alpha;
r = 255 - tmp;
g = tmp * 12f;
} else if (alpha <= (RED_THRESHOLD - 1) && alpha >= GREEN_THRESHOLD) {
tmp = (RED_THRESHOLD - 1) - alpha;
r = 255 - (tmp * 8f);
g = 255;
} else if (alpha <= (GREEN_THRESHOLD - 1) && alpha >= BLUE_THRESHOLD) {
tmp = (GREEN_THRESHOLD - 1) - alpha;
g = 255;
b = tmp * 5;
} else if (alpha <= (BLUE_THRESHOLD - 1) && alpha >= MINIMUM_THRESHOLD) {
tmp = (BLUE_THRESHOLD - 1) - alpha;
g = 255 - (tmp * 5f);
b = 255;
} else
b = 255;
pixels[i] = new Color(r, g, b, alpha / 2f);
pixels[i] = NormalizeColor(pixels[i]);
}
return pixels;
}
public static Color NormalizeColor(Color col)
{
return new Color( col.r / 255f, col.g / 255f, col.b / 255f, col.a / 255f);
}
public static Bounds WorldBounds()
{
Object[] allGameObjects = FindObjectsOfType(typeof(GameObject));
GameObject p = new GameObject();
foreach(GameObject g in allGameObjects)
g.transform.parent = p.transform;
Component[] meshFilters = p.GetComponentsInChildren(typeof(MeshFilter));
Vector3 min, max;
if(meshFilters.Length > 0)
{
min = ((MeshFilter)meshFilters[0]).gameObject.transform.TransformPoint(((MeshFilter)meshFilters[0]).sharedMesh.vertices[0]);
max = min;
}
else
{
return new Bounds();
}
foreach(MeshFilter mf in meshFilters) {
Vector3[] v = mf.sharedMesh.vertices;
for(int i = 0; i < v.Length; i++)
{
Vector3 w = mf.gameObject.transform.TransformPoint(v[i]);
if(w.x > max.x) max.x = w.x;
if(w.x < min.x) min.x = w.x;
if(w.y > max.y) max.y = w.y;
if(w.y < min.y) min.y = w.y;
if(w.z > max.z) max.z = w.z;
if(w.z < min.z) min.z = w.z;
}
}
p.transform.DetachChildren();
DestroyImmediate(p);
Vector3 size = new Vector3( (max.x - min.x), (max.y - min.y), (max.z - min.z) );
return new Bounds(size/2f + min, size);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Threading;
namespace System.Transactions
{
internal interface IPromotedEnlistment
{
void EnlistmentDone();
void Prepared();
void ForceRollback();
void ForceRollback(Exception e);
void Committed();
void Aborted();
void Aborted(Exception e);
void InDoubt();
void InDoubt(Exception e);
byte[] GetRecoveryInformation();
InternalEnlistment InternalEnlistment
{
get;
set;
}
}
//
// InternalEnlistment by itself can support a Phase0 volatile enlistment.
// There are derived classes to support durable, phase1 volatile & PSPE
// enlistments.
//
internal class InternalEnlistment : ISinglePhaseNotificationInternal
{
// Storage for the state of the enlistment.
internal EnlistmentState _twoPhaseState;
// Interface implemented by the enlistment owner for notifications
protected IEnlistmentNotification _twoPhaseNotifications;
// Store a reference to the single phase notification interface in case
// the enlisment supports it.
protected ISinglePhaseNotification _singlePhaseNotifications;
// Reference to the containing transaction.
protected InternalTransaction _transaction;
// Reference to the lightweight transaction.
private readonly Transaction _atomicTransaction;
// The EnlistmentTraceIdentifier for this enlistment.
private EnlistmentTraceIdentifier _traceIdentifier;
// Unique value amongst all enlistments for a given internal transaction.
private readonly int _enlistmentId;
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (Transaction != null)
{
returnValue = Transaction.DistributedTxId;
}
return returnValue;
}
}
// Parent Enlistment Object
private readonly Enlistment _enlistment;
private PreparingEnlistment _preparingEnlistment;
private SinglePhaseEnlistment _singlePhaseEnlistment;
// If this enlistment is promoted store the object it delegates to.
private IPromotedEnlistment _promotedEnlistment;
// For Recovering Enlistments
protected InternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications)
{
Debug.Assert(this is RecoveringInternalEnlistment, "this is RecoveringInternalEnlistment");
_enlistment = enlistment;
_twoPhaseNotifications = twoPhaseNotifications;
_enlistmentId = 1;
_traceIdentifier = EnlistmentTraceIdentifier.Empty;
}
// For Promotable Enlistments
protected InternalEnlistment(Enlistment enlistment, InternalTransaction transaction, Transaction atomicTransaction)
{
Debug.Assert(this is PromotableInternalEnlistment, "this is PromotableInternalEnlistment");
_enlistment = enlistment;
_transaction = transaction;
_atomicTransaction = atomicTransaction;
_enlistmentId = transaction._enlistmentCount++;
_traceIdentifier = EnlistmentTraceIdentifier.Empty;
}
internal InternalEnlistment(
Enlistment enlistment,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction)
{
_enlistment = enlistment;
_transaction = transaction;
_twoPhaseNotifications = twoPhaseNotifications;
_singlePhaseNotifications = singlePhaseNotifications;
_atomicTransaction = atomicTransaction;
_enlistmentId = transaction._enlistmentCount++;
_traceIdentifier = EnlistmentTraceIdentifier.Empty;
}
internal InternalEnlistment(
Enlistment enlistment,
IEnlistmentNotification twoPhaseNotifications,
InternalTransaction transaction,
Transaction atomicTransaction)
{
_enlistment = enlistment;
_twoPhaseNotifications = twoPhaseNotifications;
_transaction = transaction;
_atomicTransaction = atomicTransaction;
}
internal EnlistmentState State
{
get { return _twoPhaseState; }
set { _twoPhaseState = value; }
}
internal Enlistment Enlistment => _enlistment;
internal PreparingEnlistment PreparingEnlistment
{
get
{
if (_preparingEnlistment == null)
{
// If there is a race here one of the objects would simply be garbage collected.
_preparingEnlistment = new PreparingEnlistment(this);
}
return _preparingEnlistment;
}
}
internal SinglePhaseEnlistment SinglePhaseEnlistment
{
get
{
if (_singlePhaseEnlistment == null)
{
// If there is a race here one of the objects would simply be garbage collected.
_singlePhaseEnlistment = new SinglePhaseEnlistment(this);
}
return _singlePhaseEnlistment;
}
}
internal InternalTransaction Transaction => _transaction;
internal virtual object SyncRoot
{
get
{
Debug.Assert(_transaction != null, "this.transaction != null");
return _transaction;
}
}
internal IEnlistmentNotification EnlistmentNotification => _twoPhaseNotifications;
internal ISinglePhaseNotification SinglePhaseNotification => _singlePhaseNotifications;
internal virtual IPromotableSinglePhaseNotification PromotableSinglePhaseNotification
{
get
{
Debug.Fail("PromotableSinglePhaseNotification called for a non promotable enlistment.");
throw new NotImplementedException();
}
}
internal IPromotedEnlistment PromotedEnlistment
{
get { return _promotedEnlistment; }
set { _promotedEnlistment = value; }
}
internal EnlistmentTraceIdentifier EnlistmentTraceId
{
get
{
if (_traceIdentifier == EnlistmentTraceIdentifier.Empty)
{
lock (SyncRoot)
{
if (_traceIdentifier == EnlistmentTraceIdentifier.Empty)
{
EnlistmentTraceIdentifier temp;
if (null != _atomicTransaction)
{
temp = new EnlistmentTraceIdentifier(
Guid.Empty,
_atomicTransaction.TransactionTraceId,
_enlistmentId);
}
else
{
temp = new EnlistmentTraceIdentifier(
Guid.Empty,
new TransactionTraceIdentifier(
InternalTransaction.InstanceIdentifier +
Convert.ToString(Interlocked.Increment(ref InternalTransaction._nextHash), CultureInfo.InvariantCulture),
0),
_enlistmentId);
}
Interlocked.MemoryBarrier();
_traceIdentifier = temp;
}
}
}
return _traceIdentifier;
}
}
internal virtual void FinishEnlistment()
{
// Note another enlistment finished.
Transaction._phase0Volatiles._preparedVolatileEnlistments++;
CheckComplete();
}
internal virtual void CheckComplete()
{
// Make certain we increment the right list.
Debug.Assert(Transaction._phase0Volatiles._preparedVolatileEnlistments <=
Transaction._phase0Volatiles._volatileEnlistmentCount + Transaction._phase0Volatiles._dependentClones);
// Check to see if all of the volatile enlistments are done.
if (Transaction._phase0Volatiles._preparedVolatileEnlistments ==
Transaction._phase0VolatileWaveCount + Transaction._phase0Volatiles._dependentClones)
{
Transaction.State.Phase0VolatilePrepareDone(Transaction);
}
}
internal virtual Guid ResourceManagerIdentifier
{
get
{
Debug.Fail("ResourceManagerIdentifier called for non durable enlistment");
throw new NotImplementedException();
}
}
void ISinglePhaseNotificationInternal.SinglePhaseCommit(IPromotedEnlistment singlePhaseEnlistment)
{
bool spcCommitted = false;
_promotedEnlistment = singlePhaseEnlistment;
try
{
_singlePhaseNotifications.SinglePhaseCommit(SinglePhaseEnlistment);
spcCommitted = true;
}
finally
{
if (!spcCommitted)
{
SinglePhaseEnlistment.InDoubt();
}
}
}
void IEnlistmentNotificationInternal.Prepare(
IPromotedEnlistment preparingEnlistment
)
{
_promotedEnlistment = preparingEnlistment;
_twoPhaseNotifications.Prepare(PreparingEnlistment);
}
void IEnlistmentNotificationInternal.Commit(
IPromotedEnlistment enlistment
)
{
_promotedEnlistment = enlistment;
_twoPhaseNotifications.Commit(Enlistment);
}
void IEnlistmentNotificationInternal.Rollback(
IPromotedEnlistment enlistment
)
{
_promotedEnlistment = enlistment;
_twoPhaseNotifications.Rollback(Enlistment);
}
void IEnlistmentNotificationInternal.InDoubt(
IPromotedEnlistment enlistment
)
{
_promotedEnlistment = enlistment;
_twoPhaseNotifications.InDoubt(Enlistment);
}
}
internal class DurableInternalEnlistment : InternalEnlistment
{
// Resource Manager Identifier for this enlistment if it is durable
internal Guid _resourceManagerIdentifier;
internal DurableInternalEnlistment(
Enlistment enlistment,
Guid resourceManagerIdentifier,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction) :
base(enlistment, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction)
{
_resourceManagerIdentifier = resourceManagerIdentifier;
}
protected DurableInternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications) :
base(enlistment, twoPhaseNotifications)
{
}
internal override Guid ResourceManagerIdentifier => _resourceManagerIdentifier;
}
//
// Since RecoveringInternalEnlistment does not have a transaction it must take
// a separate object as its sync root.
//
internal class RecoveringInternalEnlistment : DurableInternalEnlistment
{
private readonly object _syncRoot;
internal RecoveringInternalEnlistment(Enlistment enlistment, IEnlistmentNotification twoPhaseNotifications, object syncRoot) :
base(enlistment, twoPhaseNotifications)
{
_syncRoot = syncRoot;
}
internal override object SyncRoot => _syncRoot;
}
internal class PromotableInternalEnlistment : InternalEnlistment
{
// This class acts as the durable single phase enlistment for a
// promotable single phase enlistment.
private readonly IPromotableSinglePhaseNotification _promotableNotificationInterface;
internal PromotableInternalEnlistment(
Enlistment enlistment,
InternalTransaction transaction,
IPromotableSinglePhaseNotification promotableSinglePhaseNotification,
Transaction atomicTransaction) :
base(enlistment, transaction, atomicTransaction)
{
_promotableNotificationInterface = promotableSinglePhaseNotification;
}
internal override IPromotableSinglePhaseNotification PromotableSinglePhaseNotification => _promotableNotificationInterface;
}
// This class supports volatile enlistments
//
internal class Phase1VolatileEnlistment : InternalEnlistment
{
public Phase1VolatileEnlistment(
Enlistment enlistment,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction)
: base(enlistment, transaction, twoPhaseNotifications, singlePhaseNotifications, atomicTransaction)
{
}
internal override void FinishEnlistment()
{
// Note another enlistment finished.
_transaction._phase1Volatiles._preparedVolatileEnlistments++;
CheckComplete();
}
internal override void CheckComplete()
{
// Make certain we increment the right list.
Debug.Assert(_transaction._phase1Volatiles._preparedVolatileEnlistments <=
_transaction._phase1Volatiles._volatileEnlistmentCount +
_transaction._phase1Volatiles._dependentClones);
// Check to see if all of the volatile enlistments are done.
if (_transaction._phase1Volatiles._preparedVolatileEnlistments ==
_transaction._phase1Volatiles._volatileEnlistmentCount +
_transaction._phase1Volatiles._dependentClones)
{
_transaction.State.Phase1VolatilePrepareDone(_transaction);
}
}
}
public class Enlistment
{
// Interface for communicating with the state machine.
internal InternalEnlistment _internalEnlistment;
internal Enlistment(InternalEnlistment internalEnlistment)
{
_internalEnlistment = internalEnlistment;
}
internal Enlistment(
Guid resourceManagerIdentifier,
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction)
{
_internalEnlistment = new DurableInternalEnlistment(
this,
resourceManagerIdentifier,
transaction,
twoPhaseNotifications,
singlePhaseNotifications,
atomicTransaction
);
}
internal Enlistment(
InternalTransaction transaction,
IEnlistmentNotification twoPhaseNotifications,
ISinglePhaseNotification singlePhaseNotifications,
Transaction atomicTransaction,
EnlistmentOptions enlistmentOptions)
{
if ((enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0)
{
_internalEnlistment = new InternalEnlistment(
this,
transaction,
twoPhaseNotifications,
singlePhaseNotifications,
atomicTransaction
);
}
else
{
_internalEnlistment = new Phase1VolatileEnlistment(
this,
transaction,
twoPhaseNotifications,
singlePhaseNotifications,
atomicTransaction
);
}
}
// This constructor is for a promotable single phase enlistment.
internal Enlistment(
InternalTransaction transaction,
IPromotableSinglePhaseNotification promotableSinglePhaseNotification,
Transaction atomicTransaction)
{
_internalEnlistment = new PromotableInternalEnlistment(
this,
transaction,
promotableSinglePhaseNotification,
atomicTransaction
);
}
internal Enlistment(
IEnlistmentNotification twoPhaseNotifications,
InternalTransaction transaction,
Transaction atomicTransaction)
{
_internalEnlistment = new InternalEnlistment(
this,
twoPhaseNotifications,
transaction,
atomicTransaction
);
}
internal Enlistment(IEnlistmentNotification twoPhaseNotifications, object syncRoot)
{
_internalEnlistment = new RecoveringInternalEnlistment(
this,
twoPhaseNotifications,
syncRoot
);
}
public void Done()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.EnlistmentDone(_internalEnlistment);
}
lock (_internalEnlistment.SyncRoot)
{
_internalEnlistment.State.EnlistmentDone(_internalEnlistment);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
internal InternalEnlistment InternalEnlistment => _internalEnlistment;
}
}
| |
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Expressions.MSBuild;
using Microsoft.TemplateEngine.Core.Operations;
using Microsoft.TemplateEngine.Core.Util;
using Xunit;
namespace Microsoft.TemplateEngine.Core.UnitTests
{
public class InlineMarkupConditionalTests : TestBase
{
private IProcessor SetupXmlPlusMsBuildProcessor(IVariableCollection vc)
{
EngineConfig cfg = new EngineConfig(EnvironmentSettings, vc, "$({0})");
return Processor.Create(cfg, new InlineMarkupConditional(
new MarkupTokens("<".TokenConfig(), "</".TokenConfig(), ">".TokenConfig(), "/>".TokenConfig(), "Condition=\"".TokenConfig(), "\"".TokenConfig()),
true,
true,
MSBuildStyleEvaluatorDefinition.Evaluate,
"$({0})",
null,
true
));
}
private IProcessor SetupXmlPlusMsBuildProcessorAndReplacement(IVariableCollection vc)
{
EngineConfig cfg = new EngineConfig(EnvironmentSettings, vc, "$({0})");
return Processor.Create(cfg, new InlineMarkupConditional(
new MarkupTokens("<".TokenConfig(), "</".TokenConfig(), ">".TokenConfig(), "/>".TokenConfig(), "Condition=\"".TokenConfig(), "\"".TokenConfig()),
true,
true,
MSBuildStyleEvaluatorDefinition.Evaluate,
"$({0})",
null,
true
), new Replacement("ReplaceMe".TokenConfig(), "I've been replaced", null, true));
}
private IProcessor SetupXmlPlusMsBuildProcessorAndReplacementWithLookaround(IVariableCollection vc)
{
EngineConfig cfg = new EngineConfig(EnvironmentSettings, vc, "$({0})");
return Processor.Create(cfg, new InlineMarkupConditional(
new MarkupTokens("<".TokenConfig(), "</".TokenConfig(), ">".TokenConfig(), "/>".TokenConfig(), "Condition=\"".TokenConfig(), "\"".TokenConfig()),
true,
true,
MSBuildStyleEvaluatorDefinition.Evaluate,
"$({0})",
null,
true
), new Replacement("ReplaceMe".TokenConfigBuilder().OnlyIfAfter("Condition=\"Exists("), "I've been replaced", null, true));
}
[Fact(DisplayName = nameof(VerifyInlineMarkupTrue))]
public void VerifyInlineMarkupTrue()
{
string originalValue = @"<root>
<element Condition=""$(FIRST_IF)"" />
<element Condition=""$(SECOND_IF)"">
<child>
<grandchild />
</child>
</element>
</root>";
string expectedValue = @"<root>
<element />
<element>
<child>
<grandchild />
</child>
</element>
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = true,
["SECOND_IF"] = true
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupSelfClosedFalse))]
public void VerifyInlineMarkupSelfClosedFalse()
{
string originalValue = @"<root>
<element Condition=""$(FIRST_IF)"" />
<element Condition=""$(SECOND_IF)"">
<child>
<grandchild />
</child>
</element>
</root>";
string expectedValue = @"<root>
<element>
<child>
<grandchild />
</child>
</element>
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = false,
["SECOND_IF"] = true
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupElementWithChildrenFalse))]
public void VerifyInlineMarkupElementWithChildrenFalse()
{
string originalValue = @"<root>
<element Condition=""$(FIRST_IF)"" />
<element Condition=""$(SECOND_IF)"">
<child>
<grandchild />
</child>
</element>
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = true,
["SECOND_IF"] = false
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupFalse))]
public void VerifyInlineMarkupFalse()
{
string originalValue = @"<root>
<element Condition=""$(FIRST_IF)"" />
<element Condition=""$(SECOND_IF)"">
<child>
<grandchild />
</child>
</element>
</root>";
string expectedValue = @"<root>
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = false,
["SECOND_IF"] = false
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditions1))]
public void VerifyInlineMarkupExpandedConditions1()
{
string originalValue = @"<root>
<element Condition=""('$(FIRST_IF)' == '$(SECOND_IF)') AND !$(FIRST_IF)"" />
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = false,
["SECOND_IF"] = false
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditions2))]
public void VerifyInlineMarkupExpandedConditions2()
{
string originalValue = @"<root>
<element Condition=""!!!$(FIRST_IF) AND !$(SECOND_IF) == !$(FIRST_IF)"" />
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = false,
["SECOND_IF"] = false
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditionsEscaping))]
public void VerifyInlineMarkupExpandedConditionsEscaping()
{
string originalValue = @"<root>
<element Condition=""'$(FIRST_IF)' == '>< &' "'"" />
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = ">< &' \""
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditionsVersion))]
public void VerifyInlineMarkupExpandedConditionsVersion()
{
string originalValue = @"<root>
<element Condition=""'$(FIRST_IF)' == '1.2.3'"" />
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = "1.2.3"
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditionsUndefinedSymbolEmitsOriginal))]
public void VerifyInlineMarkupExpandedConditionsUndefinedSymbolEmitsOriginal()
{
string originalValue = @"<root>
<element Condition=""'$(FIRST_IF)' == '1.2.3'"" />
</root>";
string expectedValue = @"<root>
<element Condition=""'$(FIRST_IF)' == '1.2.3'"" />
</root>";
VariableCollection vc = new VariableCollection();
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999, true);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditionsUndefinedSymbolEmitsOriginal2))]
public void VerifyInlineMarkupExpandedConditionsUndefinedSymbolEmitsOriginal2()
{
string originalValue = @"<PaketExePath Condition="" '$(PaketExePath)' == '' "">$(PaketToolsPath)paket.exe</PaketExePath>";
string expectedValue = @"<PaketExePath Condition="" '$(PaketExePath)' == '' "">$(PaketToolsPath)paket.exe</PaketExePath>";
VariableCollection vc = new VariableCollection();
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999, true);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditionsNumerics))]
public void VerifyInlineMarkupExpandedConditionsNumerics()
{
string originalValue = @"<root>
<element Condition=""0x20 == '32'"" />
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["FIRST_IF"] = ">< &' \""
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupExpandedConditions3))]
public void VerifyInlineMarkupExpandedConditions3()
{
string originalValue = @"<root>
<element Condition=""'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"" />
</root>";
string expectedValue = @"<root>
<element />
</root>";
VariableCollection vc = new VariableCollection
{
["Configuration"] = "Debug",
["Platform"] = "AnyCPU"
};
IProcessor processor = SetupXmlPlusMsBuildProcessor(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
originalValue = @"<root>
<element Condition=""'$(Configuration)|$(Platform)' == 'debug|anycpu'"" />
</root>";
expectedValue = @"<root>
<element />
</root>";
RunAndVerify(originalValue, expectedValue, processor, 9999);
originalValue = @"<root>
<element Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'"" />
</root>";
expectedValue = @"<root>
</root>";
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupRejectGetsProcessed))]
public void VerifyInlineMarkupRejectGetsProcessed()
{
string originalValue = @"<root>
<element Condition=""Exists(ReplaceMe)"" />
</root>";
string expectedValue = @"<root>
<element Condition=""Exists(I've been replaced)"" />
</root>";
VariableCollection vc = new VariableCollection { };
IProcessor processor = SetupXmlPlusMsBuildProcessorAndReplacement(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
[Fact(DisplayName = nameof(VerifyInlineMarkupRejectGetsProcessedWithLookaround))]
public void VerifyInlineMarkupRejectGetsProcessedWithLookaround()
{
string originalValue = @"<root>
<element Condition=""Exists(ReplaceMe)"" />
</root>";
string expectedValue = @"<root>
<element Condition=""Exists(I've been replaced)"" />
</root>";
VariableCollection vc = new VariableCollection { };
IProcessor processor = SetupXmlPlusMsBuildProcessorAndReplacementWithLookaround(vc);
RunAndVerify(originalValue, expectedValue, processor, 9999);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>AdGroupCustomizer</c> resource.</summary>
public sealed partial class AdGroupCustomizerName : gax::IResourceName, sys::IEquatable<AdGroupCustomizerName>
{
/// <summary>The possible contents of <see cref="AdGroupCustomizerName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>.
/// </summary>
CustomerAdGroupCustomizerAttribute = 1,
}
private static gax::PathTemplate s_customerAdGroupCustomizerAttribute = new gax::PathTemplate("customers/{customer_id}/adGroupCustomizers/{ad_group_id_customizer_attribute_id}");
/// <summary>Creates a <see cref="AdGroupCustomizerName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdGroupCustomizerName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdGroupCustomizerName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdGroupCustomizerName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdGroupCustomizerName"/> with the pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>A new instance of <see cref="AdGroupCustomizerName"/> constructed from the provided ids.</returns>
public static AdGroupCustomizerName FromCustomerAdGroupCustomizerAttribute(string customerId, string adGroupId, string customizerAttributeId) =>
new AdGroupCustomizerName(ResourceNameType.CustomerAdGroupCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupCustomizerName"/> with pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="AdGroupCustomizerName"/> with pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string customizerAttributeId) =>
FormatCustomerAdGroupCustomizerAttribute(customerId, adGroupId, customizerAttributeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdGroupCustomizerName"/> with pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="AdGroupCustomizerName"/> with pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupCustomizerAttribute(string customerId, string adGroupId, string customizerAttributeId) =>
s_customerAdGroupCustomizerAttribute.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupCustomizerName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupCustomizerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdGroupCustomizerName"/> if successful.</returns>
public static AdGroupCustomizerName Parse(string adGroupCustomizerName) => Parse(adGroupCustomizerName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdGroupCustomizerName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupCustomizerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdGroupCustomizerName"/> if successful.</returns>
public static AdGroupCustomizerName Parse(string adGroupCustomizerName, bool allowUnparsed) =>
TryParse(adGroupCustomizerName, allowUnparsed, out AdGroupCustomizerName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupCustomizerName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adGroupCustomizerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupCustomizerName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupCustomizerName, out AdGroupCustomizerName result) =>
TryParse(adGroupCustomizerName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdGroupCustomizerName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adGroupCustomizerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdGroupCustomizerName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adGroupCustomizerName, bool allowUnparsed, out AdGroupCustomizerName result)
{
gax::GaxPreconditions.CheckNotNull(adGroupCustomizerName, nameof(adGroupCustomizerName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupCustomizerAttribute.TryParseName(adGroupCustomizerName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupCustomizerAttribute(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adGroupCustomizerName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdGroupCustomizerName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string customerId = null, string customizerAttributeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CustomerId = customerId;
CustomizerAttributeId = customizerAttributeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdGroupCustomizerName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adGroupCustomizers/{ad_group_id}~{customizer_attribute_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
public AdGroupCustomizerName(string customerId, string adGroupId, string customizerAttributeId) : this(ResourceNameType.CustomerAdGroupCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>CustomizerAttribute</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string CustomizerAttributeId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupCustomizerAttribute: return s_customerAdGroupCustomizerAttribute.Expand(CustomerId, $"{AdGroupId}~{CustomizerAttributeId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdGroupCustomizerName);
/// <inheritdoc/>
public bool Equals(AdGroupCustomizerName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdGroupCustomizerName a, AdGroupCustomizerName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdGroupCustomizerName a, AdGroupCustomizerName b) => !(a == b);
}
public partial class AdGroupCustomizer
{
/// <summary>
/// <see cref="AdGroupCustomizerName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdGroupCustomizerName ResourceNameAsAdGroupCustomizerName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupCustomizerName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CustomizerAttributeName"/>-typed view over the <see cref="CustomizerAttribute"/> resource name
/// property.
/// </summary>
internal CustomizerAttributeName CustomizerAttributeAsCustomizerAttributeName
{
get => string.IsNullOrEmpty(CustomizerAttribute) ? null : CustomizerAttributeName.Parse(CustomizerAttribute, allowUnparsed: true);
set => CustomizerAttribute = value?.ToString() ?? "";
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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 Bas Geertsema or Xih Solutions 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.IO;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
namespace MSNPSharp
{
using MSNPSharp.P2P;
using MSNPSharp.Apps;
using MSNPSharp.Core;
/// <summary>
/// Provides an easy interface for the client programmer.
/// </summary>
/// <remarks>
/// Messenger is an important class for the client programmer. It provides an easy interface to
/// communicate with the network. Messenger is a facade which hides all lower abstractions like message
/// processors, protocol handlers, etc. Messenger passes through events from underlying objects. This way
/// the client programmer can connect eventhandlers just once.
/// </remarks>
public class Messenger
{
#region Events
public event EventHandler<EventArgs> ConnectionEstablished;
protected virtual void OnConnectionEstablished(object sender, EventArgs e)
{
if (ConnectionEstablished != null)
ConnectionEstablished(sender, e);
}
public event EventHandler<EventArgs> ConnectionClosed;
protected virtual void OnConnectionClosed(object sender, EventArgs e)
{
if (ConnectionClosed != null)
ConnectionClosed(sender, e);
if (shouldReconnect)
DoConnect();
shouldReconnect = false;
}
public event EventHandler<ExceptionEventArgs> ConnectingException;
protected virtual void OnConnectingException(object sender, ExceptionEventArgs e)
{
if (ConnectingException != null)
ConnectingException(sender, e);
}
#endregion
#region Members
private ConnectivitySettings connectivitySettings = new ConnectivitySettings();
private NSMessageHandler nsMessageHandler = new NSMessageHandler();
private bool shouldReconnect = false;
/// <summary>
/// Basic constructor to instantiate a Messenger object.
/// </summary>
public Messenger()
{
// Inform us for Connected, Disconnected, ConnectingException events.
nsMessageHandler.MessageProcessorChanged += OnMessageProcessorChanged;
}
private void OnMessageProcessorChanged(object sender, MessageProcessorChangedEventArgs e)
{
if (e.OldProcessor != null)
{
e.OldProcessor.ConnectionEstablished -= OnConnectionEstablished;
e.OldProcessor.ConnectionClosed -= OnConnectionClosed;
e.OldProcessor.ConnectingException -= OnConnectingException;
}
if (e.NewProcessor != null)
{
e.NewProcessor.ConnectionEstablished += OnConnectionEstablished;
e.NewProcessor.ConnectionClosed += OnConnectionClosed;
e.NewProcessor.ConnectingException += OnConnectingException;
}
}
#endregion
#region Properties
/// <summary>
/// The message manager providing a simple way to send and receive messages.
/// </summary>
public MessageManager MessageManager
{
get
{
return Nameserver.MessageManager;
}
}
/// <summary>
/// Specifies the connection capabilities of the local machine.
/// </summary>
/// <remarks>
/// Use this property to set specific connectivity settings like proxy servers and custom messenger servers.
/// </remarks>
public ConnectivitySettings ConnectivitySettings
{
get
{
return connectivitySettings;
}
set
{
connectivitySettings = value;
NSMessageProcessor mp = Nameserver.MessageProcessor as NSMessageProcessor;
if (mp != null)
{
mp.ConnectivitySettings = ConnectivitySettings;
}
}
}
/// <summary>
/// The credentials which identify the messenger account and the client authentication.
/// </summary>
/// <remarks>
/// This property must be set before logging in the messenger service. <b>Both</b> the account
/// properties and the client identifier codes must be set. The first, the account, specifies the
/// account which represents the local user, for example 'account@hotmail.com'. The second, the
/// client codes, specifies how this client will authenticate itself against the messenger server.
/// See <see cref="Credentials"/> for more information about this.
/// </remarks>
public Credentials Credentials
{
get
{
return Nameserver.Credentials;
}
set
{
Nameserver.Credentials = value;
}
}
/// <summary>
/// The message handler that is used to handle incoming nameserver messages.
/// </summary>
public NSMessageHandler Nameserver
{
get
{
return nsMessageHandler;
}
}
/// <summary>
/// Returns whether there is a connection with the messenger server.
/// </summary>
public bool Connected
{
get
{
NSMessageProcessor mp = Nameserver.MessageProcessor as NSMessageProcessor;
return (mp != null && mp.Connected);
}
}
/// <summary>
/// A list of all contacts.
/// </summary>
public ContactList ContactList
{
get
{
return Nameserver.ContactList;
}
}
/// <summary>
/// A list of all contactgroups.
/// </summary>
public ContactGroupList ContactGroups
{
get
{
return Nameserver.ContactGroups;
}
}
/// <summary>
/// A collection of all circles which are defined by the user who logged into the messenger network.
/// </summary>
public Dictionary<string, Contact> CircleList
{
get
{
return Nameserver.CircleList;
}
}
/// <summary>
/// Storage service to get/update display name, personal status, display picture etc.
/// </summary>
public MSNStorageService StorageService
{
get
{
return Nameserver.StorageService;
}
}
/// <summary>
/// The ticket string to fetch msn objects from storage service.
/// </summary>
public string StorageTicket
{
get
{
string ticket = string.Empty;
if (Nameserver.MSNTicket != MSNTicket.Empty && Nameserver.MSNTicket.SSOTickets.ContainsKey(SSOTicketType.Storage))
{
ticket = Nameserver.MSNTicket.SSOTickets[SSOTicketType.Storage].Ticket.Substring(2);
}
return ticket;
}
}
/// <summary>
/// What's Up service
/// </summary>
public WhatsUpService WhatsUpService
{
get
{
return Nameserver.WhatsUpService;
}
}
/// <summary>
/// Directory Service
/// </summary>
public MSNDirectoryService DirectoryService
{
get
{
return Nameserver.DirectoryService;
}
}
/// <summary>
/// Contact service.
/// </summary>
public ContactService ContactService
{
get
{
return Nameserver.ContactService;
}
}
/// <summary>
/// The local user logged into the network. It will remain null until user successfully login.
/// You can register owner events after <see cref="NSMessageHandler.OwnerVerified"/> event.
/// </summary>
public Owner Owner
{
get
{
return Nameserver.Owner;
}
}
/// <summary>
/// The handler that manages all incoming/outgoing P2P framework messages.
/// </summary>
public P2PHandler P2PHandler
{
get
{
return Nameserver.P2PHandler;
}
}
#endregion
#region Methods
/// <summary>
/// Connects to the messenger network.
/// </summary>
public virtual void Connect()
{
if (Nameserver == null)
throw new MSNPSharpException("No message handler defined");
if (Credentials == null)
throw new MSNPSharpException("No credentials defined");
if (Credentials.Account.Length == 0)
throw new MSNPSharpException("The specified account is empty");
if (Credentials.Password.Length == 0)
throw new MSNPSharpException("The specified password is empty");
if (Credentials.ClientCode.Length == 0 || Credentials.ClientID.Length == 0)
throw new MSNPSharpException("The local messengerclient credentials (client-id and client code) are not specified. This is necessary in order to authenticate the local client with the messenger server. See for more info about the values to use the documentation of the Credentials class.");
if (Connected)
{
shouldReconnect = true;
Disconnect();
}
else
{
DoConnect();
}
}
private void DoConnect()
{
if (Settings.DisableHttpPolling)
ConnectivitySettings.HttpPoll = false;
NSMessageProcessor mp = new NSMessageProcessor(ConnectivitySettings);
Nameserver.MessageProcessor = mp;
mp.Connect();
}
/// <summary>
/// Disconnects from the messenger network.
/// </summary>
public virtual void Disconnect()
{
NSMessageProcessor mp = Nameserver.MessageProcessor as NSMessageProcessor;
if (mp != null && mp.Connected)
{
if (nsMessageHandler != null && nsMessageHandler.Owner != null)
{
nsMessageHandler.Owner.SetStatus(PresenceStatus.Offline);
}
mp.Disconnect();
}
}
/// <summary>
/// Requests <paramref name="msnObject"/> from <paramref name="remoteContact"/>.
/// </summary>
/// <param name="remoteContact"></param>
/// <param name="msnObject"></param>
/// <returns></returns>
public ObjectTransfer RequestMsnObject(Contact remoteContact, MSNObject msnObject)
{
return P2PHandler.RequestMsnObject(remoteContact, msnObject);
}
/// <summary>
/// Sends a file to the <paramref name="remoteContact"/>.
/// </summary>
/// <param name="remoteContact">Remote contact to be sent a file</param>
/// <param name="filename">File name</param>
/// <param name="fileStream">File stream</param>
/// <returns></returns>
public FileTransfer SendFile(Contact remoteContact, string filename, FileStream fileStream)
{
return P2PHandler.SendFile(remoteContact, filename, fileStream);
}
/// <summary>
/// Starts a new activity with <paramref name="remoteContact"/>.
/// </summary>
/// <param name="remoteContact"></param>
/// <param name="activityID">Activity ID</param>
/// <param name="activityName">Activity name</param>
/// <param name="activityData">Activity data</param>
/// <returns></returns>
public P2PActivity StartActivity(Contact remoteContact, uint activityID, string activityName, string activityData)
{
P2PActivity p2pActivity = new P2PActivity(remoteContact, activityID, activityName, activityData);
P2PHandler.AddTransfer(p2pActivity);
return p2pActivity;
}
public void SendTextMessage(Contact contact, string msg)
{
contact.SendMessage(new TextMessage(msg));
}
public void SendMobileMessage(Contact contact, string msg)
{
contact.SendMobileMessage(msg);
}
public void SendNudge(Contact contact)
{
contact.SendNudge();
}
public void SendTypingMessage(Contact contact)
{
contact.SendTypingMessage();
}
public void SendEmoticonDefinitions(Contact contact, List<Emoticon> emoticons, EmoticonType icontype)
{
contact.SendEmoticonDefinitions(emoticons, icontype);
}
#endregion
}
public class MessageProcessorChangedEventArgs : EventArgs
{
private NSMessageProcessor oldProcessor;
private NSMessageProcessor newProcessor;
public NSMessageProcessor OldProcessor
{
get
{
return oldProcessor;
}
}
public NSMessageProcessor NewProcessor
{
get
{
return newProcessor;
}
}
public MessageProcessorChangedEventArgs(NSMessageProcessor oldProcessor, NSMessageProcessor newProcessor)
{
this.oldProcessor = oldProcessor;
this.newProcessor = newProcessor;
}
};
};
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*
* Contains definition for PSSenderInfo, PSPrincipal, PSIdentity which are
* used to provide remote user information to different plugin snapins
* like Exchange.
*/
using System;
using System.Security.Principal;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using Microsoft.PowerShell;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This class is used in the server side remoting scenarios. This class
/// holds information about the incoming connection like:
/// (a) Client's TimeZone
/// (b) Connecting User information
/// (c) Connection String used by the user to connect to the server.
/// </summary>
[Serializable]
public sealed class PSSenderInfo : ISerializable
{
#region Private Data
private PSPrimitiveDictionary _applicationArguments;
#endregion
#region Serialization
/// <summary>
/// Serialization.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
PSObject psObject = PSObject.AsPSObject(this);
psObject.GetObjectData(info, context);
}
/// <summary>
/// Deserialization constructor.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
private PSSenderInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
return;
}
string serializedData = null;
try
{
serializedData = info.GetValue("CliXml", typeof(string)) as string;
}
catch (Exception)
{
// When a workflow is run locally, there won't be PSSenderInfo
return;
}
if (serializedData == null)
{
return;
}
try
{
PSObject result = PSObject.AsPSObject(PSSerializer.Deserialize(serializedData));
PSSenderInfo senderInfo = DeserializingTypeConverter.RehydratePSSenderInfo(result);
UserInfo = senderInfo.UserInfo;
ConnectionString = senderInfo.ConnectionString;
_applicationArguments = senderInfo._applicationArguments;
ClientTimeZone = senderInfo.ClientTimeZone;
}
catch (Exception)
{
// Ignore conversion errors
return;
}
}
#endregion
#region Public Constructors
/// <summary>
/// Constructs PSPrincipal using PSIdentity and a token (used to construct WindowsIdentity)
/// </summary>
/// <param name="userPrincipal">
/// Connecting User Information
/// </param>
/// <param name="httpUrl">
/// httpUrl element (from WSMAN_SENDER_DETAILS struct).
/// </param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")]
public PSSenderInfo(PSPrincipal userPrincipal, string httpUrl)
{
UserInfo = userPrincipal;
ConnectionString = httpUrl;
}
#endregion
#region Properties
/// <summary>
/// Contains information related to the user connecting to the server.
/// </summary>
public PSPrincipal UserInfo { get;
// No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's
// and usually they dont cache this data internally..so did not want to give
// cmdlets/scripts a chance to modify these.
}
/// <summary>
/// Contains the TimeZone information from the client machine.
/// </summary>
public TimeZoneInfo ClientTimeZone
{
get;
internal set;
}
/// <summary>
/// Connection string used by the client to connect to the server. This is
/// directly taken from WSMAN_SENDER_DETAILS struct (from wsman.h)
/// </summary>
public string ConnectionString { get;
// No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's
// and usually they dont cache this data internally..so did not want to give
// cmdlets/scripts a chance to modify these.
}
/// <summary>
/// Application arguments (i.e. specified in New-PSSessionOptions -ApplicationArguments)
/// </summary>
public PSPrimitiveDictionary ApplicationArguments
{
get { return _applicationArguments; }
internal set { _applicationArguments = value; }
}
/// <summary>
/// "ConfigurationName" from the sever remote session.
/// </summary>
public string ConfigurationName { get; internal set; }
#endregion
}
/// <summary>
/// Defines the basic functionality of a PSPrincipal object.
/// </summary>
public sealed class PSPrincipal : IPrincipal
{
#region Private Data
#endregion
/// <summary>
/// Gets the identity of the current user principal.
/// </summary>
public PSIdentity Identity { get;
// No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's
// and usually they dont cache this data internally..so did not want to give
// cmdlets/scripts a chance to modify these.
}
/// <summary>
/// Gets the WindowsIdentity (if possible) representation of the current Identity.
/// PSPrincipal can represent any user for example a LiveID user, network user within
/// a domain etc. This property tries to convert the Identity to WindowsIdentity
/// using the user token supplied.
/// </summary>
public WindowsIdentity WindowsIdentity { get;
// No public set because PSSenderInfo/PSPrincipal is used by PSSessionConfiguration's
// and usually they dont cache this data internally..so did not want to give
// cmdlets/scripts a chance to modify these.
}
/// <summary>
/// Gets the identity of the current principal.
/// </summary>
IIdentity IPrincipal.Identity
{
get { return this.Identity; }
}
/// <summary>
/// Determines if the current principal belongs to a specified rule.
/// If we were able to get a WindowsIdentity then this will perform the
/// check using the WindowsIdentity otherwise this will return false.
/// </summary>
/// <param name="role"></param>
/// <returns>
/// If we were able to get a WindowsIdentity then this will perform the
/// check using the WindowsIdentity otherwise this will return false.
/// </returns>
public bool IsInRole(string role)
{
if (WindowsIdentity != null)
{
// Get Windows Principal for this identity
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(WindowsIdentity);
return windowsPrincipal.IsInRole(role);
}
else
{
return false;
}
}
/// <summary>
/// Internal overload of IsInRole() taking a WindowsBuiltInRole enum value.
/// </summary>
internal bool IsInRole(WindowsBuiltInRole role)
{
if (WindowsIdentity != null)
{
// Get Windows Principal for this identity
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(WindowsIdentity);
return windowsPrincipal.IsInRole(role);
}
else
{
return false;
}
}
#region Constructor
/// <summary>
/// Constructs PSPrincipal using PSIdentity and a WindowsIdentity.
/// </summary>
/// <param name="identity">
/// An instance of PSIdentity
/// </param>
/// <param name="windowsIdentity">
/// An instance of WindowsIdentity, if psIdentity represents a windows user. This can be
/// null.
/// </param>
public PSPrincipal(PSIdentity identity, WindowsIdentity windowsIdentity)
{
Identity = identity;
WindowsIdentity = windowsIdentity;
}
#endregion
}
/// <summary>
/// Defines the basic functionality of a PSIdentity object.
/// </summary>
public sealed class PSIdentity : IIdentity
{
#region Private Data
#endregion
/// <summary>
/// Gets the type of authentication used.
/// For a WSMan service authenticated user this will be one of the following:
/// WSMAN_DEFAULT_AUTHENTICATION
/// WSMAN_NO_AUTHENTICATION
/// WSMAN_AUTH_DIGEST
/// WSMAN_AUTH_NEGOTIATE
/// WSMAN_AUTH_BASIC
/// WSMAN_AUTH_KERBEROS
/// WSMAN_AUTH_CLIENT_CERTIFICATE
/// WSMAN_AUTH_LIVEID.
/// </summary>
public string AuthenticationType { get; }
/// <summary>
/// Gets a value that indicates whether the user has been authenticated.
/// </summary>
public bool IsAuthenticated { get; }
/// <summary>
/// Gets the name of the user.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the certificate details of the user if supported, null otherwise.
/// </summary>
public PSCertificateDetails CertificateDetails { get; }
#region Public Constructor
/// <summary>
/// Constructor used to construct a PSIdentity object.
/// </summary>
/// <param name="authType">
/// Type of authentication used to authenticate this user.
/// For a WSMan service authenticated user this will be one of the following:
/// WSMAN_DEFAULT_AUTHENTICATION
/// WSMAN_NO_AUTHENTICATION
/// WSMAN_AUTH_DIGEST
/// WSMAN_AUTH_NEGOTIATE
/// WSMAN_AUTH_BASIC
/// WSMAN_AUTH_KERBEROS
/// WSMAN_AUTH_CLIENT_CERTIFICATE
/// WSMAN_AUTH_LIVEID
/// </param>
/// <param name="isAuthenticated">
/// true if this user is authenticated.
/// </param>
/// <param name="userName">
/// Name of the user
/// </param>
/// <param name="cert">
/// Certificate details if Certificate authentication is used.
/// </param>
public PSIdentity(string authType, bool isAuthenticated, string userName, PSCertificateDetails cert)
{
AuthenticationType = authType;
IsAuthenticated = isAuthenticated;
Name = userName;
CertificateDetails = cert;
}
#endregion
}
/// <summary>
/// Represents the certificate of a user.
/// </summary>
public sealed class PSCertificateDetails
{
#region Private Data
#endregion
/// <summary>
/// Gets Subject of the certificate.
/// </summary>
public string Subject { get; }
/// <summary>
/// Gets the issuer name of the certificate.
/// </summary>
public string IssuerName { get; }
/// <summary>
/// Gets the issuer thumb print.
/// </summary>
public string IssuerThumbprint { get; }
#region Constructor
/// <summary>
/// Constructor used to construct a PSCertificateDetails object.
/// </summary>
/// <param name="subject">
/// Subject of the certificate.
/// </param>
/// <param name="issuerName">
/// Issuer name of the certificate.
/// </param>
/// <param name="issuerThumbprint">
/// Issuer thumb print of the certificate.
/// </param>
public PSCertificateDetails(string subject, string issuerName, string issuerThumbprint)
{
Subject = subject;
IssuerName = issuerName;
IssuerThumbprint = issuerThumbprint;
}
#endregion
}
}
| |
namespace Microsoft.PythonTools.Options {
partial class PythonInteractiveOptionsControl {
/// <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();
this._smartReplHistory = new System.Windows.Forms.CheckBox();
this._completionModeGroup = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel();
this._evalNever = new System.Windows.Forms.RadioButton();
this._evalNoCalls = new System.Windows.Forms.RadioButton();
this._evalAlways = new System.Windows.Forms.RadioButton();
this._useUserDefinedPrompts = new System.Windows.Forms.CheckBox();
this._priPromptLabel = new System.Windows.Forms.Label();
this._priPrompt = new System.Windows.Forms.TextBox();
this._secPromptLabel = new System.Windows.Forms.Label();
this._secPrompt = new System.Windows.Forms.TextBox();
this._tooltips = new System.Windows.Forms.ToolTip(this.components);
this._startupScript = new System.Windows.Forms.TextBox();
this._startupScriptButton = new System.Windows.Forms.Button();
this._startScriptLabel = new System.Windows.Forms.Label();
this._showSettingsForLabel = new System.Windows.Forms.Label();
this._showSettingsFor = new System.Windows.Forms.ComboBox();
this._executionModeLabel = new System.Windows.Forms.Label();
this._executionMode = new System.Windows.Forms.ComboBox();
this._interpOptionsLabel = new System.Windows.Forms.Label();
this._interpreterOptions = new System.Windows.Forms.TextBox();
this._enableAttach = new System.Windows.Forms.CheckBox();
this._liveCompletionsOnly = new System.Windows.Forms.CheckBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this._completionModeGroup.SuspendLayout();
this.tableLayoutPanel5.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
this.SuspendLayout();
//
// _smartReplHistory
//
this._smartReplHistory.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._smartReplHistory.AutoSize = true;
this._smartReplHistory.Location = new System.Drawing.Point(6, 3);
this._smartReplHistory.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._smartReplHistory.Name = "_smartReplHistory";
this._smartReplHistory.Size = new System.Drawing.Size(160, 17);
this._smartReplHistory.TabIndex = 0;
this._smartReplHistory.Text = "Arrow Keys use smart &history";
this._smartReplHistory.UseVisualStyleBackColor = true;
this._smartReplHistory.CheckedChanged += new System.EventHandler(this._smartReplHistory_CheckedChanged);
//
// _completionModeGroup
//
this._completionModeGroup.AutoSize = true;
this._completionModeGroup.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._completionModeGroup.Controls.Add(this.tableLayoutPanel5);
this._completionModeGroup.Dock = System.Windows.Forms.DockStyle.Fill;
this._completionModeGroup.Location = new System.Drawing.Point(6, 171);
this._completionModeGroup.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8);
this._completionModeGroup.Name = "_completionModeGroup";
this._completionModeGroup.Padding = new System.Windows.Forms.Padding(6, 8, 6, 8);
this._completionModeGroup.Size = new System.Drawing.Size(479, 98);
this._completionModeGroup.TabIndex = 3;
this._completionModeGroup.TabStop = false;
this._completionModeGroup.Text = "Completion Mode";
//
// tableLayoutPanel5
//
this.tableLayoutPanel5.AutoSize = true;
this.tableLayoutPanel5.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel5.ColumnCount = 1;
this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel5.Controls.Add(this._evalNever, 0, 0);
this.tableLayoutPanel5.Controls.Add(this._evalNoCalls, 0, 1);
this.tableLayoutPanel5.Controls.Add(this._evalAlways, 0, 2);
this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel5.Location = new System.Drawing.Point(6, 21);
this.tableLayoutPanel5.Name = "tableLayoutPanel5";
this.tableLayoutPanel5.RowCount = 3;
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel5.Size = new System.Drawing.Size(467, 69);
this.tableLayoutPanel5.TabIndex = 0;
//
// _evalNever
//
this._evalNever.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._evalNever.AutoSize = true;
this._evalNever.Location = new System.Drawing.Point(6, 3);
this._evalNever.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._evalNever.Name = "_evalNever";
this._evalNever.Size = new System.Drawing.Size(156, 17);
this._evalNever.TabIndex = 0;
this._evalNever.TabStop = true;
this._evalNever.Text = "&Never evaluate expressions";
this._evalNever.UseVisualStyleBackColor = true;
//
// _evalNoCalls
//
this._evalNoCalls.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._evalNoCalls.AutoSize = true;
this._evalNoCalls.Location = new System.Drawing.Point(6, 26);
this._evalNoCalls.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._evalNoCalls.Name = "_evalNoCalls";
this._evalNoCalls.Size = new System.Drawing.Size(232, 17);
this._evalNoCalls.TabIndex = 1;
this._evalNoCalls.TabStop = true;
this._evalNoCalls.Text = "Never evaluate expressions containing &calls";
this._evalNoCalls.UseVisualStyleBackColor = true;
//
// _evalAlways
//
this._evalAlways.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._evalAlways.AutoSize = true;
this._evalAlways.Location = new System.Drawing.Point(6, 49);
this._evalAlways.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._evalAlways.Name = "_evalAlways";
this._evalAlways.Size = new System.Drawing.Size(160, 17);
this._evalAlways.TabIndex = 2;
this._evalAlways.TabStop = true;
this._evalAlways.Text = "&Always evaluate expressions";
this._evalAlways.UseVisualStyleBackColor = true;
//
// _useUserDefinedPrompts
//
this._useUserDefinedPrompts.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._useUserDefinedPrompts.AutoSize = true;
this._useUserDefinedPrompts.Location = new System.Drawing.Point(6, 26);
this._useUserDefinedPrompts.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._useUserDefinedPrompts.Name = "_useUserDefinedPrompts";
this._useUserDefinedPrompts.Size = new System.Drawing.Size(146, 17);
this._useUserDefinedPrompts.TabIndex = 2;
this._useUserDefinedPrompts.Text = "Use use&r defined prompts";
this._useUserDefinedPrompts.UseVisualStyleBackColor = true;
this._useUserDefinedPrompts.CheckedChanged += new System.EventHandler(this._useInterpreterPrompts_CheckedChanged);
//
// _priPromptLabel
//
this._priPromptLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._priPromptLabel.AutoEllipsis = true;
this._priPromptLabel.AutoSize = true;
this._priPromptLabel.Location = new System.Drawing.Point(20, 6);
this._priPromptLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._priPromptLabel.Name = "_priPromptLabel";
this._priPromptLabel.Size = new System.Drawing.Size(77, 13);
this._priPromptLabel.TabIndex = 0;
this._priPromptLabel.Text = "&Primary Prompt";
this._priPromptLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _priPrompt
//
this._priPrompt.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._priPrompt.Location = new System.Drawing.Point(109, 3);
this._priPrompt.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._priPrompt.MinimumSize = new System.Drawing.Size(40, 4);
this._priPrompt.Name = "_priPrompt";
this._priPrompt.Size = new System.Drawing.Size(118, 20);
this._priPrompt.TabIndex = 1;
this._priPrompt.TextChanged += new System.EventHandler(this._priPrompt_TextChanged);
//
// _secPromptLabel
//
this._secPromptLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._secPromptLabel.AutoEllipsis = true;
this._secPromptLabel.AutoSize = true;
this._secPromptLabel.Location = new System.Drawing.Point(239, 6);
this._secPromptLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._secPromptLabel.Name = "_secPromptLabel";
this._secPromptLabel.Size = new System.Drawing.Size(94, 13);
this._secPromptLabel.TabIndex = 2;
this._secPromptLabel.Text = "S&econdary Prompt";
this._secPromptLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _secPrompt
//
this._secPrompt.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._secPrompt.Location = new System.Drawing.Point(345, 3);
this._secPrompt.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._secPrompt.MinimumSize = new System.Drawing.Size(40, 4);
this._secPrompt.Name = "_secPrompt";
this._secPrompt.Size = new System.Drawing.Size(118, 20);
this._secPrompt.TabIndex = 3;
this._secPrompt.TextChanged += new System.EventHandler(this._secPrompt_TextChanged);
//
// _startupScript
//
this._startupScript.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel2.SetColumnSpan(this._startupScript, 3);
this._startupScript.Location = new System.Drawing.Point(115, 31);
this._startupScript.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._startupScript.Name = "_startupScript";
this._startupScript.Size = new System.Drawing.Size(326, 20);
this._startupScript.TabIndex = 3;
this._startupScript.TextChanged += new System.EventHandler(this._startupScript_TextChanged);
//
// _startupScriptButton
//
this._startupScriptButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this._startupScriptButton.AutoSize = true;
this._startupScriptButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._startupScriptButton.Location = new System.Drawing.Point(453, 30);
this._startupScriptButton.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._startupScriptButton.Name = "_startupScriptButton";
this._startupScriptButton.Size = new System.Drawing.Size(26, 23);
this._startupScriptButton.TabIndex = 4;
this._startupScriptButton.Text = "...";
this._startupScriptButton.UseVisualStyleBackColor = true;
this._startupScriptButton.Click += new System.EventHandler(this._startupScriptButton_Click);
//
// _startScriptLabel
//
this._startScriptLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._startScriptLabel.AutoEllipsis = true;
this._startScriptLabel.AutoSize = true;
this._startScriptLabel.Location = new System.Drawing.Point(6, 35);
this._startScriptLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._startScriptLabel.Name = "_startScriptLabel";
this._startScriptLabel.Size = new System.Drawing.Size(74, 13);
this._startScriptLabel.TabIndex = 2;
this._startScriptLabel.Text = "&Startup Script:";
this._startScriptLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _showSettingsForLabel
//
this._showSettingsForLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._showSettingsForLabel.AutoEllipsis = true;
this._showSettingsForLabel.AutoSize = true;
this._showSettingsForLabel.Location = new System.Drawing.Point(6, 7);
this._showSettingsForLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._showSettingsForLabel.Name = "_showSettingsForLabel";
this._showSettingsForLabel.Size = new System.Drawing.Size(96, 13);
this._showSettingsForLabel.TabIndex = 0;
this._showSettingsForLabel.Text = "Show Se&ttings For:";
this._showSettingsForLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _showSettingsFor
//
this._showSettingsFor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel2.SetColumnSpan(this._showSettingsFor, 4);
this._showSettingsFor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._showSettingsFor.FormattingEnabled = true;
this._showSettingsFor.Location = new System.Drawing.Point(115, 3);
this._showSettingsFor.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._showSettingsFor.Name = "_showSettingsFor";
this._showSettingsFor.Size = new System.Drawing.Size(364, 21);
this._showSettingsFor.TabIndex = 1;
this._showSettingsFor.SelectedIndexChanged += new System.EventHandler(this._showSettingsFor_SelectedIndexChanged);
this._showSettingsFor.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.Interpreter_Format);
//
// _executionModeLabel
//
this._executionModeLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._executionModeLabel.AutoEllipsis = true;
this._executionModeLabel.AutoSize = true;
this._executionModeLabel.Location = new System.Drawing.Point(233, 63);
this._executionModeLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._executionModeLabel.Name = "_executionModeLabel";
this._executionModeLabel.Size = new System.Drawing.Size(90, 13);
this._executionModeLabel.TabIndex = 7;
this._executionModeLabel.Text = "Interactive &Mode:";
this._executionModeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _executionMode
//
this._executionMode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel2.SetColumnSpan(this._executionMode, 2);
this._executionMode.DropDownWidth = 115;
this._executionMode.FormattingEnabled = true;
this._executionMode.Location = new System.Drawing.Point(335, 59);
this._executionMode.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._executionMode.Name = "_executionMode";
this._executionMode.Size = new System.Drawing.Size(144, 21);
this._executionMode.TabIndex = 8;
this._executionMode.SelectedIndexChanged += new System.EventHandler(this._executionMode_SelectedIndexChanged);
this._executionMode.TextChanged += new System.EventHandler(this._executionMode_TextChanged);
//
// _interpOptionsLabel
//
this._interpOptionsLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._interpOptionsLabel.AutoEllipsis = true;
this._interpOptionsLabel.AutoSize = true;
this._interpOptionsLabel.Location = new System.Drawing.Point(6, 63);
this._interpOptionsLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._interpOptionsLabel.Name = "_interpOptionsLabel";
this._interpOptionsLabel.Size = new System.Drawing.Size(97, 13);
this._interpOptionsLabel.TabIndex = 5;
this._interpOptionsLabel.Text = "Interpreter &Options:";
this._interpOptionsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _interpreterOptions
//
this._interpreterOptions.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._interpreterOptions.Location = new System.Drawing.Point(115, 59);
this._interpreterOptions.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._interpreterOptions.MinimumSize = new System.Drawing.Size(40, 4);
this._interpreterOptions.Name = "_interpreterOptions";
this._interpreterOptions.Size = new System.Drawing.Size(106, 20);
this._interpreterOptions.TabIndex = 6;
this._interpreterOptions.TextChanged += new System.EventHandler(this.InterpreterOptionsTextChanged);
//
// _enableAttach
//
this._enableAttach.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._enableAttach.AutoSize = true;
this._enableAttach.Location = new System.Drawing.Point(224, 3);
this._enableAttach.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._enableAttach.Name = "_enableAttach";
this._enableAttach.Size = new System.Drawing.Size(209, 17);
this._enableAttach.TabIndex = 1;
this._enableAttach.Text = "&Enable attaching to interactive window";
this._enableAttach.UseVisualStyleBackColor = true;
this._enableAttach.CheckedChanged += new System.EventHandler(this.EnableAttachCheckedChanged);
//
// _liveCompletionsOnly
//
this._liveCompletionsOnly.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._liveCompletionsOnly.AutoSize = true;
this._liveCompletionsOnly.Location = new System.Drawing.Point(224, 26);
this._liveCompletionsOnly.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._liveCompletionsOnly.Name = "_liveCompletionsOnly";
this._liveCompletionsOnly.Size = new System.Drawing.Size(145, 17);
this._liveCompletionsOnly.TabIndex = 3;
this._liveCompletionsOnly.Text = "Only use li&ve completions";
this._liveCompletionsOnly.UseVisualStyleBackColor = true;
this._liveCompletionsOnly.CheckedChanged += new System.EventHandler(this._liveCompletionsOnly_CheckedChanged);
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel3, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel4, 0, 2);
this.tableLayoutPanel1.Controls.Add(this._completionModeGroup, 0, 3);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 5;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(491, 315);
this.tableLayoutPanel1.TabIndex = 0;
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.AutoSize = true;
this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel2.ColumnCount = 5;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel2.Controls.Add(this._showSettingsForLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this._showSettingsFor, 1, 0);
this.tableLayoutPanel2.Controls.Add(this._startScriptLabel, 0, 1);
this.tableLayoutPanel2.Controls.Add(this._startupScript, 1, 1);
this.tableLayoutPanel2.Controls.Add(this._startupScriptButton, 4, 1);
this.tableLayoutPanel2.Controls.Add(this._interpOptionsLabel, 0, 2);
this.tableLayoutPanel2.Controls.Add(this._interpreterOptions, 1, 2);
this.tableLayoutPanel2.Controls.Add(this._executionModeLabel, 2, 2);
this.tableLayoutPanel2.Controls.Add(this._executionMode, 3, 2);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 4);
this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 3;
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());
this.tableLayoutPanel2.Size = new System.Drawing.Size(485, 83);
this.tableLayoutPanel2.TabIndex = 0;
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.AutoSize = true;
this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel3.ColumnCount = 2;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 45F));
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 55F));
this.tableLayoutPanel3.Controls.Add(this._smartReplHistory, 0, 0);
this.tableLayoutPanel3.Controls.Add(this._enableAttach, 1, 0);
this.tableLayoutPanel3.Controls.Add(this._liveCompletionsOnly, 1, 1);
this.tableLayoutPanel3.Controls.Add(this._useUserDefinedPrompts, 0, 1);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 91);
this.tableLayoutPanel3.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 2;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel3.Size = new System.Drawing.Size(485, 46);
this.tableLayoutPanel3.TabIndex = 1;
//
// tableLayoutPanel4
//
this.tableLayoutPanel4.AutoSize = true;
this.tableLayoutPanel4.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel4.ColumnCount = 6;
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 5F));
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 45F));
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 45F));
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 5F));
this.tableLayoutPanel4.Controls.Add(this._priPromptLabel, 1, 0);
this.tableLayoutPanel4.Controls.Add(this._priPrompt, 2, 0);
this.tableLayoutPanel4.Controls.Add(this._secPromptLabel, 3, 0);
this.tableLayoutPanel4.Controls.Add(this._secPrompt, 4, 0);
this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 137);
this.tableLayoutPanel4.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 1;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel4.Size = new System.Drawing.Size(485, 26);
this.tableLayoutPanel4.TabIndex = 2;
//
// PythonInteractiveOptionsControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8);
this.Name = "PythonInteractiveOptionsControl";
this.Size = new System.Drawing.Size(491, 315);
this._completionModeGroup.ResumeLayout(false);
this._completionModeGroup.PerformLayout();
this.tableLayoutPanel5.ResumeLayout(false);
this.tableLayoutPanel5.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.tableLayoutPanel4.ResumeLayout(false);
this.tableLayoutPanel4.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.CheckBox _smartReplHistory;
private System.Windows.Forms.GroupBox _completionModeGroup;
private System.Windows.Forms.RadioButton _evalAlways;
private System.Windows.Forms.RadioButton _evalNoCalls;
private System.Windows.Forms.RadioButton _evalNever;
private System.Windows.Forms.CheckBox _useUserDefinedPrompts;
private System.Windows.Forms.TextBox _secPrompt;
private System.Windows.Forms.TextBox _priPrompt;
private System.Windows.Forms.Label _secPromptLabel;
private System.Windows.Forms.Label _priPromptLabel;
private System.Windows.Forms.ToolTip _tooltips;
private System.Windows.Forms.TextBox _startupScript;
private System.Windows.Forms.Button _startupScriptButton;
private System.Windows.Forms.Label _startScriptLabel;
private System.Windows.Forms.Label _showSettingsForLabel;
private System.Windows.Forms.ComboBox _showSettingsFor;
private System.Windows.Forms.Label _executionModeLabel;
private System.Windows.Forms.ComboBox _executionMode;
private System.Windows.Forms.Label _interpOptionsLabel;
private System.Windows.Forms.TextBox _interpreterOptions;
private System.Windows.Forms.CheckBox _enableAttach;
private System.Windows.Forms.CheckBox _liveCompletionsOnly;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
}
}
| |
// 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.Management.Batch
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// BatchAccountOperations operations.
/// </summary>
public partial interface IBatchAccountOperations
{
/// <summary>
/// Creates a new Batch account with the specified parameters.
/// Existing accounts cannot be updated with this API and should
/// instead be updated with the Update Batch Account API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the new Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the
/// region. Batch account names must be between 3 and 24 characters
/// in length and must use only numbers and lowercase letters. This
/// name is used as part of the DNS name that is used to access the
/// Batch service in the region in which the account is created. For
/// example: http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates a new Batch account with the specified parameters.
/// Existing accounts cannot be updated with this API and should
/// instead be updated with the Update Batch Account API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the new Batch account.
/// </param>
/// <param name='accountName'>
/// A name for the Batch account which must be unique within the
/// region. Batch account names must be between 3 and 24 characters
/// in length and must use only numbers and lowercase letters. This
/// name is used as part of the DNS name that is used to access the
/// Batch service in the region in which the account is created. For
/// example: http://accountname.region.batch.azure.com/.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account creation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of an existing Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='parameters'>
/// Additional parameters for account update.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account to
/// be deleted.
/// </param>
/// <param name='accountName'>
/// The name of the account to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account to
/// be deleted.
/// </param>
/// <param name='accountName'>
/// The name of the account to be deleted.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the Batch accounts associated with the
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the Batch accounts associated within the
/// specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group whose Batch accounts to list.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Synchronizes access keys for the auto storage account configured
/// for the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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.AzureOperationResponse> SynchronizeAutoStorageKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Regenerates the specified account key for the specified Batch
/// account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='keyName'>
/// The type of account key to regenerate. Possible values include:
/// 'Primary', 'Secondary'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, AccountKeyType keyName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the account keys for the specified Batch account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the account.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccountKeys>> GetKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the Batch accounts associated with the
/// subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the Batch accounts associated within the
/// specified resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<BatchAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Linq;
using JetBrains.Annotations;
using NodaTime.Annotations;
using NodaTime.Extensions;
#if !PCL
using System;
using System.Collections.Generic;
using NodaTime.Utility;
namespace NodaTime.TimeZones
{
/// <summary>
/// Representation of a time zone converted from a <see cref="TimeZoneInfo"/> from the Base Class Library.
/// </summary>
/// <remarks>
/// <para>
/// Two instances of this class are deemed equal if and only if they refer to the exact same
/// <see cref="TimeZoneInfo"/> object.
/// </para>
/// <para>
/// This implementation does not always give the same results as <c>TimeZoneInfo</c>, in that it doesn't replicate
/// the bugs in the BCL interpretation of the data. These bugs are described in
/// <a href="http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/">a blog post</a>, but we're
/// not expecting them to be fixed any time soon. Being bug-for-bug compatible would not only be tricky, but would be painful
/// if the BCL were ever to be fixed. As far as we are aware, there are only discrepancies around new year where the zone
/// changes from observing one rule to observing another.
/// </para>
/// </remarks>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class BclDateTimeZone : DateTimeZone
{
/// <summary>
/// This is used to cache the last result of a call to <see cref="ForSystemDefault"/>, but it doesn't
/// matter if it's out of date - we'll just create another wrapper if necessary. It's not *that* expensive to make
/// a few more wrappers than we need.
/// </summary>
private static BclDateTimeZone systemDefault;
private readonly IZoneIntervalMap map;
/// <summary>
/// Gets the original <see cref="TimeZoneInfo"/> from which this was created.
/// </summary>
/// <value>The original <see cref="TimeZoneInfo"/> from which this was created.</value>
public TimeZoneInfo OriginalZone { get; }
/// <summary>
/// Gets the display name associated with the time zone, as provided by the Base Class Library.
/// </summary>
/// <value>The display name associated with the time zone, as provided by the Base Class Library.</value>
public string DisplayName => OriginalZone.DisplayName;
private BclDateTimeZone(TimeZoneInfo bclZone, Offset minOffset, Offset maxOffset, IZoneIntervalMap map)
: base(bclZone.Id, bclZone.SupportsDaylightSavingTime, minOffset, maxOffset)
{
this.OriginalZone = bclZone;
this.map = map;
}
/// <inheritdoc />
public override ZoneInterval GetZoneInterval(Instant instant)
{
return map.GetZoneInterval(instant);
}
/// <summary>
/// Creates a new <see cref="BclDateTimeZone" /> from a <see cref="TimeZoneInfo"/> from the Base Class Library.
/// </summary>
/// <param name="bclZone">The original time zone to take information from.</param>
/// <returns>A <see cref="BclDateTimeZone"/> wrapping the given <c>TimeZoneInfo</c>.</returns>
public static BclDateTimeZone FromTimeZoneInfo([NotNull] TimeZoneInfo bclZone)
{
Preconditions.CheckNotNull(bclZone, nameof(bclZone));
Offset standardOffset = bclZone.BaseUtcOffset.ToOffset();
var rules = bclZone.GetAdjustmentRules();
if (!bclZone.SupportsDaylightSavingTime || rules.Length == 0)
{
var fixedInterval = new ZoneInterval(bclZone.StandardName, Instant.BeforeMinValue, Instant.AfterMaxValue, standardOffset, Offset.Zero);
return new BclDateTimeZone(bclZone, standardOffset, standardOffset, new SingleZoneIntervalMap(fixedInterval));
}
BclAdjustmentRule[] convertedRules = Array.ConvertAll(rules, rule => new BclAdjustmentRule(bclZone, rule));
Offset minRuleOffset = convertedRules.Aggregate(Offset.MaxValue, (min, rule) => Offset.Min(min, rule.Savings + rule.StandardOffset));
Offset maxRuleOffset = convertedRules.Aggregate(Offset.MinValue, (min, rule) => Offset.Max(min, rule.Savings + rule.StandardOffset));
IZoneIntervalMap uncachedMap = BuildMap(convertedRules, standardOffset, bclZone.StandardName);
IZoneIntervalMap cachedMap = CachingZoneIntervalMap.CacheMap(uncachedMap, CachingZoneIntervalMap.CacheType.Hashtable);
return new BclDateTimeZone(bclZone, Offset.Min(standardOffset, minRuleOffset), Offset.Max(standardOffset, maxRuleOffset), cachedMap);
}
private static IZoneIntervalMap BuildMap(BclAdjustmentRule[] rules, Offset standardOffset, [NotNull] string standardName)
{
Preconditions.CheckNotNull(standardName, nameof(standardName));
// First work out a naive list of partial maps. These will give the right offset at every instant, but not necessarily
// correct intervals - we may we need to stitch intervals together.
List<PartialZoneIntervalMap> maps = new List<PartialZoneIntervalMap>();
// Handle the start of time until the start of the first rule, if necessary.
if (rules[0].Start.IsValid)
{
maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, Instant.BeforeMinValue, rules[0].Start, standardOffset, Offset.Zero));
}
for (int i = 0; i < rules.Length - 1; i++)
{
var beforeRule = rules[i];
var afterRule = rules[i + 1];
maps.Add(beforeRule.PartialMap);
// If there's a gap between this rule and the next one, fill it with a fixed interval.
if (beforeRule.End < afterRule.Start)
{
maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, beforeRule.End, afterRule.Start, standardOffset, Offset.Zero));
}
}
var lastRule = rules[rules.Length - 1];
maps.Add(lastRule.PartialMap);
// Handle the end of the last rule until the end of time, if necessary.
if (lastRule.End.IsValid)
{
maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, lastRule.End, Instant.AfterMaxValue, standardOffset, Offset.Zero));
}
return PartialZoneIntervalMap.ConvertToFullMap(maps);
}
/// <summary>
/// Just a mapping of a TimeZoneInfo.AdjustmentRule into Noda Time types. Very little cleverness here.
/// </summary>
private sealed class BclAdjustmentRule
{
private static readonly DateTime MaxDate = DateTime.MaxValue.Date;
/// <summary>
/// Instant on which this rule starts.
/// </summary>
internal Instant Start { get; }
/// <summary>
/// Instant on which this rule ends.
/// </summary>
internal Instant End { get; }
/// <summary>
/// Daylight savings, when applicable within this rule.
/// </summary>
internal Offset Savings { get; }
/// <summary>
/// The standard offset for the duration of this rule.
/// </summary>
internal Offset StandardOffset { get; }
internal PartialZoneIntervalMap PartialMap { get; }
internal BclAdjustmentRule(TimeZoneInfo zone, TimeZoneInfo.AdjustmentRule rule)
{
// With .NET 4.6, adjustment rules can have their own standard offsets, allowing
// a much more reasonable set of time zone data. Unfortunately, this isn't directly
// exposed, but we can detect it by just finding the UTC offset for an arbitrary
// time within the rule - the start, in this case - and then take account of the
// possibility of that being in daylight saving time. Fortunately, we only need
// to do this during the setup.
var ruleStandardOffset = zone.GetUtcOffset(rule.DateStart);
if (zone.IsDaylightSavingTime(rule.DateStart))
{
ruleStandardOffset -= rule.DaylightDelta;
}
StandardOffset = ruleStandardOffset.ToOffset();
// Although the rule may have its own standard offset, the start/end is still determined
// using the zone's standard offset.
var zoneStandardOffset = zone.BaseUtcOffset.ToOffset();
// Note: this extends back from DateTime.MinValue to start of time, even though the BCL can represent
// as far back as 1AD. This is in the *spirit* of a rule which goes back that far.
Start = rule.DateStart == DateTime.MinValue ? Instant.BeforeMinValue : rule.DateStart.ToLocalDateTime().WithOffset(zoneStandardOffset).ToInstant();
// The end instant (exclusive) is the end of the given date, so we need to add a day.
End = rule.DateEnd == MaxDate ? Instant.AfterMaxValue : rule.DateEnd.ToLocalDateTime().PlusDays(1).WithOffset(zoneStandardOffset).ToInstant();
Savings = rule.DaylightDelta.ToOffset();
// Some rules have DST start/end of "January 1st", to indicate that they're just in standard time. This is important
// for rules which have a standard offset which is different to the standard offset of the zone itself.
if (IsStandardOffsetOnlyRule(rule))
{
PartialMap = PartialZoneIntervalMap.ForZoneInterval(zone.StandardName, Start, End, StandardOffset, Offset.Zero);
}
else
{
var daylightRecurrence = new ZoneRecurrence(zone.DaylightName, Savings, ConvertTransition(rule.DaylightTransitionStart), int.MinValue, int.MaxValue);
var standardRecurrence = new ZoneRecurrence(zone.StandardName, Offset.Zero, ConvertTransition(rule.DaylightTransitionEnd), int.MinValue, int.MaxValue);
var recurringMap = new DaylightSavingsDateTimeZone("ignored", StandardOffset, standardRecurrence, daylightRecurrence);
PartialMap = new PartialZoneIntervalMap(Start, End, recurringMap);
}
}
/// <summary>
/// The BCL represents "standard-only" rules using two fixed date January 1st transitions.
/// Currently the time-of-day used for the DST end transition is at one millisecond past midnight... we'll
/// be slightly more lenient, accepting anything up to 12:01...
/// </summary>
private static bool IsStandardOffsetOnlyRule(TimeZoneInfo.AdjustmentRule rule)
{
var daylight = rule.DaylightTransitionStart;
var standard = rule.DaylightTransitionEnd;
return daylight.IsFixedDateRule && daylight.Day == 1 && daylight.Month == 1 &&
daylight.TimeOfDay.TimeOfDay < TimeSpan.FromMinutes(1) &&
standard.IsFixedDateRule && standard.Day == 1 && standard.Month == 1 &&
standard.TimeOfDay.TimeOfDay < TimeSpan.FromMinutes(1);
}
// Converts a TimeZoneInfo "TransitionTime" to a "ZoneYearOffset" - the two correspond pretty closely.
private static ZoneYearOffset ConvertTransition(TimeZoneInfo.TransitionTime transitionTime)
{
// Used for both fixed and non-fixed transitions.
LocalTime timeOfDay = LocalDateTime.FromDateTime(transitionTime.TimeOfDay).TimeOfDay;
// Easy case - fixed day of the month.
if (transitionTime.IsFixedDateRule)
{
return new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, transitionTime.Day, 0, false, timeOfDay);
}
// Floating: 1st Sunday in March etc.
int dayOfWeek = (int)BclConversions.ToIsoDayOfWeek(transitionTime.DayOfWeek);
int dayOfMonth;
bool advance;
// "Last"
if (transitionTime.Week == 5)
{
advance = false;
dayOfMonth = -1;
}
else
{
advance = true;
// Week 1 corresponds to ">=1"
// Week 2 corresponds to ">=8" etc
dayOfMonth = (transitionTime.Week * 7) - 6;
}
return new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, dayOfMonth, dayOfWeek, advance, timeOfDay);
}
}
/// <summary>
/// Returns a time zone converted from the BCL representation of the system local time zone.
/// </summary>
/// <remarks>
/// <para>
/// This method is approximately equivalent to calling <see cref="IDateTimeZoneProvider.GetSystemDefault"/> with
/// an implementation that wraps <see cref="BclDateTimeZoneSource"/> (e.g.
/// <see cref="DateTimeZoneProviders.Bcl"/>), with the exception that it will succeed even if the current local
/// time zone was not one of the set of system time zones captured when the source was created (which, while
/// highly unlikely, might occur either because the local time zone is not a system time zone, or because the
/// system time zones have themselves changed).
/// </para>
/// <para>
/// This method will retain a reference to the returned <c>BclDateTimeZone</c>, and will attempt to return it if
/// called repeatedly (assuming that the local time zone has not changed) rather than creating a new instance,
/// though this behaviour is not guaranteed.
/// </para>
/// </remarks>
/// <returns>A <see cref="BclDateTimeZone"/> wrapping the "local" (system) time zone as returned by
/// <see cref="TimeZoneInfo.Local"/>.</returns>
public static BclDateTimeZone ForSystemDefault()
{
TimeZoneInfo local = TimeZoneInfo.Local;
BclDateTimeZone currentSystemDefault = systemDefault;
// Cached copy is out of date - wrap a new one
if (currentSystemDefault?.OriginalZone != local)
{
currentSystemDefault = FromTimeZoneInfo(local);
systemDefault = currentSystemDefault;
}
// Always return our local variable; the variable may have changed again.
return currentSystemDefault;
}
/// <inheritdoc />
/// <remarks>
/// This implementation simply compares the underlying `TimeZoneInfo` values for
/// reference equality.
/// </remarks>
protected override bool EqualsImpl(DateTimeZone zone)
{
return ReferenceEquals(OriginalZone, ((BclDateTimeZone) zone).OriginalZone);
}
/// <inheritdoc />
public override int GetHashCode() => OriginalZone.GetHashCode();
}
}
#endif
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WeifenLuo.WinFormsUI.Docking
{
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/ClassDef/*'/>
internal class VS2003AutoHideStrip : AutoHideStripBase
{
private class TabVS2003 : Tab
{
internal TabVS2003(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
protected internal int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
protected internal int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 16;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 4;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 4;
private const int _TextGapRight = 10;
private const int _TabGapTop = 3;
private const int _TabGapLeft = 2;
private const int _TabGapBetween = 10;
private static Matrix _matrixIdentity;
private static DockState[] _dockStates;
#region Customizable Properties
private static StringFormat _stringFormatTabHorizontal = null;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabHorizontal"]/*'/>
protected virtual StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
}
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="StringFormatTabVertical"]/*'/>
protected virtual StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
}
return _stringFormatTabVertical;
}
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageHeight"]/*'/>
protected virtual int ImageHeight
{
get { return _ImageHeight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageWidth"]/*'/>
protected virtual int ImageWidth
{
get { return _ImageWidth; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapTop"]/*'/>
protected virtual int ImageGapTop
{
get { return _ImageGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapLeft"]/*'/>
protected virtual int ImageGapLeft
{
get { return _ImageGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapRight"]/*'/>
protected virtual int ImageGapRight
{
get { return _ImageGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="ImageGapBottom"]/*'/>
protected virtual int ImageGapBottom
{
get { return _ImageGapBottom; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapLeft"]/*'/>
protected virtual int TextGapLeft
{
get { return _TextGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TextGapRight"]/*'/>
protected virtual int TextGapRight
{
get { return _TextGapRight; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapTop"]/*'/>
protected virtual int TabGapTop
{
get { return _TabGapTop; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapLeft"]/*'/>
protected virtual int TabGapLeft
{
get { return _TabGapLeft; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="TabGapBetween"]/*'/>
protected virtual int TabGapBetween
{
get { return _TabGapBetween; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabBackground"]/*'/>
protected virtual Brush BrushTabBackground
{
get { return SystemBrushes.Control; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="PenTabBorder"]/*'/>
protected virtual Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Property[@name="BrushTabText"]/*'/>
protected virtual Brush BrushTabText
{
get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); }
}
#endregion
private Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private DockState[] DockStates
{
get { return _dockStates; }
}
static VS2003AutoHideStrip()
{
_matrixIdentity = new Matrix();
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
public VS2003AutoHideStrip(DockPanel panel) : base(panel)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
BackColor = Color.WhiteSmoke;
}
/// <exclude/>
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
DrawTabStrip(g);
}
/// <exclude/>
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout (levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2003 tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
using (Graphics g = CreateGraphics())
{
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
int maxWidth = 0;
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
(int)g.MeasureString(tab.Content.DockHandler.TabText, Font).Width + 1 +
TextGapLeft + TextGapRight;
if (width > maxWidth)
maxWidth = width;
}
foreach (TabVS2003 tab in pane.AutoHideTabs)
{
tab.TabX = x;
if (tab.Content == pane.DockPane.ActiveContent)
tab.TabWidth = maxWidth;
else
tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight;
x += tab.TabWidth;
}
x += TabGapBetween;
}
}
}
private void DrawTab(Graphics g, TabVS2003 tab)
{
Rectangle rectTab = GetTabRectangle(tab);
if (rectTab.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
OnBeginDrawTab(tab);
Brush brushTabBackGround = BrushTabBackground;
Pen penTabBorder = PenTabBorder;
Brush brushTabText = BrushTabText;
g.FillRectangle(brushTabBackGround, rectTab);
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Left, rectTab.Bottom);
g.DrawLine(penTabBorder, rectTab.Right, rectTab.Top, rectTab.Right, rectTab.Bottom);
if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
else
g.DrawLine(penTabBorder, rectTab.Left, rectTab.Top, rectTab.Right, rectTab.Top);
// Set no rotate for drawing icon and text
Matrix matrixRotate = g.Transform;
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTab;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTab.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight/ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
g.DrawIcon(((Form)content).Icon, rectImage);
// Draw the text
if (content == content.DockHandler.Pane.ActiveContent)
{
Rectangle rectText = rectTab;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = GetTransformedRectangle(dockState, rectText);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal);
}
// Set rotate back
g.Transform = matrixRotate;
OnEndDrawTab(tab);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2003 tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2003 tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
using (Matrix matrix = new Matrix())
{
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
}
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
/// <exclude />
protected override IDockContent HitTest(Point ptMouse)
{
foreach(DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach(Pane pane in GetPanes(state))
{
foreach(TabVS2003 tab in pane.AutoHideTabs)
{
Rectangle rectTab = GetTabRectangle(tab, true);
rectTab.Intersect(rectTabStrip);
if (rectTab.Contains(ptMouse))
return tab.Content;
}
}
}
return null;
}
/// <exclude/>
protected internal override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
Font.Height) + TabGapTop;
}
/// <exclude/>
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2003(content);
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnBeginDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnBeginDrawTab(Tab tab)
{
}
/// <include file='CodeDoc/AutoHideStripVS2003.xml' path='//CodeDoc/Class[@name="AutoHideStripVS2003"]/Method[@name="OnEndDrawTab(AutoHideTab)"]/*'/>
protected virtual void OnEndDrawTab(Tab tab)
{
}
}
}
| |
using System.Diagnostics;
namespace YAF.Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext;
/// <summary>
/// A <see cref="ICollector"/> implementation that collects the top-scoring hits,
/// returning them as a <see cref="TopDocs"/>. this is used by <see cref="IndexSearcher"/> to
/// implement <see cref="TopDocs"/>-based search. Hits are sorted by score descending
/// and then (when the scores are tied) docID ascending. When you create an
/// instance of this collector you should know in advance whether documents are
/// going to be collected in doc Id order or not.
///
/// <para/><b>NOTE</b>: The values <see cref="float.NaN"/> and
/// <see cref="float.NegativeInfinity"/> are not valid scores. This
/// collector will not properly collect hits with such
/// scores.
/// </summary>
public abstract class TopScoreDocCollector : TopDocsCollector<ScoreDoc>
{
// Assumes docs are scored in order.
private class InOrderTopScoreDocCollector : TopScoreDocCollector
{
internal InOrderTopScoreDocCollector(int numHits)
: base(numHits)
{
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle these scores:
Debug.Assert(score != float.NegativeInfinity);
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score <= pqTop.Score)
{
// Since docs are returned in-order (i.e., increasing doc Id), a document
// with equal score to pqTop.score cannot compete since HitQueue favors
// documents with lower doc Ids. Therefore reject those docs too.
return;
}
pqTop.Doc = doc + docBase;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder
{
get { return false; }
}
}
// Assumes docs are scored in order.
private class InOrderPagingScoreDocCollector : TopScoreDocCollector
{
internal readonly ScoreDoc after;
// this is always after.doc - docBase, to save an add when score == after.score
internal int afterDoc;
internal int collectedHits;
internal InOrderPagingScoreDocCollector(ScoreDoc after, int numHits)
: base(numHits)
{
this.after = after;
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle these scores:
Debug.Assert(score != float.NegativeInfinity);
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score > after.Score || (score == after.Score && doc <= afterDoc))
{
// hit was collected on a previous page
return;
}
if (score <= pqTop.Score)
{
// Since docs are returned in-order (i.e., increasing doc Id), a document
// with equal score to pqTop.score cannot compete since HitQueue favors
// documents with lower doc Ids. Therefore reject those docs too.
return;
}
collectedHits++;
pqTop.Doc = doc + docBase;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder
{
get { return false; }
}
public override void SetNextReader(AtomicReaderContext context)
{
base.SetNextReader(context);
afterDoc = after.Doc - docBase;
}
protected override int TopDocsCount
{
get { return collectedHits < m_pq.Count ? collectedHits : m_pq.Count; }
}
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
return results == null ? new TopDocs(m_totalHits, new ScoreDoc[0], float.NaN) : new TopDocs(m_totalHits, results);
}
}
// Assumes docs are scored out of order.
private class OutOfOrderTopScoreDocCollector : TopScoreDocCollector
{
internal OutOfOrderTopScoreDocCollector(int numHits)
: base(numHits)
{
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle NaN
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score < pqTop.Score)
{
// Doesn't compete w/ bottom entry in queue
return;
}
doc += docBase;
if (score == pqTop.Score && doc > pqTop.Doc)
{
// Break tie in score by doc ID:
return;
}
pqTop.Doc = doc;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder
{
get { return true; }
}
}
// Assumes docs are scored out of order.
private class OutOfOrderPagingScoreDocCollector : TopScoreDocCollector
{
internal readonly ScoreDoc after;
// this is always after.doc - docBase, to save an add when score == after.score
internal int afterDoc;
internal int collectedHits;
internal OutOfOrderPagingScoreDocCollector(ScoreDoc after, int numHits)
: base(numHits)
{
this.after = after;
}
public override void Collect(int doc)
{
float score = scorer.GetScore();
// this collector cannot handle NaN
Debug.Assert(!float.IsNaN(score));
m_totalHits++;
if (score > after.Score || (score == after.Score && doc <= afterDoc))
{
// hit was collected on a previous page
return;
}
if (score < pqTop.Score)
{
// Doesn't compete w/ bottom entry in queue
return;
}
doc += docBase;
if (score == pqTop.Score && doc > pqTop.Doc)
{
// Break tie in score by doc ID:
return;
}
collectedHits++;
pqTop.Doc = doc;
pqTop.Score = score;
pqTop = m_pq.UpdateTop();
}
public override bool AcceptsDocsOutOfOrder
{
get { return true; }
}
public override void SetNextReader(AtomicReaderContext context)
{
base.SetNextReader(context);
afterDoc = after.Doc - docBase;
}
protected override int TopDocsCount
{
get { return collectedHits < m_pq.Count ? collectedHits : m_pq.Count; }
}
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
return results == null ? new TopDocs(m_totalHits, new ScoreDoc[0], float.NaN) : new TopDocs(m_totalHits, results);
}
}
/// <summary>
/// Creates a new <see cref="TopScoreDocCollector"/> given the number of hits to
/// collect and whether documents are scored in order by the input
/// <see cref="Scorer"/> to <see cref="SetScorer(Scorer)"/>.
///
/// <para/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length
/// <paramref name="numHits"/>, and fill the array with sentinel
/// objects.
/// </summary>
public static TopScoreDocCollector Create(int numHits, bool docsScoredInOrder)
{
return Create(numHits, null, docsScoredInOrder);
}
/// <summary>
/// Creates a new <see cref="TopScoreDocCollector"/> given the number of hits to
/// collect, the bottom of the previous page, and whether documents are scored in order by the input
/// <see cref="Scorer"/> to <see cref="SetScorer(Scorer)"/>.
///
/// <para/><b>NOTE</b>: The instances returned by this method
/// pre-allocate a full array of length
/// <paramref name="numHits"/>, and fill the array with sentinel
/// objects.
/// </summary>
public static TopScoreDocCollector Create(int numHits, ScoreDoc after, bool docsScoredInOrder)
{
if (numHits <= 0)
{
throw new System.ArgumentException("numHits must be > 0; please use TotalHitCountCollector if you just need the total hit count");
}
if (docsScoredInOrder)
{
return after == null ? (TopScoreDocCollector)new InOrderTopScoreDocCollector(numHits) : new InOrderPagingScoreDocCollector(after, numHits);
}
else
{
return after == null ? (TopScoreDocCollector)new OutOfOrderTopScoreDocCollector(numHits) : new OutOfOrderPagingScoreDocCollector(after, numHits);
}
}
internal ScoreDoc pqTop;
internal int docBase = 0;
internal Scorer scorer;
// prevents instantiation
private TopScoreDocCollector(int numHits)
: base(new HitQueue(numHits, true))
{
// HitQueue implements getSentinelObject to return a ScoreDoc, so we know
// that at this point top() is already initialized.
pqTop = m_pq.Top;
}
protected override TopDocs NewTopDocs(ScoreDoc[] results, int start)
{
if (results == null)
{
return EMPTY_TOPDOCS;
}
// We need to compute maxScore in order to set it in TopDocs. If start == 0,
// it means the largest element is already in results, use its score as
// maxScore. Otherwise pop everything else, until the largest element is
// extracted and use its score as maxScore.
float maxScore = float.NaN;
if (start == 0)
{
maxScore = results[0].Score;
}
else
{
for (int i = m_pq.Count; i > 1; i--)
{
m_pq.Pop();
}
maxScore = m_pq.Pop().Score;
}
return new TopDocs(m_totalHits, results, maxScore);
}
public override void SetNextReader(AtomicReaderContext context)
{
docBase = context.DocBase;
}
public override void SetScorer(Scorer scorer)
{
this.scorer = scorer;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndInt64()
{
var test = new SimpleBinaryOpTest__AndInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndInt64
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data1 = new Int64[ElementCount];
private static Int64[] _data2 = new Int64[ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector128<Int64> _fld1;
private Vector128<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64> _dataTable;
static SimpleBinaryOpTest__AndInt64()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.And(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.And(
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.And(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndInt64();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[ElementCount];
Int64[] inArray2 = new Int64[ElementCount];
Int64[] outArray = new Int64[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
if ((long)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((long)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.And)}<Int64>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
namespace Microsoft.VisualStudio.Services.Agent
{
public enum RunMode
{
Normal, // Keep "Normal" first (default value).
Local,
}
public enum WellKnownDirectory
{
Bin,
Diag,
Externals,
LegacyPSHost,
Root,
ServerOM,
Tee,
Tasks,
Update,
Work,
}
public static class Constants
{
/// <summary>Path environment varible name.</summary>
#if OS_WINDOWS
public static readonly string PathVariable = "Path";
#else
public static readonly string PathVariable = "PATH";
#endif
public static string SecretMask = "********";
public static string TFBuild = "TF_BUILD";
// This enum is embedded within the Constants class to make it easier to reference and avoid
// ambiguous type reference with System.Runtime.InteropServices.OSPlatform.
public enum OSPlatform
{
OSX,
Linux,
Windows
}
public static class Agent
{
public static readonly string Version = "2.120.0";
#if OS_LINUX
public static readonly OSPlatform Platform = OSPlatform.Linux;
#elif OS_OSX
public static readonly OSPlatform Platform = OSPlatform.OSX;
#elif OS_WINDOWS
public static readonly OSPlatform Platform = OSPlatform.Windows;
#endif
public static readonly TimeSpan ExitOnUnloadTimeout = TimeSpan.FromSeconds(30);
public static class CommandLine
{
//if you are adding a new arg, please make sure you update the
//validArgs array as well present in the CommandSettings.cs
public static class Args
{
public static readonly string Agent = "agent";
public static readonly string Auth = "auth";
public static readonly string NotificationPipeName = "notificationpipename";
public static readonly string NotificationSocketAddress = "notificationsocketaddress";
public static readonly string Pool = "pool";
public static readonly string Url = "url";
public static readonly string UserName = "username";
public static readonly string WindowsLogonAccount = "windowslogonaccount";
public static readonly string Work = "work";
public static readonly string MachineGroupName = "machinegroupname";
public static readonly string DeploymentGroupName = "deploymentgroupname";
public static readonly string ProjectName = "projectname";
public static readonly string CollectionName = "collectionname";
public static readonly string MachineGroupTags = "machinegrouptags";
public static readonly string DeploymentGroupTags = "deploymentgrouptags";
public static readonly string Yaml = "yaml";
// Secret args. Must be added to the "Secrets" getter as well.
public static readonly string Password = "password";
public static readonly string Token = "token";
public static readonly string WindowsLogonPassword = "windowslogonpassword";
public static readonly string StartupType = "startuptype";
public static string[] Secrets => new[]
{
Password,
Token,
WindowsLogonPassword,
};
}
public static class Commands
{
public static readonly string Configure = "configure";
public static readonly string Run = "run";
public static readonly string Unconfigure = "remove";
}
//if you are adding a new flag, please make sure you update the
//validFlags array as well present in the CommandSettings.cs
public static class Flags
{
public static readonly string AcceptTeeEula = "acceptteeeula";
public static readonly string AddDeploymentGroupTags = "adddeploymentgrouptags";
public static readonly string AddMachineGroupTags = "addmachinegrouptags";
public static readonly string Commit = "commit";
public static readonly string DeploymentGroup = "deploymentgroup";
public static readonly string EnableAutoLogon = "enableautologon";
public static readonly string OverwriteAutoLogonSettings = "overwriteautologonsettings";
public static readonly string Help = "help";
public static readonly string MachineGroup = "machinegroup";
public static readonly string Replace = "replace";
public static readonly string NoRestart = "norestart";
public static readonly string RunAsService = "runasservice";
public static readonly string Unattended = "unattended";
public static readonly string Version = "version";
public static readonly string WhatIf = "whatif";
}
}
public static class ReturnCode
{
public const int Success = 0;
public const int TerminatedError = 1;
public const int RetryableError = 2;
public const int AgentUpdating = 3;
}
public static class AgentConfigurationProvider
{
public static readonly string BuildReleasesAgentConfiguration = "BuildReleasesAgentConfiguration";
public static readonly string DeploymentAgentConfiguration = "DeploymentAgentConfiguration";
}
}
public static class Build
{
public static readonly string NoCICheckInComment = "***NO_CI***";
public static class Path
{
public static readonly string ArtifactsDirectory = "a";
public static readonly string BinariesDirectory = "b";
public static readonly string GarbageCollectionDirectory = "GC";
public static readonly string LegacyArtifactsDirectory = "artifacts";
public static readonly string LegacyStagingDirectory = "staging";
public static readonly string SourceRootMappingDirectory = "SourceRootMapping";
public static readonly string SourcesDirectory = "s";
public static readonly string TestResultsDirectory = "TestResults";
public static readonly string TopLevelTrackingConfigFile = "Mappings.json";
public static readonly string TrackingConfigFile = "SourceFolder.json";
public static readonly string VariablesMappingDirectory = "v";
}
}
public static class Configuration
{
public static readonly string PAT = "PAT";
public static readonly string Alternate = "ALT";
public static readonly string Negotiate = "Negotiate";
public static readonly string Integrated = "Integrated";
public static readonly string OAuth = "OAuth";
public static readonly string ServiceIdentity = "ServiceIdentity";
}
public static class EndpointData
{
public static readonly string SourcesDirectory = "SourcesDirectory";
public static readonly string SourceVersion = "SourceVersion";
public static readonly string SourceBranch = "SourceBranch";
public static readonly string SourceTfvcShelveset = "SourceTfvcShelveset";
public static readonly string GatedShelvesetName = "GatedShelvesetName";
public static readonly string GatedRunCI = "GatedRunCI";
}
public static class Expressions
{
public static readonly string Always = "always";
public static readonly string Canceled = "canceled";
public static readonly string Failed = "failed";
public static readonly string Succeeded = "succeeded";
public static readonly string SucceededOrFailed = "succeededOrFailed";
public static readonly string Variables = "variables";
}
public static class Path
{
public static readonly string BinDirectory = "bin";
public static readonly string DiagDirectory = "_diag";
public static readonly string ExternalsDirectory = "externals";
public static readonly string LegacyPSHostDirectory = "vstshost";
public static readonly string ServerOMDirectory = "vstsom";
public static readonly string TempDirectory = "_temp";
public static readonly string TeeDirectory = "tee";
public static readonly string ToolDirectory = "_tool";
public static readonly string TaskJsonFile = "task.json";
public static readonly string TasksDirectory = "_tasks";
public static readonly string UpdateDirectory = "_update";
public static readonly string WorkDirectory = "_work";
public static readonly string DevelopmentDirectory = "_dev";
}
public static class Release
{
public static readonly string Map = "Map";
public static class Path
{
public static readonly string ArtifactsDirectory = "a";
public static readonly string CommitsDirectory = "c";
public static readonly string DefinitionMapping = "DefinitionMapping.json";
public static readonly string ReleaseDirectoryPrefix = "r";
public static readonly string ReleaseTempDirectoryPrefix = "t";
public static readonly string RootMappingDirectory = "ReleaseRootMapping";
}
}
// Related to definition variables.
public static class Variables
{
public static readonly string MacroPrefix = "$(";
public static readonly string MacroSuffix = ")";
public static class Agent
{
//
// Keep alphabetical
//
public static readonly string AllowAllEndpoints = "agent.allowAllEndpoints"; // remove after sprint 120 or so.
public static readonly string AllowAllSecureFiles = "agent.allowAllSecureFiles"; // remove after sprint 121 or so.
public static readonly string BuildDirectory = "agent.builddirectory";
public static readonly string HomeDirectory = "agent.homedirectory";
public static readonly string Id = "agent.id";
public static readonly string JobName = "agent.jobname";
public static readonly string JobStatus = "agent.jobstatus";
public static readonly string MachineName = "agent.machinename";
public static readonly string Name = "agent.name";
public static readonly string OS = "agent.os";
public static readonly string OSVersion = "agent.osversion";
public static readonly string ProxyUrl = "agent.proxyurl";
public static readonly string ProxyUsername = "agent.proxyusername";
public static readonly string ProxyPassword = "agent.proxypassword";
public static readonly string ProxyBypassList = "agent.proxybypasslist";
public static readonly string RootDirectory = "agent.RootDirectory";
public static readonly string RunMode = "agent.runmode";
public static readonly string ServerOMDirectory = "agent.ServerOMDirectory";
public static readonly string TempDirectory = "agent.TempDirectory";
public static readonly string ToolsDirectory = "agent.ToolsDirectory";
public static readonly string Version = "agent.version";
public static readonly string UseNode5 = "agent.usenode5";
public static readonly string WorkFolder = "agent.workfolder";
public static readonly string WorkingDirectory = "agent.WorkingDirectory";
}
public static class Build
{
//
// Keep alphabetical
//
public static readonly string ArtifactStagingDirectory = "build.artifactstagingdirectory";
public static readonly string BinariesDirectory = "build.binariesdirectory";
public static readonly string Clean = "build.clean";
public static readonly string DefinitionName = "build.definitionname";
public static readonly string GatedRunCI = "build.gated.runci";
public static readonly string GatedShelvesetName = "build.gated.shelvesetname";
public static readonly string RepoClean = "build.repository.clean";
public static readonly string RepoGitSubmoduleCheckout = "build.repository.git.submodulecheckout";
public static readonly string RepoId = "build.repository.id";
public static readonly string RepoLocalPath = "build.repository.localpath";
public static readonly string RepoName = "build.Repository.name";
public static readonly string RepoProvider = "build.repository.provider";
public static readonly string RepoTfvcWorkspace = "build.repository.tfvc.workspace";
public static readonly string RepoUri = "build.repository.uri";
public static readonly string SourceBranch = "build.sourcebranch";
public static readonly string SourceTfvcShelveset = "build.sourcetfvcshelveset";
public static readonly string SourceVersion = "build.sourceversion";
public static readonly string SourcesDirectory = "build.sourcesdirectory";
public static readonly string StagingDirectory = "build.stagingdirectory";
public static readonly string SyncSources = "build.syncSources";
}
public static class Common
{
public static readonly string TestResultsDirectory = "common.testresultsdirectory";
}
public static class Features
{
//
// Keep alphabetical
//
public static readonly string BuildDirectoryClean = "agent.clean.buildDirectory";
public static readonly string GitLfsSupport = "agent.source.git.lfs";
public static readonly string GitShallowDepth = "agent.source.git.shallowFetchDepth";
public static readonly string SkipSyncSource = "agent.source.skip";
}
public static class Release
{
//
// Keep alphabetical
//
public static readonly string AgentReleaseDirectory = "agent.releaseDirectory";
public static readonly string ArtifactsDirectory = "system.artifactsDirectory";
public static readonly string AttemptNumber = "release.attemptNumber";
public static readonly string DisableRobocopy = "release.disableRobocopy";
public static readonly string ReleaseDefinitionName = "release.definitionName";
public static readonly string ReleaseEnvironmentName = "release.environmentName";
public static readonly string ReleaseEnvironmentUri = "release.environmentUri";
public static readonly string ReleaseDefinitionId = "release.definitionId";
public static readonly string ReleaseDescription = "release.releaseDescription";
public static readonly string ReleaseId = "release.releaseId";
public static readonly string ReleaseName = "release.releaseName";
public static readonly string ReleaseRequestedForId = "release.requestedForId";
public static readonly string ReleaseUri = "release.releaseUri";
public static readonly string ReleaseDownloadBufferSize = "release.artifact.download.buffersize";
public static readonly string ReleaseParallelDownloadLimit = "release.artifact.download.parallellimit";
public static readonly string ReleaseWebUrl = "release.releaseWebUrl";
public static readonly string RequestorId = "release.requestedFor";
public static readonly string RobocopyMT = "release.robocopyMT";
public static readonly string SkipArtifactsDownload = "release.skipartifactsDownload";
}
public static class System
{
//
// Keep alphabetical
//
public static readonly string AccessToken = "system.accessToken";
public static readonly string ArtifactsDirectory = "system.artifactsdirectory";
public static readonly string CollectionId = "system.collectionid";
public static readonly string Culture = "system.culture";
public static readonly string Debug = "system.debug";
public static readonly string DefaultWorkingDirectory = "system.defaultworkingdirectory";
public static readonly string DefinitionId = "system.definitionid";
public static readonly string EnableAccessToken = "system.enableAccessToken";
public static readonly string HostType = "system.hosttype";
public static readonly string PreferGitFromPath = "system.prefergitfrompath";
public static readonly string SelfManageGitCreds = "system.selfmanagegitcreds";
public static readonly string TFServerUrl = "system.TeamFoundationServerUri"; // back compat variable, do not document
public static readonly string TeamProject = "system.teamproject";
public static readonly string TeamProjectId = "system.teamProjectId";
public static readonly string WorkFolder = "system.workfolder";
}
public static class Task
{
public static readonly string DisplayName = "task.displayname";
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Preview.DeployedDevices.Fleet;
namespace Twilio.Tests.Rest.Preview.DeployedDevices.Fleet
{
[TestFixture]
public class CertificateTest : TwilioTest
{
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates/CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CertificateResource.Fetch("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"device_sid\": \"THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"thumbprint\": \"1234567890\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CertificateResource.Fetch("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates/CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CertificateResource.Delete("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = CertificateResource.Delete("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates",
""
);
request.AddPostParam("CertificateData", Serialize("certificate_data"));
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CertificateResource.Create("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "certificate_data", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"device_sid\": \"THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"thumbprint\": \"1234567890\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CertificateResource.Create("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "certificate_data", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CertificateResource.Read("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"certificates\": [],\"meta\": {\"first_page_url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0\",\"key\": \"certificates\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0\"}}"
));
var response = CertificateResource.Read("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestReadFullResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"certificates\": [{\"sid\": \"CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"device_sid\": \"THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"thumbprint\": \"1234567890\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"first_page_url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0\",\"key\": \"certificates\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates?PageSize=50&Page=0\"}}"
));
var response = CertificateResource.Read("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestUpdateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Preview,
"/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates/CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
CertificateResource.Update("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestUpdateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"fleet_sid\": \"FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"device_sid\": \"THaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"thumbprint\": \"1234567890\",\"date_created\": \"2016-07-30T20:00:00Z\",\"date_updated\": \"2016-07-30T20:00:00Z\",\"url\": \"https://preview.twilio.com/DeployedDevices/Fleets/FLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Certificates/CYaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}"
));
var response = CertificateResource.Update("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "CYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using NuGet.Resources;
namespace NuGet
{
public abstract class PackageWalker
{
private readonly Dictionary<IPackage, PackageWalkInfo> _packageLookup = new Dictionary<IPackage, PackageWalkInfo>();
private readonly FrameworkName _targetFramework;
protected PackageWalker()
: this(targetFramework: null)
{
}
protected PackageWalker(FrameworkName targetFramework)
{
_targetFramework = targetFramework;
Marker = new PackageMarker();
DependencyVersion = DependencyVersion.Lowest;
}
public virtual bool SkipPackageTargetCheck { get; set; }
protected FrameworkName TargetFramework
{
get
{
return _targetFramework;
}
}
protected virtual bool RaiseErrorOnCycle
{
get
{
return true;
}
}
protected virtual bool SkipDependencyResolveError
{
get
{
return false;
}
}
protected virtual bool IgnoreDependencies
{
get
{
return false;
}
}
protected virtual bool AllowPrereleaseVersions
{
get
{
return true;
}
}
public DependencyVersion DependencyVersion
{
get;
set;
}
protected PackageMarker Marker
{
get;
private set;
}
protected virtual bool IgnoreWalkInfo
{
get
{
return false;
}
}
public void Walk(IPackage package)
{
CheckPackageMinClientVersion(package);
// Do nothing if we saw this package already
if (Marker.IsVisited(package))
{
ProcessPackageTarget(package);
return;
}
OnBeforePackageWalk(package);
// Mark the package as processing
Marker.MarkProcessing(package);
if (!IgnoreDependencies)
{
foreach (var dependency in package.GetCompatiblePackageDependencies(TargetFramework))
{
// Try to resolve the dependency from the visited packages first
IPackage resolvedDependency = Marker.ResolveDependency(
dependency, constraintProvider: null,
allowPrereleaseVersions: AllowPrereleaseVersions,
preferListedPackages: false,
dependencyVersion: DependencyVersion) ??
ResolveDependency(dependency);
if (resolvedDependency == null)
{
OnDependencyResolveError(package, dependency);
// If we're skipping dependency resolve errors then move on to the next
// dependency
if (SkipDependencyResolveError)
{
continue;
}
return;
}
if (!IgnoreWalkInfo)
{
// Set the parent
PackageWalkInfo dependencyInfo = GetPackageInfo(resolvedDependency);
dependencyInfo.Parent = package;
}
Marker.AddDependent(package, resolvedDependency);
if (!OnAfterResolveDependency(package, resolvedDependency))
{
continue;
}
if (Marker.IsCycle(resolvedDependency) ||
Marker.IsVersionCycle(resolvedDependency.Id))
{
if (RaiseErrorOnCycle)
{
List<IPackage> packages = Marker.Packages.ToList();
packages.Add(resolvedDependency);
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.CircularDependencyDetected, String.Join(" => ",
packages.Select(p => p.GetFullName()))));
}
continue;
}
Walk(resolvedDependency);
}
}
// Mark the package as visited
Marker.MarkVisited(package);
ProcessPackageTarget(package);
OnAfterPackageWalk(package);
}
private static void CheckPackageMinClientVersion(IPackage package)
{
// validate that the current version of NuGet satisfies the minVersion attribute specified in the .nuspec
if (Constants.NuGetVersion < package.MinClientVersion)
{
throw new NuGetVersionNotSatisfiedException(
String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageMinVersionNotSatisfied, package.GetFullName(), package.MinClientVersion, Constants.NuGetVersion));
}
}
/// <summary>
/// Resolve the package target (i.e. if the parent package was a meta package then set the parent to the current project type)
/// </summary>
private void ProcessPackageTarget(IPackage package)
{
if (IgnoreWalkInfo || SkipPackageTargetCheck)
{
return;
}
PackageWalkInfo info = GetPackageInfo(package);
// If our parent is an unknown then we need to bubble up the type
if (info.Parent != null)
{
PackageWalkInfo parentInfo = GetPackageInfo(info.Parent);
Debug.Assert(parentInfo != null);
if (parentInfo.InitialTarget == PackageTargets.None)
{
// Update the parent target type
parentInfo.Target |= info.Target;
// If we ended up with both that means we found a dependency only packages
// that has a mix of solution and project level packages
if (parentInfo.Target == PackageTargets.All)
{
throw new InvalidOperationException(NuGetResources.DependencyOnlyCannotMixDependencies);
}
}
// Solution packages can't depend on project level packages
if (parentInfo.Target == PackageTargets.External && info.Target.HasFlag(PackageTargets.Project))
{
throw new InvalidOperationException(NuGetResources.ExternalPackagesCannotDependOnProjectLevelPackages);
}
}
}
protected virtual bool OnAfterResolveDependency(IPackage package, IPackage dependency)
{
return true;
}
protected virtual void OnBeforePackageWalk(IPackage package)
{
}
protected virtual void OnAfterPackageWalk(IPackage package)
{
}
protected virtual void OnDependencyResolveError(IPackage package, PackageDependency dependency)
{
}
protected abstract IPackage ResolveDependency(PackageDependency dependency);
protected internal PackageWalkInfo GetPackageInfo(IPackage package)
{
PackageWalkInfo info;
if (!_packageLookup.TryGetValue(package, out info))
{
info = new PackageWalkInfo(GetPackageTarget(package));
_packageLookup.Add(package, info);
}
return info;
}
private static PackageTargets GetPackageTarget(IPackage package)
{
if (package.HasProjectContent())
{
return PackageTargets.Project;
}
if (IsDependencyOnly(package))
{
return PackageTargets.None;
}
return PackageTargets.External;
}
/// <summary>
/// Returns true if a package has dependencies but no \tools directory
/// </summary>
private static bool IsDependencyOnly(IPackage package)
{
return !package.GetFiles().Any(f => f.Path.StartsWith(@"tools\", StringComparison.OrdinalIgnoreCase)) &&
package.DependencySets.SelectMany(d => d.Dependencies).Any();
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Scripting.Runtime;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("_codecs", typeof(IronPython.Modules.PythonCodecs))]
namespace IronPython.Modules {
public static class PythonCodecs {
public const string __doc__ = "Provides access to various codecs (ASCII, UTF7, UTF8, etc...)";
internal const int EncoderIndex = 0;
internal const int DecoderIndex = 1;
internal const int StreamReaderIndex = 2;
internal const int StreamWriterIndex = 3;
#region ASCII Encoding
public static object ascii_decode(object input) {
return ascii_decode(input, "strict");
}
public static object ascii_decode(object input, string errors) {
return DoDecode(PythonAsciiEncoding.Instance, input, errors, true);
}
public static object ascii_encode(object input) {
return ascii_encode(input, "strict");
}
public static object ascii_encode(object input, string errors) {
return DoEncode(PythonAsciiEncoding.Instance, input, errors);
}
#endregion
/// <summary>
/// Creates an optimized encoding mapping that can be consumed by an optimized version of charmap_encode.
/// </summary>
public static EncodingMap charmap_build(string decoding_table) {
if (decoding_table.Length != 256) {
throw PythonOps.TypeError("charmap_build expected 256 character string");
}
EncodingMap map = new EncodingMap();
for (int i = 0; i < decoding_table.Length; i++) {
map.Mapping[(int)decoding_table[i]] = (char)i;
}
return map;
}
/// <summary>
/// Optimied encoding mapping that can be consumed by charmap_encode.
/// </summary>
[PythonHidden]
public class EncodingMap {
internal Dictionary<int, char> Mapping = new Dictionary<int, char>();
}
/// <summary>
/// Decodes the input string using the provided string mapping.
/// </summary>
public static PythonTuple charmap_decode([BytesConversion]string input, string errors, [NotNull]string map) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < input.Length; i++) {
var charIndex = (int)input[i];
if (map.Length <= charIndex) {
if (errors == "strict") {
throw PythonOps.UnicodeDecodeError("failed to find key in mapping");
}
res.Append("\ufffd");
} else {
res.Append(map[input[i]]);
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
/// <summary>
/// Encodes the input string with the specified optimized encoding map.
/// </summary>
public static PythonTuple charmap_encode([BytesConversion]string input, string errors, [NotNull]EncodingMap map) {
StringBuilder res = new StringBuilder();
var dict = map.Mapping;
for (int i = 0; i < input.Length; i++) {
char val;
if (!dict.TryGetValue(input[i], out val)) {
if (errors == "strict") {
throw PythonOps.UnicodeEncodeError("failed to find key in mapping");
}
res.Append("\ufffd");
} else {
res.Append(val);
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
public static object charbuffer_encode() {
throw PythonOps.NotImplementedError("charbuffer_encode");
}
public static object charmap_decode([BytesConversion]string input, [Optional]string errors, [Optional]IDictionary<object, object> map) {
return CharmapDecodeWorker(input, errors, map, true);
}
private static object CharmapDecodeWorker(string input, string errors, IDictionary<object, object> map, bool isDecode) {
if (input.Length == 0) {
return PythonTuple.MakeTuple(String.Empty, 0);
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < input.Length; i++) {
object val;
if (map == null) {
res.Append(input[i]);
continue;
}
object charObj = ScriptingRuntimeHelpers.Int32ToObject((int)input[i]);
if (!map.TryGetValue(charObj, out val)) {
if (errors == "strict" && isDecode) {
throw PythonOps.UnicodeDecodeError("failed to find key in mapping");
} else if (!isDecode) {
throw PythonOps.UnicodeEncodeError("failed to find key in mapping");
}
res.Append("\ufffd");
} else if (val == null) {
if (errors == "strict" && isDecode) {
throw PythonOps.UnicodeDecodeError("'charmap' codec can't decode characters at index {0} because charmap maps to None", i);
} else if (!isDecode) {
throw PythonOps.UnicodeEncodeError("charmap", input[i], i,
"'charmap' codec can't encode characters at index {0} because charmap maps to None", i);
}
res.Append("\ufffd");
} else if (val is string) {
res.Append((string)val);
} else if (val is int) {
res.Append((char)(int)val);
} else {
throw PythonOps.TypeError("charmap must be an int, str, or None");
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
public static object charmap_encode([BytesConversion]string input, [DefaultParameterValue("strict")]string errors, [DefaultParameterValue(null)]IDictionary<object, object> map) {
return CharmapDecodeWorker(input, errors, map, false);
}
public static object decode(CodeContext/*!*/ context, object obj) {
PythonTuple t = lookup(context, PythonContext.GetContext(context).GetDefaultEncodingName());
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, null), 0);
}
public static object decode(CodeContext/*!*/ context, object obj, string encoding) {
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, null), 0);
}
public static object decode(CodeContext/*!*/ context, object obj, string encoding, string errors) {
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, errors), 0);
}
public static object encode(CodeContext/*!*/ context, object obj) {
PythonTuple t = lookup(context, PythonContext.GetContext(context).GetDefaultEncodingName());
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, null), 0);
}
public static object encode(CodeContext/*!*/ context, object obj, string encoding) {
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, null), 0);
}
public static object encode(CodeContext/*!*/ context, object obj, string encoding, string errors) {
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, errors), 0);
}
public static object escape_decode(string text, [DefaultParameterValue("strict")]string errors) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\') {
if (i == text.Length - 1) throw PythonOps.ValueError("\\ at end of string");
switch (text[++i]) {
case 'a': res.Append((char)0x07); break;
case 'b': res.Append((char)0x08); break;
case 't': res.Append('\t'); break;
case 'n': res.Append('\n'); break;
case 'r': res.Append('\r'); break;
case '\\': res.Append('\\'); break;
case 'f': res.Append((char)0x0c); break;
case 'v': res.Append((char)0x0b); break;
case '\n': break;
case 'x':
int dig1, dig2;
if (i >= text.Length - 2 || !CharToInt(text[i], out dig1) || !CharToInt(text[i + 1], out dig2)) {
switch (errors) {
case "strict":
if (i >= text.Length - 2) {
throw PythonOps.ValueError("invalid character value");
} else {
throw PythonOps.ValueError("invalid hexadecimal digit");
}
case "replace":
res.Append("?");
i--;
while (i < (text.Length - 1)) {
res.Append(text[i++]);
}
continue;
default:
throw PythonOps.ValueError("decoding error; unknown error handling code: " + errors);
}
}
res.Append(dig1 * 16 + dig2);
i += 2;
break;
default:
res.Append("\\" + text[i]);
break;
}
} else {
res.Append(text[i]);
}
}
return PythonTuple.MakeTuple(res.ToString(), text.Length);
}
private static bool CharToInt(char ch, out int val) {
if (Char.IsDigit(ch)) {
val = ch - '0';
return true;
}
ch = Char.ToUpper(ch);
if (ch >= 'A' && ch <= 'F') {
val = ch - 'A' + 10;
return true;
}
val = 0;
return false;
}
public static PythonTuple/*!*/ escape_encode(string text, [DefaultParameterValue("strict")]string errors) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < text.Length; i++) {
switch (text[i]) {
case '\n': res.Append("\\n"); break;
case '\r': res.Append("\\r"); break;
case '\t': res.Append("\\t"); break;
case '\\': res.Append("\\\\"); break;
case '\'': res.Append("\\'"); break;
default:
if (text[i] < 0x20 || text[i] >= 0x7f) {
res.AppendFormat("\\x{0:x2}", (int)text[i]);
} else {
res.Append(text[i]);
}
break;
}
}
return PythonTuple.MakeTuple(res.ToString(), ScriptingRuntimeHelpers.Int32ToObject(res.Length));
}
#region Latin-1 Functions
#if !SILVERLIGHT
public static object latin_1_decode(object input) {
return latin_1_decode(input, "strict");
}
public static object latin_1_decode(object input, string errors) {
return DoDecode(Encoding.GetEncoding("iso-8859-1"), input, errors);
}
public static object latin_1_encode(object input) {
return latin_1_encode(input, "strict");
}
public static object latin_1_encode(object input, string errors) {
return DoEncode(Encoding.GetEncoding("iso-8859-1"), input, errors);
}
#endif
#endregion
public static PythonTuple lookup(CodeContext/*!*/ context, string encoding) {
return PythonOps.LookupEncoding(context, encoding);
}
[LightThrowing]
public static object lookup_error(CodeContext/*!*/ context, string name) {
return PythonOps.LookupEncodingError(context, name);
}
#if FEATURE_ENCODING
#region MBCS Functions
public static PythonTuple mbcs_decode(CodeContext/*!*/ context, string input, [DefaultParameterValue("strict")]string errors, [DefaultParameterValue(false)]bool ignored) {
// CPython ignores the errors parameter
return PythonTuple.MakeTuple(
StringOps.decode(context, input, Encoding.Default, "replace"),
Builtin.len(input)
);
}
public static PythonTuple mbcs_encode(CodeContext/*!*/ context, string input, [DefaultParameterValue("strict")]string errors) {
// CPython ignores the errors parameter
return PythonTuple.MakeTuple(
StringOps.encode(context, input, Encoding.Default, "replace"),
Builtin.len(input)
);
}
#endregion
#endif
public static PythonTuple raw_unicode_escape_decode(CodeContext/*!*/ context, object input, [DefaultParameterValue("strict")]string errors) {
return PythonTuple.MakeTuple(
StringOps.decode(context, Converter.ConvertToString(input), "raw-unicode-escape", errors),
Builtin.len(input)
);
}
public static PythonTuple raw_unicode_escape_encode(CodeContext/*!*/ context, object input, [DefaultParameterValue("strict")]string errors) {
return PythonTuple.MakeTuple(
StringOps.encode(context, Converter.ConvertToString(input), "raw-unicode-escape", errors),
Builtin.len(input)
);
}
public static object readbuffer_encode() {
throw PythonOps.NotImplementedError("readbuffer_encode");
}
public static void register(CodeContext/*!*/ context, object search_function) {
PythonOps.RegisterEncoding(context, search_function);
}
public static void register_error(CodeContext/*!*/ context, string name, object handler) {
PythonOps.RegisterEncodingError(context, name, handler);
}
#region Unicode Escape Encoding
public static PythonTuple unicode_escape_decode() {
throw PythonOps.NotImplementedError("unicode_escape_decode");
}
public static PythonTuple unicode_escape_encode() {
throw PythonOps.NotImplementedError("unicode_escape_encode");
}
public static PythonTuple unicode_internal_decode(object input, [Optional]string errors) {
return utf_16_decode(input, errors, false);
}
public static PythonTuple unicode_internal_encode(object input, [Optional]string errors) {
// length consumed is returned in bytes and for a UTF-16 string that is 2 bytes per char
PythonTuple res = DoEncode(Encoding.Unicode, input, errors, false);
return PythonTuple.MakeTuple(
res[0],
((int)res[1]) * 2
);
}
#endregion
#region Utf-16 Big Endian Functions
public static PythonTuple utf_16_be_decode(object input) {
return utf_16_be_decode(input, "strict", false);
}
public static PythonTuple utf_16_be_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.BigEndianUnicode, input, errors);
}
public static PythonTuple utf_16_be_encode(object input) {
return utf_16_be_encode(input, "strict");
}
public static PythonTuple utf_16_be_encode(object input, string errors) {
return DoEncode(Encoding.BigEndianUnicode, input, errors);
}
#endregion
#region Utf-16 Functions
public static PythonTuple utf_16_decode(object input) {
return utf_16_decode(input, "strict", false);
}
public static PythonTuple utf_16_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.Unicode, input, errors);
}
public static PythonTuple utf_16_encode(object input) {
return utf_16_encode(input, "strict");
}
public static PythonTuple utf_16_encode(object input, string errors) {
return DoEncode(Encoding.Unicode, input, errors, true);
}
#endregion
public static PythonTuple utf_16_ex_decode(object input, [Optional]string errors) {
return utf_16_ex_decode(input, errors, null, null);
}
public static PythonTuple utf_16_ex_decode(object input, string errors, object unknown1, object unknown2) {
byte[] lePre = Encoding.Unicode.GetPreamble();
byte[] bePre = Encoding.BigEndianUnicode.GetPreamble();
string instr = Converter.ConvertToString(input);
bool match = true;
if (instr.Length > lePre.Length) {
for (int i = 0; i < lePre.Length; i++) {
if ((byte)instr[i] != lePre[i]) {
match = false;
break;
}
}
if (match) {
return PythonTuple.MakeTuple(String.Empty, lePre.Length, -1);
}
match = true;
}
if (instr.Length > bePre.Length) {
for (int i = 0; i < bePre.Length; i++) {
if ((byte)instr[i] != bePre[i]) {
match = false;
break;
}
}
if (match) {
return PythonTuple.MakeTuple(String.Empty, bePre.Length, 1);
}
}
PythonTuple res = utf_16_decode(input, errors, false) as PythonTuple;
return PythonTuple.MakeTuple(res[0], res[1], 0);
}
#region Utf-16 Le Functions
public static PythonTuple utf_16_le_decode(object input) {
return utf_16_le_decode(input, "strict", false);
}
public static PythonTuple utf_16_le_decode(object input, string errors, [Optional]bool ignored) {
return utf_16_decode(input, errors, false);
}
public static PythonTuple utf_16_le_encode(object input) {
return utf_16_le_encode(input, "strict");
}
public static PythonTuple utf_16_le_encode(object input, string errors) {
return DoEncode(Encoding.Unicode, input, errors);
}
#endregion
#region Utf-7 Functions
#if FEATURE_ENCODING
public static PythonTuple utf_7_decode(object input) {
return utf_7_decode(input, "strict", false);
}
public static PythonTuple utf_7_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.UTF7, input, errors);
}
public static PythonTuple utf_7_encode(object input) {
return utf_7_encode(input, "strict");
}
public static PythonTuple utf_7_encode(object input, string errors) {
return DoEncode(Encoding.UTF7, input, errors);
}
#endif
#endregion
#region Utf-8 Functions
public static PythonTuple utf_8_decode(object input) {
return utf_8_decode(input, "strict", false);
}
public static PythonTuple utf_8_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.UTF8, input, errors);
}
public static PythonTuple utf_8_encode(object input) {
return utf_8_encode(input, "strict");
}
public static PythonTuple utf_8_encode(object input, string errors) {
return DoEncode(Encoding.UTF8, input, errors);
}
#endregion
#if FEATURE_ENCODING
#region Utf-32 Functions
public static PythonTuple utf_32_decode(object input) {
return utf_32_decode(input, "strict");
}
public static PythonTuple utf_32_decode(object input, string errors) {
return DoDecode(Encoding.UTF32, input, errors);
}
public static PythonTuple utf_32_encode(object input) {
return utf_32_encode(input, "strict");
}
public static PythonTuple utf_32_encode(object input, string errors) {
return DoEncode(Encoding.UTF32, input, errors, true);
}
#endregion
public static PythonTuple utf_32_ex_decode(object input, [Optional]string errors) {
return utf_32_ex_decode(input, errors, null, null);
}
public static PythonTuple utf_32_ex_decode(object input, string errors, object unknown1, object unknown2) {
byte[] lePre = Encoding.UTF32.GetPreamble();
string instr = Converter.ConvertToString(input);
bool match = true;
if (instr.Length > lePre.Length) {
for (int i = 0; i < lePre.Length; i++) {
if ((byte)instr[i] != lePre[i]) {
match = false;
break;
}
}
if (match) {
return PythonTuple.MakeTuple(String.Empty, lePre.Length, -1);
}
}
PythonTuple res = utf_32_decode(input, errors) as PythonTuple;
return PythonTuple.MakeTuple(res[0], res[1], 0);
}
#region Utf-32 Le Functions
public static PythonTuple utf_32_le_decode(object input) {
return utf_32_le_decode(input, "strict", false);
}
public static PythonTuple utf_32_le_decode(object input, string errors, [Optional]bool ignored) {
return utf_32_decode(input, errors);
}
public static PythonTuple utf_32_le_encode(object input) {
return utf_32_le_encode(input, "strict");
}
public static PythonTuple utf_32_le_encode(object input, string errors) {
return DoEncode(Encoding.UTF32, input, errors);
}
#endregion
#endif
#region Private implementation
private static PythonTuple DoDecode(Encoding encoding, object input, string errors) {
return DoDecode(encoding, input, errors, false);
}
private static PythonTuple DoDecode(Encoding encoding, object input, string errors, bool fAlwaysThrow) {
// input should be character buffer of some form...
string res;
if (!Converter.TryConvertToString(input, out res)) {
Bytes tempBytes = input as Bytes;
if (tempBytes == null) {
throw PythonOps.TypeErrorForBadInstance("argument 1 must be string, got {0}", input);
} else {
res = tempBytes.ToString();
}
}
int preOffset = CheckPreamble(encoding, res);
byte[] bytes = new byte[res.Length - preOffset];
for (int i = 0; i < bytes.Length; i++) {
bytes[i] = (byte)res[i + preOffset];
}
#if FEATURE_ENCODING // DecoderFallback
encoding = (Encoding)encoding.Clone();
ExceptionFallBack fallback = null;
if (fAlwaysThrow) {
encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
} else {
fallback = (encoding is UTF8Encoding && DotNet) ?
// This is a workaround for a bug, see ExceptionFallbackBufferUtf8DotNet
// for more details.
new ExceptionFallBackUtf8DotNet(bytes):
new ExceptionFallBack(bytes);
encoding.DecoderFallback = fallback;
}
#endif
string decoded = encoding.GetString(bytes, 0, bytes.Length);
int badByteCount = 0;
#if FEATURE_ENCODING // DecoderFallback
if (!fAlwaysThrow) {
byte[] badBytes = fallback.buffer.badBytes;
if (badBytes != null) {
badByteCount = badBytes.Length;
}
}
#endif
PythonTuple tuple = PythonTuple.MakeTuple(decoded, bytes.Length - badByteCount);
return tuple;
}
internal static readonly bool DotNet;
static PythonCodecs() {
DotNet = Type.GetType("Mono.Runtime") == null;
}
private static int CheckPreamble(Encoding enc, string buffer) {
byte[] preamble = enc.GetPreamble();
if (preamble.Length != 0 && buffer.Length >= preamble.Length) {
bool hasPreamble = true;
for (int i = 0; i < preamble.Length; i++) {
if (preamble[i] != (byte)buffer[i]) {
hasPreamble = false;
break;
}
}
if (hasPreamble) {
return preamble.Length;
}
}
return 0;
}
private static PythonTuple DoEncode(Encoding encoding, object input, string errors) {
return DoEncode(encoding, input, errors, false);
}
private static PythonTuple DoEncode(Encoding encoding, object input, string errors, bool includePreamble) {
// input should be some Unicode object
string res;
if (Converter.TryConvertToString(input, out res)) {
StringBuilder sb = new StringBuilder();
encoding = (Encoding)encoding.Clone();
#if FEATURE_ENCODING // EncoderFallback
encoding.EncoderFallback = EncoderFallback.ExceptionFallback;
#endif
if (includePreamble) {
byte[] preamble = encoding.GetPreamble();
for (int i = 0; i < preamble.Length; i++) {
sb.Append((char)preamble[i]);
}
}
byte[] bytes = encoding.GetBytes(res);
for (int i = 0; i < bytes.Length; i++) {
sb.Append((char)bytes[i]);
}
return PythonTuple.MakeTuple(sb.ToString(), res.Length);
}
throw PythonOps.TypeErrorForBadInstance("cannot decode {0}", input);
}
#endregion
}
#if FEATURE_ENCODING // Encoding
class ExceptionFallBack : DecoderFallback {
internal ExceptionFallbackBuffer buffer;
// This ctor can be removed as soon as workaround for utf8 encoding in .net is
// no longer necessary.
protected ExceptionFallBack() {
}
public ExceptionFallBack(byte[] bytes) {
buffer = new ExceptionFallbackBuffer(bytes);
}
public override DecoderFallbackBuffer CreateFallbackBuffer() {
return buffer;
}
public override int MaxCharCount {
get { return 100; }
}
}
class ExceptionFallbackBuffer : DecoderFallbackBuffer {
internal byte[] badBytes;
protected byte[] inputBytes;
public ExceptionFallbackBuffer(byte[] bytes) {
inputBytes = bytes;
}
public override bool Fallback(byte[] bytesUnknown, int index) {
if (index > 0 && index + bytesUnknown.Length != inputBytes.Length) {
throw PythonOps.UnicodeDecodeError(
String.Format("failed to decode bytes at index: {0}", index), bytesUnknown, index);
}
// just some bad bytes at the end
badBytes = bytesUnknown;
return false;
}
public override char GetNextChar() {
return ' ';
}
public override bool MovePrevious() {
return false;
}
public override int Remaining {
get { return 0; }
}
}
// This class can be removed as soon as workaround for utf8 encoding in .net is
// no longer necessary.
class ExceptionFallBackUtf8DotNet : ExceptionFallBack {
public ExceptionFallBackUtf8DotNet(byte[] bytes) {
buffer = new ExceptionFallbackBufferUtf8DotNet(bytes);
}
}
// This class can be removed as soon as workaround for utf8 encoding in .net is
// no longer necessary.
class ExceptionFallbackBufferUtf8DotNet : ExceptionFallbackBuffer {
private bool ignoreNext = false;
public ExceptionFallbackBufferUtf8DotNet(byte[] bytes) : base(bytes) {
}
public override bool Fallback(byte[] bytesUnknown, int index) {
// In case of dot net and utf-8 value of index does not conform to documentation provided by
// Microsoft http://msdn.microsoft.com/en-us/library/bdftay9c%28v=vs.100%29.aspx
// The value of index is mysteriously decreased by the size of bytesUnknown
// Tested on Windows 7 64, .NET 4.0.30319.18408, all recommended patches as of 06.02.2014
if (ignoreNext) {
// dot net sometimes calls second time after this method returns false
// if this is the case, do nothing
return false;
}
// adjust index
index = index + bytesUnknown.Length;
ignoreNext = true;
return base.Fallback(bytesUnknown, index);
}
}
#endif
}
| |
namespace AutoMapper.UnitTests
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Should;
using Xunit;
public class CollectionMapping
{
public CollectionMapping()
{
SetUp();
}
public void SetUp()
{
Mapper.Reset();
}
public class MasterWithList
{
private IList<Detail> _details = new List<Detail>();
public int Id { get; set; }
// ReSharper disable once ConvertToAutoProperty
public IList<Detail> Details
{
get { return _details; }
set { _details = value; }
}
}
public class MasterWithCollection
{
public MasterWithCollection(ICollection<Detail> details)
{
Details = details;
}
public int Id { get; set; }
public ICollection<Detail> Details { get; set; }
}
public class MasterWithNoExistingCollection
{
public int Id { get; set; }
public HashSet<Detail> Details { get; set; }
}
public class Detail
{
public int Id { get; set; }
}
public class MasterDto
{
public int Id { get; set; }
public DetailDto[] Details { get; set; }
}
public class DetailDto
{
public int Id { get; set; }
}
private static void FillCollection<TSource, TDestination, TSourceItem, TDestinationItem>(
TSource s, TDestination d,
Func<TSource, IEnumerable<TSourceItem>> getSourceEnum,
Func<TDestination, ICollection<TDestinationItem>> getDestinationColl)
{
var collection = getDestinationColl(d);
collection.Clear();
foreach (var sourceItem in getSourceEnum(s))
{
collection.Add(Mapper.Map<TSourceItem, TDestinationItem>(sourceItem));
}
}
[Fact]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_list()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new List<Detail>());
var originalCollection = master.Details;
Mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldEqual(master.Details.Count);
}
[Fact]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new HashSet<Detail>());
var originalCollection = master.Details;
Mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldEqual(master.Details.Count);
}
[Fact]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set_with_aftermap()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.Ignore())
.AfterMap((s, d) => FillCollection(s, d, ss => ss.Details, dd => dd.Details));
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new HashSet<Detail>());
var originalCollection = master.Details;
Mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldEqual(master.Details.Count);
}
[Fact]
public void Should_keep_and_fill_destination_list()
{
Mapper.CreateMap<MasterDto, MasterWithList>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithList();
var originalCollection = master.Details;
Mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
originalCollection.Count.ShouldEqual(master.Details.Count);
}
[Fact]
public void Should_not_replace_destination_collection()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>();
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new List<Detail>());
var originalCollection = master.Details;
Mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
}
[Fact]
public void Should_be_able_to_map_to_a_collection_type_that_implements_ICollection_of_T()
{
Mapper.CreateMap<MasterDto, MasterWithNoExistingCollection>();
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = Mapper.Map<MasterDto, MasterWithNoExistingCollection>(dto);
master.Details.Count.ShouldEqual(2);
}
[Fact]
public void Should_not_replace_destination_list()
{
Mapper.CreateMap<MasterDto, MasterWithList>();
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithList();
var originalCollection = master.Details;
Mapper.Map(dto, master);
originalCollection.ShouldBeSameAs(master.Details);
}
#if !(SILVERLIGHT || NETFX_CORE)
[Fact]
public void Should_map_to_NameValueCollection()
{
// initially results in the following exception:
// ----> System.InvalidCastException : Unable to cast object of type 'System.Collections.Specialized.NameValueCollection' to type 'System.Collections.IList'.
// this was fixed by adding NameValueCollectionMapper to the MapperRegistry.
var c = new NameValueCollection();
var mappedCollection = Mapper.Map<NameValueCollection, NameValueCollection>(c);
mappedCollection.ShouldNotBeNull();
}
#endif
#if SILVERLIGHT || NETFX_CORE
public class HashSet<T> : Collection<T>
{
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
using System.Threading;
using System.Collections.ObjectModel;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Agent.Sdk;
namespace Microsoft.VisualStudio.Services.Agent.Tests.LogPluginHost
{
public sealed class LogPluginHostL0
{
public class TestTrace : IAgentLogPluginTrace
{
private Tracing _trace;
public TestTrace(TestHostContext testHostContext)
{
_trace = testHostContext.GetTrace();
}
public List<string> Outputs = new List<string>();
public void Output(string message)
{
Outputs.Add(message);
_trace.Info(message);
}
public void Trace(string message)
{
Outputs.Add(message);
_trace.Info(message);
}
}
public class TestPlugin1 : IAgentLogPlugin
{
public string FriendlyName => "Test1";
public Task FinalizeAsync(IAgentLogPluginContext context)
{
context.Output("Done");
return Task.CompletedTask;
}
public Task<bool> InitializeAsync(IAgentLogPluginContext context)
{
return Task.FromResult(true);
}
public Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line)
{
context.Output(line);
return Task.CompletedTask;
}
}
public class TestPlugin2 : IAgentLogPlugin
{
public string FriendlyName => "Test2";
public Task FinalizeAsync(IAgentLogPluginContext context)
{
context.Output("Done");
return Task.CompletedTask;
}
public Task<bool> InitializeAsync(IAgentLogPluginContext context)
{
return Task.FromResult(true);
}
public Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line)
{
context.Output(line);
return Task.CompletedTask;
}
}
public class TestPluginSlow : IAgentLogPlugin
{
public string FriendlyName => "TestSlow";
public Task FinalizeAsync(IAgentLogPluginContext context)
{
context.Output("Done");
return Task.CompletedTask;
}
public Task<bool> InitializeAsync(IAgentLogPluginContext context)
{
return Task.FromResult(true);
}
public async Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line)
{
context.Output("BLOCK");
await Task.Delay(TimeSpan.FromMilliseconds(-1));
}
}
public class TestPluginSlowRecover : IAgentLogPlugin
{
private int _counter = 0;
public string FriendlyName => "TestSlowRecover";
public Task FinalizeAsync(IAgentLogPluginContext context)
{
context.Output("Done");
return Task.CompletedTask;
}
public Task<bool> InitializeAsync(IAgentLogPluginContext context)
{
return Task.FromResult(true);
}
public async Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line)
{
if (_counter++ < 1)
{
context.Output("SLOW");
await Task.Delay(400);
}
else
{
context.Output(line);
}
}
}
public class TestPluginNotInitialized : IAgentLogPlugin
{
public string FriendlyName => "TestNotInitialized";
public Task FinalizeAsync(IAgentLogPluginContext context)
{
context.Output("Done");
return Task.CompletedTask;
}
public Task<bool> InitializeAsync(IAgentLogPluginContext context)
{
return Task.FromResult(false);
}
public Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line)
{
context.Output(line);
return Task.CompletedTask;
}
}
public class TestPluginException : IAgentLogPlugin
{
public string FriendlyName => "TestException";
public Task FinalizeAsync(IAgentLogPluginContext context)
{
if (context.Variables.ContainsKey("throw_finalize"))
{
throw new NotSupportedException();
}
else
{
context.Output("Done");
return Task.CompletedTask;
}
}
public Task<bool> InitializeAsync(IAgentLogPluginContext context)
{
if (context.Variables.ContainsKey("throw_initialize"))
{
throw new NotSupportedException();
}
else
{
return Task.FromResult(true);
}
}
public Task ProcessLineAsync(IAgentLogPluginContext context, Pipelines.TaskStepDefinitionReference step, string line)
{
if (context.Variables.ContainsKey("throw_process"))
{
throw new NotSupportedException();
}
else
{
context.Output(line);
return Task.CompletedTask;
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_RunSinglePlugin()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 999"));
Assert.True(trace.Outputs.Contains("Test1: Done"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_RunSinglePluginWithEmptyLinesInput()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
var task = logPluginHost.Run();
for (int i = 0; i < 100; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
for (int i = 0; i < 100; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
for (int i = 0; i < 10; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:");
}
for (int i = 100; i < 200; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 99"));
Assert.True(trace.Outputs.Contains("Test1: "));
Assert.True(trace.Outputs.Contains("Test1: 100"));
Assert.True(trace.Outputs.Contains("Test1: 199"));
Assert.Equal(10, trace.Outputs.FindAll(x => x == "Test1: ").Count);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_RunMultiplePlugins()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPlugin2() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
foreach (var fragment in new string[] { "Test1: 0", "Test1: 999", "Test1: Done", "Test2: 0", "Test2: 999", "Test2: Done"})
{
Assert.True(trace.Outputs.Contains(fragment), $"Found '{fragment}' in: {trace.Outputs}");
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_ShortCircuitSlowPlugin()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPluginSlow() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace, 100, 100);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
// regular one still running
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 999"));
Assert.True(trace.Outputs.Contains("Test1: Done"));
// slow one got killed
Assert.False(trace.Outputs.Contains("TestSlow: Done"));
Assert.True(trace.Outputs.Exists(x => x.Contains("Plugin has been short circuited")));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_SlowPluginRecover()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPluginSlowRecover() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace, 950, 100);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(2000);
logPluginHost.Finish();
await task;
// regular one still running
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 999"));
Assert.True(trace.Outputs.Contains("Test1: Done"));
Assert.True(trace.Outputs.Contains("TestSlowRecover: Done"));
Assert.True(trace.Outputs.Exists(x => x.Contains("TestPluginSlowRecover' has too many buffered outputs.")));
Assert.True(trace.Outputs.Exists(x => x.Contains("TestPluginSlowRecover' has cleared out buffered outputs.")));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_NotInitialized()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPluginNotInitialized() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
// regular one still running
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 999"));
Assert.True(trace.Outputs.Contains("Test1: Done"));
Assert.True(!trace.Outputs.Contains("TestNotInitialized: 0"));
Assert.True(!trace.Outputs.Contains("TestNotInitialized: Done"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_HandleInitialExceptions()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
hostContext.Variables["throw_initialize"] = "1";
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPluginException() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
// regular one still running
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 999"));
Assert.True(trace.Outputs.Contains("Test1: Done"));
Assert.True(!trace.Outputs.Contains("TestException: 0"));
Assert.True(!trace.Outputs.Contains("TestException: Done"));
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Plugin")]
public async Task LogPluginHost_HandleProcessExceptions()
{
using (TestHostContext tc = new TestHostContext(this))
{
AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
hostContext.Variables["throw_process"] = "1";
List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPluginException() };
TestTrace trace = new TestTrace(tc);
AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
var task = logPluginHost.Run();
for (int i = 0; i < 1000; i++)
{
logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
}
await Task.Delay(1000);
logPluginHost.Finish();
await task;
// regular one still running
Assert.True(trace.Outputs.Contains("Test1: 0"));
Assert.True(trace.Outputs.Contains("Test1: 999"));
Assert.True(trace.Outputs.Contains("Test1: Done"));
Assert.True(!trace.Outputs.Contains("TestException: 0"));
Assert.True(!trace.Outputs.Contains("TestException: 999"));
Assert.True(trace.Outputs.Contains("TestException: Done"));
}
}
// potential bug in XUnit cause the test failure.
// [Fact]
// [Trait("Level", "L0")]
// [Trait("Category", "Plugin")]
// public async Task LogPluginHost_HandleFinalizeExceptions()
// {
// using (TestHostContext tc = new TestHostContext(this))
// {
// AgentLogPluginHostContext hostContext = CreateTestLogPluginHostContext();
// hostContext.Variables["throw_finalize"] = "1";
// List<IAgentLogPlugin> plugins = new List<IAgentLogPlugin>() { new TestPlugin1(), new TestPluginException() };
// TestTrace trace = new TestTrace(tc);
// AgentLogPluginHost logPluginHost = new AgentLogPluginHost(hostContext, plugins, trace);
// var task = logPluginHost.Run();
// for (int i = 0; i < 1000; i++)
// {
// logPluginHost.EnqueueOutput($"{Guid.Empty.ToString("D")}:{i}");
// }
// await Task.Delay(1000);
// logPluginHost.Finish();
// await task;
// // regular one still running
// Assert.True(trace.Outputs.Contains("Test1: 0"));
// Assert.True(trace.Outputs.Contains("Test1: 999"));
// Assert.True(trace.Outputs.Contains("Test1: Done"));
// Assert.True(trace.Outputs.Contains("TestException: 0"));
// Assert.True(trace.Outputs.Contains("TestException: 999"));
// Assert.True(!trace.Outputs.Contains("TestException: Done"));
// }
// }
private AgentLogPluginHostContext CreateTestLogPluginHostContext()
{
AgentLogPluginHostContext hostContext = new AgentLogPluginHostContext()
{
Endpoints = new List<ServiceEndpoint>(),
PluginAssemblies = new List<string>(),
Repositories = new List<Pipelines.RepositoryResource>(),
Variables = new Dictionary<string, VariableValue>(),
Steps = new Dictionary<string, Pipelines.TaskStepDefinitionReference>()
};
hostContext.Steps[Guid.Empty.ToString("D")] = new Pipelines.TaskStepDefinitionReference()
{
Id = Guid.NewGuid(),
Name = "Test",
Version = "1.0.0."
};
var systemConnection = new ServiceEndpoint()
{
Name = WellKnownServiceEndpointNames.SystemVssConnection,
Id = Guid.NewGuid(),
Url = new Uri("https://dev.azure.com/test"),
Authorization = new EndpointAuthorization()
{
Scheme = EndpointAuthorizationSchemes.OAuth,
Parameters = { { EndpointAuthorizationParameters.AccessToken, "Test" } }
}
};
hostContext.Endpoints.Add(systemConnection);
return hostContext;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.OpenXmlFormats;
using System;
using NPOI.HSSF.Util;
using System.Text;
using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
namespace NPOI.XSSF.UserModel
{
/**
* Represents a color in SpreadsheetML
*/
public class XSSFColor : IColor
{
private CT_Color ctColor;
/**
* Create an instance of XSSFColor from the supplied XML bean
*/
public XSSFColor(CT_Color color)
{
this.ctColor = color;
}
/**
* Create an new instance of XSSFColor
*/
public XSSFColor()
{
this.ctColor = new CT_Color();
}
public XSSFColor(System.Drawing.Color clr)
: this()
{
ctColor.SetRgb((byte)clr.R, (byte)clr.G, (byte)clr.B);
}
public XSSFColor(byte[] rgb)
: this()
{
ctColor.SetRgb(rgb);
}
/// <summary>
///A bool value indicating the ctColor is automatic and system ctColor dependent.
/// </summary>
public bool IsAuto
{
get
{
return ctColor.auto;
}
set
{
ctColor.auto = value;
ctColor.autoSpecified = true;
}
}
/**
* Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors.
*/
public short Indexed
{
get
{
return ctColor.indexedSpecified ? (short)ctColor.indexed : (short)0;
}
set
{
ctColor.indexed = (uint)value;
ctColor.indexedSpecified = true;
}
}
public byte[] GetRgb()
{
return this.RGB;
}
/**
* Standard Red Green Blue ctColor value (RGB).
* If there was an A (Alpha) value, it will be stripped.
*/
public byte[] RGB
{
get
{
byte[] rgb = GetRGBOrARGB();
if (rgb == null) return null;
if (rgb.Length == 4)
{
// Need to trim off the alpha
byte[] tmp = new byte[3];
Array.Copy(rgb, 1, tmp, 0, 3);
return tmp;
}
else
{
return rgb;
}
}
}
/**
* Standard Alpha Red Green Blue ctColor value (ARGB).
*/
public byte[] GetARgb()
{
byte[] rgb = GetRGBOrARGB();
if (rgb == null) return null;
if (rgb.Length == 3)
{
// Pad with the default Alpha
byte[] tmp = new byte[4];
tmp[0] = 255;
Array.Copy(rgb, 0, tmp, 1, 3);
return tmp;
}
else
{
return rgb;
}
}
private byte[] GetRGBOrARGB()
{
byte[] rgb = null;
if (ctColor.indexedSpecified && ctColor.indexed > 0)
{
HSSFColor indexed = (HSSFColor)HSSFColor.GetIndexHash()[(int)ctColor.indexed];
if (indexed != null)
{
rgb = new byte[3];
rgb[0] = (byte)indexed.GetTriplet()[0];
rgb[1] = (byte)indexed.GetTriplet()[1];
rgb[2] = (byte)indexed.GetTriplet()[2];
return rgb;
}
}
if (!ctColor.IsSetRgb())
{
// No colour is available, sorry
return null;
}
// Grab the colour
rgb = ctColor.GetRgb();
// Correct it as needed, and return
return (rgb);
}
/**
* Standard Red Green Blue ctColor value (RGB) with applied tint.
* Alpha values are ignored.
*/
public byte[] GetRgbWithTint()
{
byte[] rgb = ctColor.GetRgb();
if (rgb != null)
{
if (rgb.Length == 4)
{
byte[] tmp = new byte[3];
Array.Copy(rgb, 1, tmp, 0, 3);
rgb = tmp;
}
for (int i = 0; i < rgb.Length; i++)
{
rgb[i] = ApplyTint(rgb[i] & 0xFF, ctColor.tint);
}
}
return rgb;
}
/**
* Return the ARGB value in hex format, eg FF00FF00.
* Works for both regular and indexed colours.
*/
public String GetARGBHex()
{
StringBuilder sb = new StringBuilder();
byte[] rgb = GetARgb();
if (rgb == null)
{
return null;
}
foreach (byte c in rgb)
{
int i = (int)c;
if (i < 0)
{
i += 256;
}
String cs = StringUtil.ToHexString(i);
if (cs.Length == 1)
{
sb.Append('0');
}
sb.Append(cs);
}
return sb.ToString().ToUpper();
}
private static byte ApplyTint(int lum, double tint)
{
if (tint > 0)
{
return (byte)(lum * (1.0 - tint) + (255 - 255 * (1.0 - tint)));
}
else if (tint < 0)
{
return (byte)(lum * (1 + tint));
}
else
{
return (byte)lum;
}
}
/**
* Standard Alpha Red Green Blue ctColor value (ARGB).
*/
public void SetRgb(byte[] rgb)
{
// Correct it and save
ctColor.SetRgb((rgb));
}
/**
* Index into the <clrScheme> collection, referencing a particular <sysClr> or
* <srgbClr> value expressed in the Theme part.
*/
public int Theme
{
get
{
return ctColor.themeSpecified ? (int)ctColor.theme : (int)0;
}
set
{
ctColor.theme = (uint)value;
}
}
/**
* Specifies the tint value applied to the ctColor.
*
* <p>
* If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final
* ctColor applied.
* </p>
* <p>
* The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and
* 1.0 means 100% lighten. Also, 0.0 means no Change.
* </p>
* <p>
* In loading the RGB value, it is Converted to HLS where HLS values are (0..HLSMAX), where
* HLSMAX is currently 255.
* </p>
* Here are some examples of how to apply tint to ctColor:
* <blockquote>
* <pre>
* If (tint < 0)
* Lum' = Lum * (1.0 + tint)
*
* For example: Lum = 200; tint = -0.5; Darken 50%
* Lum' = 200 * (0.5) => 100
* For example: Lum = 200; tint = -1.0; Darken 100% (make black)
* Lum' = 200 * (1.0-1.0) => 0
* If (tint > 0)
* Lum' = Lum * (1.0-tint) + (HLSMAX - HLSMAX * (1.0-tint))
* For example: Lum = 100; tint = 0.75; Lighten 75%
*
* Lum' = 100 * (1-.75) + (HLSMAX - HLSMAX*(1-.75))
* = 100 * .25 + (255 - 255 * .25)
* = 25 + (255 - 63) = 25 + 192 = 217
* For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
* Lum' = 100 * (1-1) + (HLSMAX - HLSMAX*(1-1))
* = 100 * 0 + (255 - 255 * 0)
* = 0 + (255 - 0) = 255
* </pre>
* </blockquote>
*
* @return the tint value
*/
public double Tint
{
get
{
return ctColor.tint;
}
set
{
ctColor.tint = value;
ctColor.tintSpecified = true;
}
}
/**
* Specifies the tint value applied to the ctColor.
*
* <p>
* If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final
* ctColor applied.
* </p>
* <p>
* The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and
* 1.0 means 100% lighten. Also, 0.0 means no Change.
* </p>
* <p>
* In loading the RGB value, it is Converted to HLS where HLS values are (0..HLSMAX), where
* HLSMAX is currently 255.
* </p>
* Here are some examples of how to apply tint to ctColor:
* <blockquote>
* <pre>
* If (tint < 0)
* Lum' = Lum * (1.0 + tint)
*
* For example: Lum = 200; tint = -0.5; Darken 50%
* Lum' = 200 * (0.5) => 100
* For example: Lum = 200; tint = -1.0; Darken 100% (make black)
* Lum' = 200 * (1.0-1.0) => 0
* If (tint > 0)
* Lum' = Lum * (1.0-tint) + (HLSMAX - HLSMAX * (1.0-tint))
* For example: Lum = 100; tint = 0.75; Lighten 75%
*
* Lum' = 100 * (1-.75) + (HLSMAX - HLSMAX*(1-.75))
* = 100 * .25 + (255 - 255 * .25)
* = 25 + (255 - 63) = 25 + 192 = 217
* For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
* Lum' = 100 * (1-1) + (HLSMAX - HLSMAX*(1-1))
* = 100 * 0 + (255 - 255 * 0)
* = 0 + (255 - 0) = 255
* </pre>
* </blockquote>
*
* @param tint the tint value
*/
/**
* Returns the underlying XML bean
*
* @return the underlying XML bean
*/
internal CT_Color GetCTColor()
{
return ctColor;
}
public override int GetHashCode()
{
return ctColor.ToString().GetHashCode();
}
public override bool Equals(Object o)
{
if (o == null || !(o is XSSFColor)) return false;
XSSFColor cf = (XSSFColor)o;
return ctColor.ToString().Equals(cf.GetCTColor().ToString());
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace LaunchServer.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using XenAdmin.Controls;
namespace XenAdmin.Wizards.HAWizard_Pages
{
partial class AssignPriorities
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#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(AssignPriorities));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.pictureBoxStatus = new System.Windows.Forms.PictureBox();
this.labelHaStatus = new System.Windows.Forms.Label();
this.labelProtectionLevel = new System.Windows.Forms.Label();
this.m_dropDownButtonRestartPriority = new XenAdmin.Controls.DropDownButton();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.labelStartOrder = new System.Windows.Forms.Label();
this.nudOrder = new System.Windows.Forms.NumericUpDown();
this.labelStartDelay = new System.Windows.Forms.Label();
this.nudStartDelay = new System.Windows.Forms.NumericUpDown();
this.labelStartDelayUnits = new System.Windows.Forms.Label();
this.linkLabelTellMeMore = new System.Windows.Forms.LinkLabel();
this.haNtolIndicator = new XenAdmin.Controls.HaNtolIndicator();
this.dataGridViewVms = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.colImage = new System.Windows.Forms.DataGridViewImageColumn();
this.colVm = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colRestartPriority = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colStartOrder = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDelay = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colAgile = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.button1 = new System.Windows.Forms.Button();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudOrder)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudStartDelay)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewVms)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.pictureBoxStatus, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.labelHaStatus, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.labelProtectionLevel, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.m_dropDownButtonRestartPriority, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.labelStartOrder, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.nudOrder, 3, 3);
this.tableLayoutPanel1.Controls.Add(this.labelStartDelay, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.nudStartDelay, 3, 4);
this.tableLayoutPanel1.Controls.Add(this.labelStartDelayUnits, 4, 4);
this.tableLayoutPanel1.Controls.Add(this.linkLabelTellMeMore, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.haNtolIndicator, 5, 2);
this.tableLayoutPanel1.Controls.Add(this.dataGridViewVms, 0, 1);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// pictureBoxStatus
//
this.pictureBoxStatus.Image = global::XenAdmin.Properties.Resources._000_Tick_h32bit_16;
resources.ApplyResources(this.pictureBoxStatus, "pictureBoxStatus");
this.pictureBoxStatus.Name = "pictureBoxStatus";
this.pictureBoxStatus.TabStop = false;
//
// labelHaStatus
//
resources.ApplyResources(this.labelHaStatus, "labelHaStatus");
this.tableLayoutPanel1.SetColumnSpan(this.labelHaStatus, 5);
this.labelHaStatus.Name = "labelHaStatus";
//
// labelProtectionLevel
//
resources.ApplyResources(this.labelProtectionLevel, "labelProtectionLevel");
this.tableLayoutPanel1.SetColumnSpan(this.labelProtectionLevel, 2);
this.labelProtectionLevel.Name = "labelProtectionLevel";
//
// m_dropDownButtonRestartPriority
//
this.tableLayoutPanel1.SetColumnSpan(this.m_dropDownButtonRestartPriority, 2);
this.m_dropDownButtonRestartPriority.ContextMenuStrip = this.contextMenuStrip;
resources.ApplyResources(this.m_dropDownButtonRestartPriority, "m_dropDownButtonRestartPriority");
this.m_dropDownButtonRestartPriority.Name = "m_dropDownButtonRestartPriority";
this.m_dropDownButtonRestartPriority.UseVisualStyleBackColor = true;
this.m_dropDownButtonRestartPriority.Click += new System.EventHandler(this.m_dropDownButtonRestartPriority_Click);
//
// contextMenuStrip
//
this.contextMenuStrip.Name = "contextMenuStrip";
resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip");
//
// labelStartOrder
//
resources.ApplyResources(this.labelStartOrder, "labelStartOrder");
this.tableLayoutPanel1.SetColumnSpan(this.labelStartOrder, 3);
this.labelStartOrder.Name = "labelStartOrder";
//
// nudOrder
//
resources.ApplyResources(this.nudOrder, "nudOrder");
this.nudOrder.Name = "nudOrder";
this.nudOrder.ValueChanged += new System.EventHandler(this.nudOrder_ValueChanged);
//
// labelStartDelay
//
resources.ApplyResources(this.labelStartDelay, "labelStartDelay");
this.tableLayoutPanel1.SetColumnSpan(this.labelStartDelay, 3);
this.labelStartDelay.Name = "labelStartDelay";
//
// nudStartDelay
//
resources.ApplyResources(this.nudStartDelay, "nudStartDelay");
this.nudStartDelay.Name = "nudStartDelay";
this.nudStartDelay.ValueChanged += new System.EventHandler(this.nudStartDelay_ValueChanged);
//
// labelStartDelayUnits
//
resources.ApplyResources(this.labelStartDelayUnits, "labelStartDelayUnits");
this.labelStartDelayUnits.Name = "labelStartDelayUnits";
//
// linkLabelTellMeMore
//
resources.ApplyResources(this.linkLabelTellMeMore, "linkLabelTellMeMore");
this.tableLayoutPanel1.SetColumnSpan(this.linkLabelTellMeMore, 5);
this.linkLabelTellMeMore.Name = "linkLabelTellMeMore";
this.linkLabelTellMeMore.TabStop = true;
this.linkLabelTellMeMore.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelTellMeMore_LinkClicked);
//
// haNtolIndicator
//
resources.ApplyResources(this.haNtolIndicator, "haNtolIndicator");
this.haNtolIndicator.Name = "haNtolIndicator";
this.tableLayoutPanel1.SetRowSpan(this.haNtolIndicator, 4);
//
// dataGridViewVms
//
this.dataGridViewVms.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridViewVms.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridViewVms.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridViewVms.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colImage,
this.colVm,
this.colRestartPriority,
this.colStartOrder,
this.colDelay,
this.colAgile});
this.tableLayoutPanel1.SetColumnSpan(this.dataGridViewVms, 6);
resources.ApplyResources(this.dataGridViewVms, "dataGridViewVms");
this.dataGridViewVms.MultiSelect = true;
this.dataGridViewVms.Name = "dataGridViewVms";
this.dataGridViewVms.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridViewVms_KeyDown);
this.dataGridViewVms.SelectionChanged += new System.EventHandler(this.dataGridViewVms_SelectionChanged);
//
// colImage
//
this.colImage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.colImage, "colImage");
this.colImage.Name = "colImage";
//
// colVm
//
this.colVm.FillWeight = 123.8597F;
resources.ApplyResources(this.colVm, "colVm");
this.colVm.Name = "colVm";
//
// colRestartPriority
//
this.colRestartPriority.FillWeight = 142.0455F;
resources.ApplyResources(this.colRestartPriority, "colRestartPriority");
this.colRestartPriority.Name = "colRestartPriority";
//
// colStartOrder
//
this.colStartOrder.FillWeight = 78.03161F;
resources.ApplyResources(this.colStartOrder, "colStartOrder");
this.colStartOrder.Name = "colStartOrder";
//
// colDelay
//
this.colDelay.FillWeight = 78.03161F;
resources.ApplyResources(this.colDelay, "colDelay");
this.colDelay.Name = "colDelay";
//
// colAgile
//
this.colAgile.FillWeight = 78.03161F;
resources.ApplyResources(this.colAgile, "colAgile");
this.colAgile.Name = "colAgile";
//
// button1
//
resources.ApplyResources(this.button1, "button1");
this.button1.Name = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// AssignPriorities
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "AssignPriorities";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudOrder)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudStartDelay)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewVms)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label labelHaStatus;
private System.Windows.Forms.PictureBox pictureBoxStatus;
private HaNtolIndicator haNtolIndicator;
private System.Windows.Forms.Label labelStartDelayUnits;
private System.Windows.Forms.NumericUpDown nudStartDelay;
private System.Windows.Forms.Label labelStartDelay;
private System.Windows.Forms.Label labelStartOrder;
private System.Windows.Forms.NumericUpDown nudOrder;
private DropDownButton m_dropDownButtonRestartPriority;
private System.Windows.Forms.Label labelProtectionLevel;
private System.Windows.Forms.LinkLabel linkLabelTellMeMore;
private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewVms;
private System.Windows.Forms.DataGridViewImageColumn colImage;
private System.Windows.Forms.DataGridViewTextBoxColumn colVm;
private System.Windows.Forms.DataGridViewTextBoxColumn colRestartPriority;
private System.Windows.Forms.DataGridViewTextBoxColumn colStartOrder;
private System.Windows.Forms.DataGridViewTextBoxColumn colDelay;
private System.Windows.Forms.DataGridViewTextBoxColumn colAgile;
}
}
| |
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.ChangeTracking;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using EntityGenerics.Annotations;
namespace EntityGenerics.Core.Abstractions
{
public interface IDbContext
{
/// <summary>
/// Provides access to database related information and operations for this context.
///
/// </summary>
DatabaseFacade Database { get; }
/// <summary>
/// Provides access to information and operations for entity instances this context is tracking.
///
/// </summary>
ChangeTracker ChangeTracker { get; }
/// <summary>
/// The metadata about the shape of entities, the relationships between them, and how they map to the database.
///
/// </summary>
IModel Model { get; }
/// <summary>
/// Saves all changes made in this context to the database.
///
/// </summary>
///
/// <remarks>
/// This method will automatically call <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.DetectChanges"/> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled"/>.
///
/// </remarks>
///
/// <returns>
/// The number of state entries written to the database.
///
/// </returns>
int SaveChanges();
/// <summary>
/// Saves all changes made in this context to the database.
///
/// </summary>
/// <param name="acceptAllChangesOnSuccess">Indicates whether <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AcceptAllChanges"/> is called after the changes have
/// been sent successfully to the database.
/// </param>
/// <remarks>
/// This method will automatically call <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.DetectChanges"/> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled"/>.
///
/// </remarks>
///
/// <returns>
/// The number of state entries written to the database.
///
/// </returns>
int SaveChanges(bool acceptAllChangesOnSuccess);
/// <summary>
/// Asynchronously saves all changes made in this context to the database.
///
/// </summary>
///
/// <remarks>
///
/// <para>
/// This method will automatically call <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.DetectChanges"/> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled"/>.
///
/// </para>
///
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
///
/// </para>
///
/// </remarks>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken"/> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the database.
///
/// </returns>
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Asynchronously saves all changes made in this context to the database.
///
/// </summary>
/// <param name="acceptAllChangesOnSuccess">Indicates whether <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AcceptAllChanges"/> is called after the changes have
/// been sent successfully to the database.
/// </param>
/// <remarks>
///
/// <para>
/// This method will automatically call <see cref="M:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.DetectChanges"/> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.Data.Entity.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled"/>.
///
/// </para>
///
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
///
/// </para>
///
/// </remarks>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken"/> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the database.
///
/// </returns>
Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Releases the allocated resources for this context.
///
/// </summary>
void Dispose();
/// <summary>
/// Gets an <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry`1"/> for the given entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </summary>
/// <typeparam name="TEntity">The type of the entity. </typeparam><param name="entity">The entity to get the entry for. </param>
/// <returns>
/// The entry for the given entity.
/// </returns>
EntityEntry<TEntity> Entry<TEntity>([NotNull] TEntity entity) where TEntity : class;
/// <summary>
///
/// <para>
/// Gets an <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> for the given entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </para>
///
/// <para>
/// This method may be called on an entity that is not tracked. You can then
/// set the <see cref="P:Microsoft.Data.Entity.ChangeTracking.EntityEntry.State"/> property on the returned entry
/// to have the context begin tracking the entity in the specified state.
///
/// </para>
///
/// </summary>
/// <param name="entity">The entity to get the entry for. </param>
/// <returns>
/// The entry for the given entity.
/// </returns>
EntityEntry Entry([NotNull] object entity);
/// <summary>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state such that it will
/// be inserted into the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <typeparam name="TEntity">The type of the entity. </typeparam><param name="entity">The entity to add. </param><param name="behavior">Determines whether the context will bring in only the given entity or also other related entities.
/// </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry`1"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry<TEntity> Add<TEntity>([NotNull] TEntity entity, GraphBehavior behavior = GraphBehavior.IncludeDependents) where TEntity : class;
/// <summary>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/> state such that no
/// operation will be performed when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <typeparam name="TEntity">The type of the entity. </typeparam><param name="entity">The entity to attach. </param><param name="behavior">Determines whether the context will bring in only the given entity or also other related entities.
/// </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry`1"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry<TEntity> Attach<TEntity>([NotNull] TEntity entity, GraphBehavior behavior = GraphBehavior.IncludeDependents) where TEntity : class;
/// <summary>
///
/// <para>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Modified"/> state such that it will
/// be updated in the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </para>
///
/// <para>
/// All properties of the entity will be marked as modified. To mark only some properties as modified, use
/// <see cref="M:Microsoft.Data.Entity.DbContext.Attach``1(``0,Microsoft.Data.Entity.GraphBehavior)"/> to begin tracking the entity in the
/// <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/> state and then use the returned <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry`1"/>
/// to mark the desired properties as modified.
///
/// </para>
///
/// </summary>
/// <typeparam name="TEntity">The type of the entity. </typeparam><param name="entity">The entity to update. </param><param name="behavior">Determines whether the context will bring in only the given entity or also other related entities.
/// </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry`1"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry<TEntity> Update<TEntity>([NotNull] TEntity entity, GraphBehavior behavior = GraphBehavior.IncludeDependents) where TEntity : class;
/// <summary>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/> state such that it will
/// be removed from the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
///
/// <remarks>
/// If the entity is already tracked in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state then the context will
/// stop tracking the entity (rather than marking it as <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/>) since the
/// entity was previously added to the context and does not exist in the database.
///
/// </remarks>
/// <typeparam name="TEntity">The type of the entity. </typeparam><param name="entity">The entity to remove. </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry`1"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry<TEntity> Remove<TEntity>([NotNull] TEntity entity) where TEntity : class;
/// <summary>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state such that it will
/// be inserted into the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <param name="entity">The entity to add. </param><param name="behavior">Determines whether the context will bring in only the given entity or also other related entities.
/// </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry Add([NotNull] object entity, GraphBehavior behavior = GraphBehavior.IncludeDependents);
/// <summary>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/> state such that no
/// operation will be performed when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <param name="entity">The entity to attach. </param><param name="behavior">Determines whether the context will bring in only the given entity or also other related entities.
/// </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry Attach([NotNull] object entity, GraphBehavior behavior = GraphBehavior.IncludeDependents);
/// <summary>
///
/// <para>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Modified"/> state such that it will
/// be updated in the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </para>
///
/// <para>
/// All properties of the entity will be marked as modified. To mark only some properties as modified, use
/// <see cref="M:Microsoft.Data.Entity.DbContext.Attach(System.Object,Microsoft.Data.Entity.GraphBehavior)"/> to begin tracking the entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/>
/// state and then use the returned <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> to mark the desired properties as modified.
///
/// </para>
///
/// </summary>
/// <param name="entity">The entity to update. </param><param name="behavior">Determines whether the context will bring in only the given entity or also other related entities.
/// </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry Update([NotNull] object entity, GraphBehavior behavior = GraphBehavior.IncludeDependents);
/// <summary>
/// Begins tracking the given entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/> state such that it will
/// be removed from the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
///
/// <remarks>
/// If the entity is already tracked in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state then the context will
/// stop tracking the entity (rather than marking it as <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/>) since the
/// entity was previously added to the context and does not exist in the database.
///
/// </remarks>
/// <param name="entity">The entity to remove. </param>
/// <returns>
/// The <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> for the entity. The entry provides
/// access to change tracking information and operations for the entity.
///
/// </returns>
EntityEntry Remove([NotNull] object entity);
/// <summary>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state such that they will
/// be inserted into the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <param name="entities">The entities to add. </param>
void AddRange([NotNull] params object[] entities);
/// <summary>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/> state such that no
/// operation will be performed when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <param name="entities">The entities to attach. </param>
void AttachRange([NotNull] params object[] entities);
/// <summary>
///
/// <para>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Modified"/> state such that they will
/// be updated in the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </para>
///
/// <para>
/// All properties of the entities will be marked as modified. To mark only some properties as modified, use
/// <see cref="M:Microsoft.Data.Entity.DbContext.Attach(System.Object,Microsoft.Data.Entity.GraphBehavior)"/> to begin tracking each entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/>
/// state and then use the returned <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> to mark the desired properties as modified.
///
/// </para>
///
/// </summary>
/// <param name="entities">The entities to update. </param>
void UpdateRange([NotNull] params object[] entities);
/// <summary>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/> state such that they will
/// be removed from the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
///
/// <remarks>
/// If any of the entities are already tracked in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state then the context will
/// stop tracking those entities (rather than marking them as <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/>) since those
/// entities were previously added to the context and do not exist in the database.
///
/// </remarks>
/// <param name="entities">The entities to remove. </param>
void RemoveRange([NotNull] params object[] entities);
/// <summary>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state such that they will
/// be inserted into the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <param name="entities">The entities to add. </param><param name="behavior">Determines whether the context will bring in only the given entities or also other related entities.
/// </param>
void AddRange([NotNull] IEnumerable<object> entities, GraphBehavior behavior = GraphBehavior.IncludeDependents);
/// <summary>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/> state such that no
/// operation will be performed when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
/// <param name="entities">The entities to attach. </param><param name="behavior">Determines whether the context will bring in only the given entities or also other related entities.
/// </param>
void AttachRange([NotNull] IEnumerable<object> entities, GraphBehavior behavior = GraphBehavior.IncludeDependents);
/// <summary>
///
/// <para>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Modified"/> state such that they will
/// be updated in the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </para>
///
/// <para>
/// All properties of the entities will be marked as modified. To mark only some properties as modified, use
/// <see cref="M:Microsoft.Data.Entity.DbContext.Attach(System.Object,Microsoft.Data.Entity.GraphBehavior)"/> to begin tracking each entity in the <see cref="F:Microsoft.Data.Entity.EntityState.Unchanged"/>
/// state and then use the returned <see cref="T:Microsoft.Data.Entity.ChangeTracking.EntityEntry"/> to mark the desired properties as modified.
///
/// </para>
///
/// </summary>
/// <param name="entities">The entities to update. </param><param name="behavior">Determines whether the context will bring in only the given entities or also other related entities.
/// </param>
void UpdateRange([NotNull] IEnumerable<object> entities, GraphBehavior behavior = GraphBehavior.IncludeDependents);
/// <summary>
/// Begins tracking the given entities in the <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/> state such that they will
/// be removed from the database when <see cref="M:Microsoft.Data.Entity.DbContext.SaveChanges"/> is called.
///
/// </summary>
///
/// <remarks>
/// If any of the entities are already tracked in the <see cref="F:Microsoft.Data.Entity.EntityState.Added"/> state then the context will
/// stop tracking those entities (rather than marking them as <see cref="F:Microsoft.Data.Entity.EntityState.Deleted"/>) since those
/// entities were previously added to the context and do not exist in the database.
///
/// </remarks>
/// <param name="entities">The entities to remove. </param>
void RemoveRange([NotNull] IEnumerable<object> entities);
/// <summary>
/// Creates a <see cref="T:Microsoft.Data.Entity.DbSet`1"/> that can be used to query and save instances of <typeparamref name="TEntity"/>.
///
/// </summary>
/// <typeparam name="TEntity">The type of entity for which a set should be returned. </typeparam>
/// <returns>
/// A set for the given entity type.
/// </returns>
DbSet<TEntity> Set<TEntity>() where TEntity : class;
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Net;
using System.IO;
using System.Text;
namespace Microsoft.Zelig.Test
{
public class FunctionalTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
try
{
// Check networking - we need to make sure we can reach our proxy server
Dns.GetHostEntry(HttpTests.Proxy);
}
catch (Exception ex)
{
Log.Exception("Unable to get address for " + HttpTests.Proxy, ex);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
public override TestResult Run( string[] args )
{
return TestResult.Pass;
}
//--//
//--//
//--//
[TestMethod]
public TestResult VisitMicrosoft()
{
try
{
Log.Comment("Small web page - redirect");
// Print for now, Parse later
string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.microsoft.com", "IIS")));
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult VisitNYTimes()
{
try
{
Log.Comment("SUN web page");
// Print for now, Parse later
string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.nytimes.com", "SUN", "APACHE")));
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult VisitApache()
{
try
{
Log.Comment("Apache Web server");
// Print for now, Parse later
string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.apache.org", "Apache")));
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult VisitGoogle()
{
try
{
Log.Comment("Google Web server");
// Print for now, Parse later
string data = new string(Encoding.UTF8.GetChars(GetRequested("http://www.google.com", "GWS")));
}
catch (ArgumentException) { /* Don't care if google doesn't return wrong header, happens at major 'holidays' like april 1 */ }
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
return TestResult.Fail;
}
return TestResult.Pass;
}
[TestMethod]
public TestResult VisitLighttpd()
{
try
{
Log.Comment("Lighttpd Web server");
// Print for now, Parse later
string data = new string(Encoding.UTF8.GetChars(GetRequested("http://redmine.lighttpd.net", "Lighttpd")));
}
catch (Exception ex)
{
Log.Exception("Unexpected Exception", ex);
return TestResult.Fail;
}
return TestResult.Pass;
}
private byte[] GetRequested(string uri, params string[] servers)
{
byte[] page = null;
// Create request.
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
// Set proxy information
WebProxy itgProxy = new WebProxy(HttpTests.Proxy, true);
request.Proxy = itgProxy;
// Get response from server.
WebResponse resp = null;
try
{
resp = request.GetResponse();
}
catch (Exception e)
{
Log.Exception("GetResponse Exception", e);
throw e;
}
try
{
// Get Network response stream
if (resp != null)
{
Log.Comment("Headers - ");
foreach (string header in resp.Headers.AllKeys)
{
Log.Comment(" " + header + ": " + resp.Headers[header]);
}
using (Stream respStream = resp.GetResponseStream())
{
// Get all data:
if (resp.ContentLength != -1)
{
int respLength = (int)resp.ContentLength;
page = new byte[respLength];
// Now need to read all data. We read in the loop until resp.ContentLength or zero bytes read.
// Zero bytes read means there was error on server and it did not send all data.
for (int totalBytesRead = 0; totalBytesRead < respLength; )
{
int bytesRead = respStream.Read(page, totalBytesRead, respLength - totalBytesRead);
// If nothing is read - means server closed connection or timeout. In this case no retry.
if (bytesRead == 0)
{
break;
}
// Adds number of bytes read on this iteration.
totalBytesRead += bytesRead;
}
}
else
{
byte[] byteData = new byte[4096];
char[] charData = new char[4096];
string data = null;
int bytesRead = 0;
Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder();
int totalBytes = 0;
while ((bytesRead = respStream.Read(byteData, 0, byteData.Length)) > 0)
{
int byteUsed, charUsed;
bool completed = false;
totalBytes += bytesRead;
UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0, bytesRead, true, out byteUsed, out charUsed, out completed);
data = data + new String(charData, 0, charUsed);
Log.Comment("Bytes Read Now: " + bytesRead + " Total: " + totalBytes);
}
Log.Comment("Total bytes downloaded in message body : " + totalBytes);
page = Encoding.UTF8.GetBytes(data);
}
Log.Comment("Page downloaded");
respStream.Close();
}
bool fFoundExpectedServer = false;
string httpServer = resp.Headers["server"].ToLower();
foreach(string server in servers)
{
if (httpServer.IndexOf(server.ToLower()) >= 0)
{
fFoundExpectedServer = true;
break;
}
}
if(!fFoundExpectedServer)
{
Log.Exception("Expected server: " + servers[0] + ", but got server: " + resp.Headers["Server"]);
throw new ArgumentException("Unexpected Server type");
}
resp.Close();
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception processing response", ex);
throw ex;
}
return page;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MiniOa.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
Copyright (c) 2012-2015, Coherent Labs AD
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 Coherent UI nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Coherent.UI.Mobile.Binding;
namespace Coherent.UI.Binding
{
struct Sequence
{
private long Size;
public void Begin(ValueType type, long size, BlobWriter blob)
{
Size = blob.WriteRaw((System.UInt64)type);
blob.WriteRaw(0UL);
blob.WriteRaw((System.UInt64)size);
}
public void Finish(BlobWriter blob)
{
var bytes = blob.GetBytesCount() - Size;
blob.WriteAt((System.UInt64)bytes, Size);
}
}
internal class BlobWriter
{
System.IO.MemoryStream Stream;
System.IO.BinaryWriter Writer;
System.Collections.Generic.Stack<Sequence> Sequences;
public BlobWriter()
{
Stream = new System.IO.MemoryStream(256);
Writer = new System.IO.BinaryWriter(Stream);
Sequences = new System.Collections.Generic.Stack<Coherent.UI.Binding.Sequence>();
}
public byte[] GetBytes()
{
return Stream.GetBuffer();
}
public long GetBytesCount()
{
return Stream.Position;
}
public void WriteNull()
{
Writer.Write((System.UInt64)ValueType.Null);
Writer.Write((System.UInt64)0);
}
public void Write(bool value)
{
WritePrimitive(ValueType.Boolean, (value)? 1L : 0L);
}
public void Write(int value)
{
WritePrimitive(ValueType.Integer, (System.Int64)value);
}
public void Write(uint value)
{
WritePrimitive(ValueType.UInteger, (System.Int64)value);
}
public void Write(sbyte value)
{
WritePrimitive(ValueType.SByte, (System.Int64)value);
}
public void Write(byte value)
{
WritePrimitive(ValueType.Byte, (System.Int64)value);
}
public void Write(float value)
{
Write((double)value);
}
public void Write(double value)
{
Writer.Write((System.UInt64)ValueType.Number);
Writer.Write(value);
}
private char[] m_CharBuffer = new char[64];
private byte[] m_ByteBuffer = new byte[64];
private byte[] m_Padding = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
public void Write(string value)
{
Writer.Write((System.UInt64)ValueType.String);
var length = 0L;
var valueLength = value.Length;
if (m_CharBuffer.Length < valueLength)
{
m_CharBuffer = new char[valueLength];
m_ByteBuffer = new byte[valueLength];
}
bool isAscii = true;
for (var i = 0; i < valueLength && isAscii; ++i)
{
var b = (int)value[i];
if (b < 0x80)
{
m_ByteBuffer[i] = (byte)b;
}
else
{
isAscii = false;
}
}
if (isAscii)
{
Writer.Write((ulong)valueLength);
length = valueLength;
Writer.Write(m_ByteBuffer, 0, valueLength);
}
else
{
var lengthPosition = Stream.Position;
Writer.Write(0UL);
value.CopyTo(0, m_CharBuffer, 0, valueLength);
Writer.Write(m_CharBuffer, 0, valueLength);
length = Stream.Position - lengthPosition - 8;
WriteAt((ulong)length, lengthPosition);
}
var actualBytes = (((length + 8) - 1) / 8) * 8;
Writer.Write(m_Padding, 0, (int)(actualBytes - length));
}
internal long WriteRaw(System.UInt64 value)
{
Writer.Write(value);
return Stream.Position;
}
internal void WriteAt(System.UInt64 value, long position)
{
var oldPosition = Stream.Position;
Writer.Seek((int)position, System.IO.SeekOrigin.Begin);
Writer.Write(value);
Writer.Seek((int)oldPosition, System.IO.SeekOrigin.Begin);
}
private void WritePrimitive(ValueType type, System.Int64 value)
{
Writer.Write((System.UInt64)type);
Writer.Write(value);
}
public void BeginSequence(ValueType type, long size)
{
var sequence = new Sequence();
sequence.Begin(type, size, this);
Sequences.Push(sequence);
}
public void EndSequence()
{
var sequence = Sequences.Pop();
sequence.Finish(this);
}
internal void Reset()
{
Stream.Position = 0;
}
}
}
| |
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.Principal;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using DirectShowLib;
namespace AgreementTrac
{
public partial class AgreementTrac : Form
{
#region Imports
[DllImport("user32.dll")]
public static extern int SendMessage(
IntPtr hWnd, // handle to destination window
int Msg, // message
IntPtr wParam, // first message parameter
IntPtr lParam // second message parameter
);
[DllImport("User32.Dll")]
public static extern int SendNotifyMessage(IntPtr hWnd, int msg, int wParam, int lParam);
#endregion
#region Enums
enum PlayState
{
Stopped,
Paused,
Running,
Init
};
#endregion
#region Constants
public const int WM_GRAPHNOTIFY = 0x8000 + 1;
public const int WM_SAVE_STARTED = 0x0400;
public const int WM_SAVE_COMPLETED = 0x0401;
public const int WM_CLOSE = 0x10;
//private const string HKEY_ROOT = "HKEY_LOCAL_MACHINE\\Software";
//private const string KEY_APPNAME = "AgreementTrac";
//private const string KEY_NAME = HKEY_ROOT + "\\" + KEY_APPNAME;
//private const string KEY_INSTALL_DATE = "Install Date";
//private const string KEY_COMPANY_NAME = "Company Name";
//private const string KEY_PRODUCT_KEY = "Product Key";
//private const string KEY_LICENSE_COUNT = "License Count";
//private const string KEY_SERIAL_NUMBER = "Serial Number";
#endregion
#region Private Fields
SavingDlg m_sd = null;
PlayState m_enCurrentState = PlayState.Stopped;
FilterState m_FilterState = FilterState.Stopped;
IMediaControl m_MediaControl = null;
IMediaEventEx m_MediaEventEx = null;
IVideoWindow m_videoWindow = null;
CCapture m_CaptureObjForPreview = null;
CCapture m_CaptureObjForCapture = null;
DsDevice[] m_videoCapDevices = null;
DsDevice[] m_audioCapDevices = null;
ConfigSettings csPersistedSettings = null;
ConfigSettings csChangedSettings = null;
CDealInfo DealInfo = null;
string m_sSaveFilePath = string.Empty;
string m_sCaptureFileName = string.Empty;
string m_sConfigPath = string.Empty;
string m_sUserName = string.Empty;
string m_sComputerName = string.Empty;
string m_sDomainName = string.Empty;
string m_sIPAddress = string.Empty;
bool m_bAdmin = false;
bool m_bDataDirty = false;
IntPtr m_pHwnd;
//string m_sCompanyName = string.Empty;
//string m_sProductKey = string.Empty;
//long m_nLicenseCount = 0;
//string m_sSerialNumber = string.Empty;
#endregion
public AgreementTrac()
{
InitializeComponent();
m_pHwnd = this.Handle;
// Setup directory information
string sDir = System.Reflection.Assembly.GetExecutingAssembly().Location;
string sLowerDir = sDir.ToLower();
int nIndex = sLowerDir.LastIndexOf("\\");
if (nIndex >= 0)
sLowerDir = sLowerDir.Substring(0, nIndex);
m_sConfigPath = sLowerDir;
// Enable Tracer class
Tracer.SetupTracing(m_sConfigPath);
//bool bResult = false;
//bResult = SetRegistryKeys();
//Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "SetRegistryKeys() returned result: " + bResult.ToString());
//CheckEvalStatus();
// Initialize settings objects
csPersistedSettings = new ConfigSettings(); // object for holding values from config file
GetConfigurationInfo();
GetSystemInfo();
csChangedSettings = new ConfigSettings(csPersistedSettings);
if (UserIsAdmin())
{
SetPreviewOrConfigButtonStates();
panelVideo.Visible = true;
cboVideoDevices.Enabled = true;
cboAudioDevices.Enabled = true;
txtOutputDirectory.Enabled = true;
txtDealershipName.Enabled = true;
btnSaveConfig.Visible = true;
btnBrowse.Visible = true;
chkAppendUserName.Enabled = true;
txtSQLServer.Enabled = true;
txtDatabaseName.Enabled = true;
chkUseSQLAuth.Enabled = true;
if (chkUseSQLAuth.Checked)
{
txtSqlUser.Enabled = true;
txtPassword.Enabled = true;
}
btnSaveConfig.Enabled = m_bDataDirty;
btnCancel.Enabled = false;
}
toolTip1.SetToolTip(chkAppendUserName, "Selecting this check box will append the\r\ncurrently logged in username to the output path.");
LoadCaptureSettings();
SetupSaveFilePath();
}
#region Public Properties
public string ManagerName
{
get { return m_sUserName; }
}
public string IP_Address
{
get { return m_sIPAddress; }
}
public string ComputerName
{
get { return m_sComputerName; }
}
#endregion
#region Button Methods
private void NewDealPreviewLoad()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered NewDealPreviewLoad() Method.");
CloseInterfaces();
string sError = string.Empty;
int hr = 0;
try
{
if (m_CaptureObjForPreview == null)
m_CaptureObjForPreview = new CCapture(GetVideoDevice(csChangedSettings.VideoDevice), GetAudioDevice(csChangedSettings.AudioDevice));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
CloseInterfaces();
return;
}
if (m_MediaControl == null)
m_MediaControl = (IMediaControl)m_CaptureObjForPreview.m_FilterGraph;
if (m_videoWindow == null)
m_videoWindow = (IVideoWindow)m_CaptureObjForPreview.m_FilterGraph;
if (m_MediaEventEx == null)
{
m_MediaEventEx = (IMediaEventEx)m_CaptureObjForPreview.m_FilterGraph;
hr = m_MediaEventEx.SetNotifyWindow(pnlNewDealPreview.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
sError = DsError.GetErrorText(hr);
if (hr != 0)
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tSetNotifyWindow failed with message: " + sError);
DsError.ThrowExceptionForHR(hr);
SetupVideoWindow(true);
}
if (m_FilterState == FilterState.Stopped)
hr = m_MediaControl.Run();
m_MediaControl.GetState(5, out m_FilterState);
sError = DsError.GetErrorText(hr);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tMediaControl.Run() failed with message: " + sError);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tThe previous error can safely be ignored unless other errors are occurring.");
m_enCurrentState = PlayState.Running;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting NewDealPreviewLoad() Method.\r\n");
}
private void btnPreview_Click(object sender, EventArgs e)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered btnPreview_Click() Method.");
string sError = string.Empty;
if (btnPreview.Text == "Stop")
{
btnPreview.Text = "Preview";
while (m_FilterState != FilterState.Stopped)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tAttempting to stop MediaControl");
btnPreview.Enabled = false;
m_MediaControl.StopWhenReady();
m_MediaControl.GetState(0, out m_FilterState);
}
CloseInterfaces();
btnPreview.Enabled = true;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting btnPreview_Click() Method after stopping preview.\r\n");
return;
}
if (cboVideoDevices.SelectedIndex < 0)
{
MessageBox.Show("Please select a video capture device before trying to preview.",
"No Video Device Selected", MessageBoxButtons.OK);
cboVideoDevices.Focus();
}
else
{
int hr = 0;
try
{
if (m_CaptureObjForPreview == null)
m_CaptureObjForPreview = new CCapture(GetVideoDevice(csChangedSettings.VideoDevice), GetAudioDevice(csChangedSettings.AudioDevice));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
CloseInterfaces();
return;
}
if (m_MediaControl == null)
m_MediaControl = (IMediaControl)m_CaptureObjForPreview.m_FilterGraph;
if (m_videoWindow == null)
m_videoWindow = (IVideoWindow)m_CaptureObjForPreview.m_FilterGraph;
if (m_MediaEventEx == null)
{
m_MediaEventEx = (IMediaEventEx)m_CaptureObjForPreview.m_FilterGraph;
hr = m_MediaEventEx.SetNotifyWindow(pnlVideoPreview.Handle, WM_GRAPHNOTIFY, IntPtr.Zero);
sError = DsError.GetErrorText(hr);
if (hr != 0)
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tSetNotifyWindow failed with message: " + sError);
DsError.ThrowExceptionForHR(hr);
SetupVideoWindow(false);
}
if (m_FilterState == FilterState.Stopped)
hr = m_MediaControl.Run();
m_MediaControl.GetState(5, out m_FilterState);
sError = DsError.GetErrorText(hr);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tMediaControl.Run() failed with message: " + sError);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tThe previous error can safely be ignored unless other errors are occurring.");
m_enCurrentState = PlayState.Running;
btnPreview.Text = "Stop";
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting btnPreview_Click() Method.\r\n");
}
}
private void btnNewDeal_Click(object sender, EventArgs e)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered btnNewDeal_Click() method.");
// Test connection string
btnTestSQLConn_Click(null, null);
if (m_bDataDirty && !m_bAdmin)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tApplication needs re-configured by Admin.");
MessageBox.Show("Configuration is invalid. Please have an Admin reconfigure the application. Application will now exit.", "Configuration Error", MessageBoxButtons.OK);
Environment.Exit(0);
}
else if (m_bDataDirty)
{
MessageBox.Show("Configuration is invalid. Please reconfigure the application.", "Configuration Error", MessageBoxButtons.OK);
if (!panelVideo.Visible)
panelVideo.Visible = true;
return;
}
ResetDataFieldsAndDestroyObjects();
SetDataFieldsEnabledValueTo(true);
// Instantiate Data Object
InitDataObjects();
txtManagerName.Text = this.ManagerName;
txtDealerName.Text = csChangedSettings.Dealership;
panelDealInfo.Visible = true;
if (panelVideo.Visible)
panelVideo.Visible = false;
InitNewDealButtonStates();
NewDealPreviewLoad();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting btnNewDeal_Click() method.");
}
private void btnSearch_Click(object sender, EventArgs e)
{
}
private void btnSaveConfig_Click(object sender, EventArgs e)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered btnSaveConfig() Method.");
if (m_FilterState != FilterState.Stopped || m_CaptureObjForPreview != null)
{
btnPreview.Enabled = false;
btnPreview.Text = "Preview";
CloseInterfaces();
btnPreview.Enabled = true;
}
if (csChangedSettings.UseSQLAuthentication && (txtSqlUser.Text != string.Empty && txtPassword.Text != string.Empty))
{
// create SQL Connection string
csChangedSettings.SQLConnectionString = CreateConnectionString(csChangedSettings.SqlServer, csChangedSettings.SQLUserName, csChangedSettings.Password);
}
else if (txtSQLServer.Text != string.Empty && !chkUseSQLAuth.Checked)
{
csChangedSettings.SQLConnectionString = CreateConnectionString(csChangedSettings.SqlServer, "", "");
}
if (cboVideoDevices.SelectedIndex < 0 || cboAudioDevices.SelectedIndex < 0 ||
txtOutputDirectory.Text == string.Empty || txtDealershipName.Text == string.Empty ||
txtSQLServer.Text == string.Empty || txtDatabaseName.Text == string.Empty)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tEnter values for all fields before saving config.");
MessageBox.Show("Please enter values for all fields before saving configuration.", "Configuration values missing.", MessageBoxButtons.OK);
if (txtDealershipName.Text == string.Empty)
txtDealershipName.Focus();
else if (cboVideoDevices.SelectedIndex < 0)
cboVideoDevices.Focus();
else if (cboAudioDevices.SelectedIndex < 0)
cboAudioDevices.Focus();
else if (txtOutputDirectory.Text == string.Empty)
txtOutputDirectory.Focus();
else if (txtSQLServer.Text == string.Empty)
txtSQLServer.Focus();
else
txtDatabaseName.Focus();
}
else if (csChangedSettings.UseSQLAuthentication && (txtSqlUser.Text == string.Empty || txtPassword.Text == string.Empty))
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tAdmin failed to enter SQL username or password.");
MessageBox.Show("SQL Authentication requires a valid user name and password.\r\nPlease ensure both values are filled in.", "Configuration values missing.", MessageBoxButtons.OK);
txtSqlUser.Focus();
return;
}
else if ( !System.IO.Directory.Exists(txtOutputDirectory.Text) )
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tOutput directory doesn't exist or format invalid.");
DialogResult dr = MessageBox.Show("Path: " + txtOutputDirectory.Text + " doesn't exist or is invalid.\r\nWould you like to try to create it?", "Invalid Output Path", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
try
{
System.IO.Directory.CreateDirectory(txtOutputDirectory.Text);
}
catch (DirectoryNotFoundException ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tDirectoryNotFoundException encountered. Message: " + ex.Message);
MessageBox.Show(ex.Message);
txtOutputDirectory.Focus();
}
catch (Exception ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tUnhandled exception occurred. Message: " + ex.Message);
MessageBox.Show(ex.Message);
txtOutputDirectory.Focus();
}
}
else
{
txtOutputDirectory.Focus();
}
}
else
{
try
{
// Lets write the configuration file
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tStarting to save configuration file.");
string sFilePath = m_sConfigPath + Path.DirectorySeparatorChar + "AppSettings.xml";
XmlDocument doc = new XmlDocument();
doc.Load(sFilePath);
XmlNodeList nodeList = doc.SelectNodes("/Configuration");
foreach (XmlNode n in nodeList)
{
if (n.HasChildNodes)
{
XmlNode vidNode = n.SelectSingleNode("descendant::VideoCaptureDevice");
vidNode.InnerText = csChangedSettings.VideoDevice = cboVideoDevices.Text;
XmlNode audNode = n.SelectSingleNode("descendant::AudioCaptureDevice");
audNode.InnerText = csChangedSettings.AudioDevice = cboAudioDevices.Text;
XmlNode outputNode = n.SelectSingleNode("descendant::OutputDirectory");
outputNode.InnerText = csChangedSettings.OutputDirectory = txtOutputDirectory.Text;
XmlNode appendUserNode = n.SelectSingleNode("descendant::AppendUserNameToOutput");
csChangedSettings.AppendUserName = chkAppendUserName.Checked;
appendUserNode.InnerText = csChangedSettings.AppendUserName.ToString();
XmlNode dealershipName = n.SelectSingleNode("descendant::DealershipName");
dealershipName.InnerText = csChangedSettings.Dealership = txtDealershipName.Text;
XmlNode xnSQLServer = n.SelectSingleNode("descendant::SQLServerInstance");
xnSQLServer.InnerText = csChangedSettings.SqlServer = txtSQLServer.Text;
XmlNode xnDatabaseName = n.SelectSingleNode("descendant::DatabaseName");
xnDatabaseName.InnerText = csChangedSettings.DatabaseName = txtDatabaseName.Text;
XmlNode xnUseSQLAuth = n.SelectSingleNode("descendant::UseSQLAuthentication");
csChangedSettings.UseSQLAuthentication = chkUseSQLAuth.Checked;
xnUseSQLAuth.InnerText = csChangedSettings.UseSQLAuthentication.ToString();
XmlNode xnSQLConnectionString = n.SelectSingleNode("descendant::SQLConnectionString");
byte[] baConnString = Encoding.ASCII.GetBytes(csChangedSettings.SQLConnectionString);
byte[] baPrivateKey = Encoding.ASCII.GetBytes("e");
baConnString = MangleConnString(baConnString, baPrivateKey);
xnSQLConnectionString.InnerText = Encoding.ASCII.GetString(baConnString);
}
}
doc.Save(sFilePath);
btnSaveConfig.Enabled = m_bDataDirty = false; // may not need bDataDirty flag?
if (!btnPreview.Enabled)
btnPreview.Enabled = true;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSave configuration file succeeded.");
}
catch (XmlException ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tSaving configuration file failed with message: " + ex.Message);
MessageBox.Show("XmlException Occurred accessing configuration file. Please review log file for more information.",
"XmlException Occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
csPersistedSettings = null;
csPersistedSettings = new ConfigSettings(csChangedSettings);
SetupSaveFilePath();
btnTestSQLConn_Click(null, null);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting btnSaveConfig() Method.");
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult dr = folderBrowserDialog.ShowDialog();
if (dr == DialogResult.Cancel)
{
txtOutputDirectory.Text = txtOutputDirectory.Text;
}
else
{
txtOutputDirectory.Text = folderBrowserDialog.SelectedPath;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Trace.Close();
Application.ExitThread();
}
private void btnCancel_Click(object sender, EventArgs e)
{
btnNewDeal_Click(null, null);
}
private void btnTestSQLConn_Click(object sender, EventArgs e)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered btnTestSQLConn_Click() method.");
bool bExceptionCaught = false;
System.Data.SqlClient.SqlConnection sConn = null;
try
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tBegin testing SQL Connection.");
sConn = new System.Data.SqlClient.SqlConnection(csChangedSettings.SQLConnectionString);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tBegin opening SQLConnection.");
sConn.Open();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tOpen SQL Connection successful.");
SqlCommand cmd = sConn.CreateCommand();
cmd.CommandText = @"SELECT count(name) FROM master.dbo.sysdatabases WHERE name = N'" + csChangedSettings.DatabaseName + "'";
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tBegin ExecuteScalar() to test if database exists.");
Int32 i = (Int32)cmd.ExecuteScalar();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tExecuteScalar() succeeded. SELECT query returned count: " + i.ToString());
if ( i == 0 )
{
if (m_bAdmin)
{
// create database
cmd.CommandText = @"CREATE DATABASE " + csChangedSettings.DatabaseName + "";
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tBegin ExecuteNonQuery to create database.");
cmd.ExecuteNonQuery();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCreate Database succeeded.");
}
else
{
// Database doesn't exist. Admin needs to run application to create DB
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tDatabase doesn't exist. Please run as Admin to create database.");
MessageBox.Show("Configured database doesn't exist, or SQL error occurred. Please have an admin reconfigure. Application will now exit.",
"Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Trace.Close();
if (sConn != null && sConn.State != System.Data.ConnectionState.Closed)
sConn.Close();
Environment.Exit(0);
}
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tTry to change connection to " + csChangedSettings.DatabaseName + ".");
sConn.ChangeDatabase(csChangedSettings.DatabaseName);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tChanged to " + csChangedSettings.DatabaseName + " succeeded.");
if (m_bAdmin)
{
TextReader tr = new StreamReader(m_sConfigPath + Path.DirectorySeparatorChar + "DBValidate.sql");
cmd.CommandText = tr.ReadToEnd();
tr.Close();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tAttempting to Validate DB tables.");
cmd.ExecuteNonQuery();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tValidate DB tables succeeded.");
}
else
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tUser is not admin, assume database is ok.");
}
if (sender != null) // called from loading NewDeal screen
MessageBox.Show("Connection Test Successful.", "Success", MessageBoxButtons.OK);
}
catch (ArgumentException ex)
{
bExceptionCaught = true;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tArgumentExeption caught. Message: " + ex.Message);
}
catch (System.Data.SqlClient.SqlException ex)
{
bExceptionCaught = true;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tSQLException caught. Message: " + ex.Message);
}
catch (InvalidOperationException ex)
{
bExceptionCaught = true;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tInvalidOperationExeption caught, Problem with Connection string. Message: " + ex.Message);
}
catch (Exception ex)
{
bExceptionCaught = true;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tUnexpected Exeption caught. Message: " + ex.Message);
}
finally
{
if (bExceptionCaught)
{
if (!m_bAdmin)
{
MessageBox.Show("There was a problem with the configuration. Please have an Admin re-configure the application. The application will now exit.");
Trace.Close();
Application.ExitThread();
}
else
{
MessageBox.Show("Something went wrong with the SQL connection. Please reconfigure and save settings.", "Error Connecting", MessageBoxButtons.OK);
btnSaveConfig.Enabled = m_bDataDirty = true;
if (!panelVideo.Visible)
panelVideo.Visible = true;
}
}
if (sConn != null && sConn.State == System.Data.ConnectionState.Open)
sConn.Close();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSQL Connection closed successfully.");
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting btnTestSQLConn_Click() method.");
}
private void btnStartRecording_Click(object sender, EventArgs e)
{
// check for required fields
if (txtLastName.Text == string.Empty || txtFirstName.Text == string.Empty ||
txtMake.Text == string.Empty || txtModel.Text == string.Empty || txtYear.Text == string.Empty ||
txtStockNumber.Text == string.Empty || txtDealNumber.Text == string.Empty)
{
MessageBox.Show("One or more required fields are missing. Please fill in the data correctly before starting recording.",
"Data Entry Error", MessageBoxButtons.OK);
return;
}
if (btnCancel.Enabled)
btnCancel.Enabled = false; // Do not allow canceling once recording has been initiated.
if (btnExit.Enabled)
btnExit.Enabled = false;
btnStartRecording.Enabled = false; // Disable this button so it cannot be selected again.
// Do not allow any changes to data fields
SetDataFieldsEnabledValueTo(false);
DealInfo.DealNumber = txtDealNumber.Text;
m_sCaptureFileName = DealInfo.customerInfo.LastName.Trim() + DealInfo.customerInfo.FirstName.Substring(0,1).Trim() + DealInfo.DealNumber.Trim() + ".asf";
DealInfo.videoInfo.VidFileName = m_sCaptureFileName;
DealInfo.videoInfo.VidSaveDir = m_sSaveFilePath;
DealInfo.TransactionDate = DateTime.Now;
bool bSucceeded = StartCapture(DealInfo.videoInfo.VidSaveDir + DealInfo.videoInfo.VidFileName);
if (!bSucceeded)
{
MessageBox.Show("Error occurred when trying to create capture object. Capture has been cancelled.");
SetDataFieldsEnabledValueTo(true);
btnStartRecording.Enabled = true;
btnCancel.Enabled = true;
}
else
{
// Allow the recording to be stopped.
// Capture should be setup by now. Errors can occur if user is
// allowed to cancel before capture is fully started.
btnStopRecording.Enabled = true;
}
}
private void btnStopRecording_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
m_sd = new SavingDlg();
m_sd.ShowDialog(this);
}
#endregion Button Methods
#region Supporting Methods
//private bool SetRegistryKeys()
//{
// bool bSuccess = true;
// object obj = null;
// // Get\Set Company Name registry key
// try
// {
// obj = Registry.GetValue(KEY_NAME, KEY_COMPANY_NAME, null);
// }
// catch (Exception ex)
// {
// Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Error getting registry value. Error message: " + ex.Message);
// bSuccess = false;
// }
// if (obj == null)
// {
// m_sCompanyName = "Evaluation";
// Registry.SetValue(KEY_NAME, KEY_COMPANY_NAME, m_sCompanyName);
// }
// else
// {
// m_sCompanyName = obj.ToString();
// }
// // Get\Set Product Key registry key
// obj = null;
// try
// {
// obj = Registry.GetValue(KEY_NAME, KEY_PRODUCT_KEY, null);
// }
// catch (Exception ex)
// {
// Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Error getting registry value. Error message: " + ex.Message);
// bSuccess = false;
// }
// if (obj == null)
// {
// m_sProductKey = string.Empty;
// Registry.SetValue(KEY_NAME, KEY_PRODUCT_KEY, "");
// }
// else
// {
// m_sProductKey = obj.ToString();
// }
// // Get\Set License count registry key
// obj = null;
// try
// {
// obj = Registry.GetValue(KEY_NAME, KEY_LICENSE_COUNT, null);
// }
// catch (Exception ex)
// {
// Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Error getting registry value. Error message: " + ex.Message);
// bSuccess = false;
// }
// if (obj == null)
// {
// m_nLicenseCount = 0;
// Registry.SetValue(KEY_NAME, KEY_LICENSE_COUNT, m_nLicenseCount, RegistryValueKind.DWord);
// }
// else
// {
// m_nLicenseCount = Convert.ToInt64(obj);
// }
// // Get\Set Serial Number registry key
// obj = null;
// try
// {
// obj = Registry.GetValue(KEY_NAME, KEY_SERIAL_NUMBER, null);
// }
// catch (Exception ex)
// {
// Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Error getting registry value. Error message: " + ex.Message);
// bSuccess = false;
// }
// if (obj == null)
// {
// m_sSerialNumber = string.Empty;
// Registry.SetValue(KEY_NAME, KEY_SERIAL_NUMBER, "");
// }
// else
// {
// m_sSerialNumber = obj.ToString();
// }
// return bSuccess;
//}
//private void CheckEvalStatus()
//{
// object objDate = null;
// TimeSpan tsInstallDate;
// TimeSpan tsToday;
// long nBinaryInstallDate = 0;
// try
// {
// objDate = Registry.GetValue(KEY_NAME, KEY_INSTALL_DATE, null);
// }
// catch (Exception ex)
// {
// Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Error getting registry value. Error message: " + ex.Message);
// }
// if (objDate == null)
// {
// nBinaryInstallDate = DateTime.Now.Date.ToBinary();
// Registry.SetValue(KEY_NAME, KEY_INSTALL_DATE, nBinaryInstallDate);
// }
// else
// {
// nBinaryInstallDate = Convert.ToInt64(objDate);
// }
// if (m_nLicenseCount <= 0) // Must be evaluation version
// {
// tsInstallDate = new TimeSpan(DateTime.FromBinary(nBinaryInstallDate).Ticks);
// tsToday = new TimeSpan(DateTime.Now.Date.Ticks);
// if ((30 - (tsToday.Days - tsInstallDate.Days)) < 0)
// {
// MessageBox.Show("Evaluation period has expired. Please uninstall the application. Program will now exit", "Evaluation Expired", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// Environment.Exit(0);
// }
// else
// {
// int nDaysLeft = (30 - (tsToday.Days - tsInstallDate.Days));
// if (nDaysLeft == 0)
// {
// MessageBox.Show("Day 30 of Evaluation period. Program will expire tomorrow.", "Evaluation expiration", MessageBoxButtons.OK, MessageBoxIcon.Information);
// }
// else
// {
// MessageBox.Show("Evaluation period will expire in " + nDaysLeft + " days.", "Evaluation expiration", MessageBoxButtons.OK, MessageBoxIcon.Information);
// }
// }
// }
//}
private void GetSystemInfo()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered GetSystemInfo() method.");
m_sUserName = SystemInformation.UserName;
m_sComputerName = SystemInformation.ComputerName;
m_sDomainName = SystemInformation.UserDomainName;
System.Net.IPAddress[] ipAddresses = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
foreach (System.Net.IPAddress ip in ipAddresses)
{
if ((ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) && (ip.ToString() != "127.0.0.1"))
{
if (ip.ToString().StartsWith("0"))
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Invalid IP. Value = " + ip.ToString());
continue;
}
m_sIPAddress = ip.ToString();
return;
}
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting GetSystemInfo() method.");
}
private bool UserIsAdmin()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered IsUserAdmin() Method.");
string sLocalAdminGroup = @"BUILTIN\Administrators";
string sDomainAdminGroup = m_sDomainName + @"\Domain Admins";
try
{
AppDomain myDomain = System.Threading.Thread.GetDomain();
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
if (myPrincipal.IsInRole(sLocalAdminGroup))
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tUser is in local Admin group. Setting m_bAdmin to 'true'.");
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tUserName: " + m_sUserName);
m_bAdmin = true;
}
else if (myPrincipal.IsInRole(sDomainAdminGroup))
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tUser is in Domain Admin group. Setting m_bAdmin to 'true'.");
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tDomainName: " + m_sDomainName + " UserName: " + m_sUserName);
m_bAdmin = true;
}
else
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tUser is not an Admin. Setting m_bAdmin to 'false'.");
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tUserName: " + m_sUserName);
m_bAdmin = false;
}
}
catch (Exception ex)
{
// Something went wrong with finding credentials
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tProblem occurred in GetUserInfo(). \r\n\tFailure message: " + ex.Message);
m_bAdmin = false;
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting IsUserAdmin() Method.\r\n");
return m_bAdmin;
}
private void LoadCaptureSettings()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered LoadCaptureSettings() Method.");
m_videoCapDevices = CCapture.GetVideoDevices();
m_audioCapDevices = CCapture.GetAudioDevices();
if (m_videoCapDevices != null)
{
foreach (DsDevice d in m_videoCapDevices)
{
cboVideoDevices.Items.Add(d.Name);
}
if (csChangedSettings.VideoDevice.Length > 0 && cboVideoDevices.Items.Contains(csChangedSettings.VideoDevice))
{
cboVideoDevices.Text = csChangedSettings.VideoDevice;
}
if ( !m_bAdmin && !(cboVideoDevices.Items.Contains(csChangedSettings.VideoDevice)) )
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tNot admin, and persisted video solution doesn't exist, please reconfigure.");
MessageBox.Show("Selected Video solution doesn't exist, please contact an Admin to re-configure. Application will now exit.", "Configuration Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Trace.Close();
Environment.Exit(0);
}
}
else
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tNo Video capture devices found...Exiting.");
System.Windows.Forms.MessageBox.Show("No Video Capture devices found. The application will now exit.");
Trace.Close();
Environment.Exit(0);
}
if (m_audioCapDevices != null)
{
foreach (DsDevice d in m_audioCapDevices)
{
cboAudioDevices.Items.Add(d.Name);
}
if (csChangedSettings.AudioDevice.Length > 0 && cboAudioDevices.Items.Contains(csChangedSettings.AudioDevice))
{
cboAudioDevices.Text = csChangedSettings.AudioDevice;
}
if (!m_bAdmin && !(cboAudioDevices.Items.Contains(csChangedSettings.AudioDevice)))
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tNot admin, and persisted audio solution doesn't exist, please reconfigure.");
MessageBox.Show("Selected Audio solution doesn't exist, please contact an Admin to re-configure. Application will now exit.", "Configuration Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Trace.Close();
Environment.Exit(0);
}
}
else
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tNo Audio capture devices found...Exiting.");
System.Windows.Forms.MessageBox.Show("No Audio Capture devices found. The application will now exit.");
Trace.Close();
Environment.Exit(0);
}
if (csChangedSettings.OutputDirectory != string.Empty)
{
txtOutputDirectory.Text = csChangedSettings.OutputDirectory;
}
if (csChangedSettings.Dealership != string.Empty)
{
txtDealershipName.Text = csChangedSettings.Dealership;
}
if (csChangedSettings.SqlServer != string.Empty)
{
txtSQLServer.Text = csChangedSettings.SqlServer;
}
if (csChangedSettings.DatabaseName != string.Empty)
{
txtDatabaseName.Text = csChangedSettings.DatabaseName;
}
if (csChangedSettings.UseSQLAuthentication)
{
chkUseSQLAuth.Checked = csChangedSettings.UseSQLAuthentication;
txtSqlUser.Text = csChangedSettings.SQLUserName;
txtPassword.Text = csChangedSettings.Password;
}
if (!m_bAdmin && (cboVideoDevices.Text == string.Empty ||
cboAudioDevices.Text == string.Empty ||
txtOutputDirectory.Text == string.Empty ||
txtDealershipName.Text == string.Empty ||
csChangedSettings.SQLConnectionString == string.Empty))
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tOne or more configuration values are null, check AppSettings.xml file");
MessageBox.Show("One or more configuration values are missing, please have an admin re-configure the application. The Application will now exit.", "Configuration Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
Trace.Close();
Environment.Exit(0);
}
chkAppendUserName.Checked = csChangedSettings.AppendUserName;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting LoadCaptureSettings() Method.\r\n");
}
private void SetupSaveFilePath()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Entered SetupSaveFilePath() method.");
// ensure that m_sSaveFilePath has a ending '/' character
if (csChangedSettings.AppendUserName)
{
// Need to append username to output path, and create it if it doesn't exist
if (csChangedSettings.OutputDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
m_sSaveFilePath = csChangedSettings.OutputDirectory + m_sUserName + Path.DirectorySeparatorChar;
else
m_sSaveFilePath = csChangedSettings.OutputDirectory + Path.DirectorySeparatorChar + m_sUserName +
Path.DirectorySeparatorChar;
}
else
{
if (csChangedSettings.OutputDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
m_sSaveFilePath = csChangedSettings.OutputDirectory;
else
m_sSaveFilePath = csChangedSettings.OutputDirectory + Path.DirectorySeparatorChar;
}
if (!System.IO.Directory.Exists(m_sSaveFilePath))
{
try
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tAttempt to create save file path.");
System.IO.Directory.CreateDirectory(m_sSaveFilePath);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSave file path created successfully.");
}
catch (DirectoryNotFoundException ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tDirectoryNotFoundException encountered. Message: " + ex.Message);
if (!m_bAdmin)
{
MessageBox.Show("Error creating save file path. Please have an Admin reconfigure the application. The application will now exit",
"Directory Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
Trace.Close();
Environment.Exit(0);
}
}
catch (Exception ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tUnhandled exception occurred. Message: " + ex.Message);
MessageBox.Show("Unexpected error occurred. Message: " + ex.Message + "\r\nApplication will now exit.");
Trace.Close();
Environment.Exit(0);
}
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Exiting SetupSaveFilePath() method.");
}
[FileIOPermission(SecurityAction.Assert)]
private void GetConfigurationInfo()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered GetConfigurationInfo() Method.");
string sAppSettingsPath = m_sConfigPath + Path.DirectorySeparatorChar + "AppSettings.xml";
FileInfo fiConfigFile = new FileInfo(sAppSettingsPath);
if (!fiConfigFile.Exists)
{
// If file doesn't exist, treat as new config.
try
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tAppSettings.xml file doesn't exist...Creating.");
XmlTextWriter xmlTextWriter = new XmlTextWriter(sAppSettingsPath, Encoding.Unicode);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.Indentation = 6;
xmlTextWriter.Namespaces = false;
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("", "Configuration", "");
xmlTextWriter.WriteStartElement("", "DealershipName", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "VideoCaptureDevice", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "AudioCaptureDevice", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "OutputDirectory", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "AppendUserNameToOutput", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "SQLServerInstance", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "DatabaseName", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "UseSQLAuthentication", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("", "SQLConnectionString", "");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteEndElement();
xmlTextWriter.Flush();
xmlTextWriter.Close();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tAppSettings.xml file created successfully.");
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSet Dirty Flag, so save button will be enabled.");
m_bDataDirty = true;
}
catch (Exception ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError,
"\tError occurred trying to create AppSettings file.\r\n\t Failed with message: " + ex.Message);
MessageBox.Show("Error occurred trying to create configuration file. Please review log file for more information. Program will now exit.",
"Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Trace.Close();
Environment.Exit(0);
}
}
else
{
// open file and get values
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tAppSettings.xml file exists...Getting values.");
try
{
XmlTextReader xmlReader = new XmlTextReader(sAppSettingsPath);
xmlReader.ReadStartElement("Configuration");
xmlReader.WhitespaceHandling = WhitespaceHandling.None;
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.LocalName.Equals("DealershipName"))
{
csPersistedSettings.Dealership = xmlReader.ReadString();
}
if (xmlReader.LocalName.Equals("VideoCaptureDevice"))
{
csPersistedSettings.VideoDevice = xmlReader.ReadString();
}
if (xmlReader.LocalName.Equals("AudioCaptureDevice"))
{
csPersistedSettings.AudioDevice = xmlReader.ReadString();
}
if (xmlReader.LocalName.Equals("OutputDirectory"))
{
csPersistedSettings.OutputDirectory = xmlReader.ReadString();
}
if (xmlReader.LocalName.Equals("AppendUserNameToOutput"))
{
string sChecked = xmlReader.ReadString().ToLower();
if (sChecked == "true")
csPersistedSettings.AppendUserName = true;
else
csPersistedSettings.AppendUserName = false;
}
if (xmlReader.LocalName.Equals("UseSQLAuthentication"))
{
string sChecked = xmlReader.ReadString().ToLower();
if (sChecked == "true")
csPersistedSettings.UseSQLAuthentication = true;
else
csPersistedSettings.UseSQLAuthentication = false;
}
if (xmlReader.LocalName.Equals("SQLServerInstance"))
{
csPersistedSettings.SqlServer = xmlReader.ReadString();
}
if (xmlReader.LocalName.Equals("DatabaseName"))
{
csPersistedSettings.DatabaseName = xmlReader.ReadString();
}
if (xmlReader.LocalName.Equals("SQLConnectionString"))
{
csPersistedSettings.SQLConnectionString = xmlReader.ReadString(); // will need to decrypt
byte[] baConnString = Encoding.ASCII.GetBytes(csPersistedSettings.SQLConnectionString);
byte[] baPrivateKey = Encoding.ASCII.GetBytes("e");
baConnString = MangleConnString(baConnString, baPrivateKey);
csPersistedSettings.SQLConnectionString = Encoding.ASCII.GetString(baConnString);
}
}
if (csPersistedSettings.UseSQLAuthentication)
{
string[] sConn = csPersistedSettings.SQLConnectionString.Split(Convert.ToChar(";"));
foreach (string s in sConn)
{
if (s.StartsWith("User Id"))
{
csPersistedSettings.SQLUserName = s.Substring(s.IndexOf("=") + 1);
}
else if (s.StartsWith("Password"))
{
csPersistedSettings.Password = s.Substring(s.IndexOf("=") + 1);
}
}
}
}
xmlReader.Close();
if (csPersistedSettings.Dealership == string.Empty || csPersistedSettings.VideoDevice == string.Empty ||
csPersistedSettings.AudioDevice == string.Empty || csPersistedSettings.OutputDirectory == string.Empty ||
csPersistedSettings.SqlServer == string.Empty || csPersistedSettings.DatabaseName == string.Empty ||
csPersistedSettings.SQLConnectionString == string.Empty)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tOne or more config values were missing.");
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSet Dirty Flag, so save button will be enabled.");
m_bDataDirty = true;
}
}
catch (Exception ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError,
"\tError occurred reading values from AppSettings file. \r\n\tFailed with message: " + ex.Message);
MessageBox.Show("Error occurred reading values from configuration file. Please review log file for more information. Program will now exit.",
"Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Trace.Close();
Environment.Exit(0);
}
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting GetConfigurationInfo() Method.\r\n");
}
private DsDevice GetVideoDevice(string sVideoCaptureDevice)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered GetVideoDevice() Method.");
DsDevice device = null;
foreach (DsDevice dev in m_videoCapDevices)
{
if (dev.Name == sVideoCaptureDevice)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tFound VideoCaptureDevice, returning device: " + dev.Name);
device = dev;
}
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting GetVideoDevice() Method.\r\n");
return device;
}
private DsDevice GetAudioDevice(string sAudioCaptureDevice)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered GetAudioDevice() Method.");
DsDevice device = null;
foreach (DsDevice dev in m_audioCapDevices)
{
if (dev.Name == sAudioCaptureDevice)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tFound AudioCaptureDevice, returning device: " + dev.Name);
device = dev;
}
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting GetAudioDevice() Method.\r\n");
return device;
}
private void InitDataObjects()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered InitDataObjects() method.");
DealInfo = new CDealInfo(csChangedSettings.SQLConnectionString, this.ManagerName, csChangedSettings.DatabaseName);
DealInfo.IP_Address = this.IP_Address;
DealInfo.ComputerName = this.ComputerName;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting InitDataObjects() method.");
}
private byte[] MangleConnString(byte[] baConnString, byte[] baPrivKey)
{
for (int i = 0; i < baConnString.Length; ++i)
{
int b = (int)baConnString[i];
int key = (int)baPrivKey[0];
int result = b ^ key;
baConnString[i] = (byte)result;
}
return baConnString;
}
private string CreateConnectionString(string sServerName, string sUserName, string sPassword)
{
string sConnString = string.Empty;
if (sUserName == string.Empty && sPassword == string.Empty)
{
// use integrated security "Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
return sConnString = string.Format("Data Source={0};Integrated Security=SSPI;", sServerName);
}
else
{
// use SQL Authentication "Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"
return sConnString = string.Format("Data Source={0};User Id={1};Password={2};",
sServerName, sUserName, sPassword);
}
}
private void CloseInterfaces()
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered CloseInterfaces() Method.");
try
{
if (m_MediaControl != null)
{
if (m_enCurrentState != PlayState.Stopped)
m_MediaControl.StopWhenReady();
m_MediaControl.GetState(0, out m_FilterState);
while (m_FilterState != FilterState.Stopped)
{
m_MediaControl.GetState(0, out m_FilterState);
}
}
// Stop receiving events
if (m_MediaEventEx != null)
m_MediaEventEx.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
// Relinquish ownership of video window
if (m_videoWindow != null)
{
m_videoWindow.put_Visible(OABool.False);
m_videoWindow.put_Owner(IntPtr.Zero);
}
m_enCurrentState = PlayState.Stopped;
if (m_MediaControl != null)
m_MediaControl = null;
if (m_MediaEventEx != null)
m_MediaEventEx = null;
if (m_videoWindow != null)
m_videoWindow = null;
if (m_CaptureObjForPreview != null)
{
m_CaptureObjForPreview.Dispose();
m_CaptureObjForPreview = null;
}
if (m_CaptureObjForCapture != null)
{
m_CaptureObjForCapture.Dispose();
m_CaptureObjForCapture = null;
}
}
catch (Exception ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tCloseInterfaces failed with message: " + ex.Message);
}
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting CloseInterfaces() Method.\r\n");
}
public void SetupVideoWindow(bool bNewDeal)
{
int hr = 0;
// Set the video window to be a child of the main window
if (bNewDeal)
hr = this.m_videoWindow.put_Owner(pnlNewDealPreview.Handle);
else
hr = this.m_videoWindow.put_Owner(pnlVideoPreview.Handle);
string sErrorText = DsError.GetErrorText(hr);
DsError.ThrowExceptionForHR(hr);
hr = this.m_videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren);
sErrorText = DsError.GetErrorText(hr);
DsError.ThrowExceptionForHR(hr);
ResizeVideoWindow(bNewDeal);
// Make the video window visible
hr = this.m_videoWindow.put_Visible(OABool.True);
sErrorText = DsError.GetErrorText(hr);
DsError.ThrowExceptionForHR(hr);
}
public void ResizeVideoWindow(bool bNewDeal)
{
if (this.m_videoWindow != null)
{
if (bNewDeal)
this.m_videoWindow.SetWindowPosition(0, 0, pnlNewDealPreview.ClientSize.Width, pnlNewDealPreview.ClientSize.Height);
else
this.m_videoWindow.SetWindowPosition(0, 0, pnlVideoPreview.ClientSize.Width, pnlVideoPreview.ClientSize.Height);
}
}
public void HandleGraphEvent()
{
int hr = 0;
EventCode evCode;
IntPtr evParam1, evParam2;
if (m_MediaEventEx == null)
return;
while (m_MediaEventEx.GetEvent(out evCode, out evParam1, out evParam2, 0) == 0)
{
// Free event parameters to prevent memory leaks associated with
// event parameter data. While this application is not interested
// in the received events, applications should always process them.
hr = m_MediaEventEx.FreeEventParams(evCode, evParam1, evParam2);
string sErrorText = DsError.GetErrorText(hr);
DsError.ThrowExceptionForHR(hr);
}
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_GRAPHNOTIFY:
{
HandleGraphEvent();
break;
}
case WM_SAVE_STARTED:
{
SetSaveStartedState();
break;
}
case WM_SAVE_COMPLETED:
{
SetSaveCompletedState();
break;
}
}
// Pass this message to the video window for notification of system changes
if (m_videoWindow != null)
m_videoWindow.NotifyOwnerMessage(m.HWnd, m.Msg, m.WParam, m.LParam);
base.WndProc(ref m);
}
private void SetSaveCompletedState()
{
this.btnStopRecording.Text = "Stop Recording";
btnNewDeal.Enabled = true;
btnExit.Enabled = true;
}
private void InitNewDealButtonStates()
{
btnStartRecording.Enabled = true;
btnNewDeal.Enabled = false;
btnCancel.Enabled = true;
btnSearch.Enabled = false;
btnStopRecording.Enabled = false;
}
private void SetSaveStartedState()
{
this.btnStopRecording.Enabled = false;
this.btnStopRecording.Text = "Saving Data...";
}
private void SetPreviewOrConfigButtonStates()
{
if (csChangedSettings.Equals(csPersistedSettings))
{
btnSaveConfig.Enabled = m_bDataDirty = false;
btnPreview.Enabled = true;
}
else
{
btnSaveConfig.Enabled = m_bDataDirty = true;
btnPreview.Enabled = false;
}
}
private void SetDataFieldsEnabledValueTo(bool bEnable)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered SetDataFieldsEnabledValueTo() method");
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tSetting all data fields to :" + bEnable.ToString());
txtStockNumber.Enabled = txtVinNumber.Enabled = bEnable;
txtMake.Enabled = txtModel.Enabled = txtYear.Enabled = bEnable;
txtFirstName.Enabled = txtLastName.Enabled = txtDealNumber.Enabled = bEnable;
chkAH.Enabled = chkETCH.Enabled = chkGAP.Enabled = chkMaint.Enabled = chkVSC.Enabled = bEnable;
txtNotes.Enabled = bEnable;
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Exiting SetDataFieldsEnabledValueTo() method");
}
private void ResetDataFieldsAndDestroyObjects()
{
// reset all values
txtStockNumber.Text = txtVinNumber.Text = txtMake.Text = txtModel.Text = string.Empty;
txtYear.Text = txtFirstName.Text = txtLastName.Text = txtDealNumber.Text = txtNotes.Text = string.Empty;
chkAH.Checked = chkETCH.Checked = chkGAP.Checked = chkMaint.Checked = chkVSC.Checked = false;
if (DealInfo != null)
{
DealInfo = null;
}
}
private bool StartCapture(string sFullPath)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "Entered StartCapture() method.");
string sError = string.Empty;
int hr = 0;
try
{
CloseInterfaces();
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tTry to create CaptureObject.");
m_CaptureObjForCapture = new CCapture(GetVideoDevice(csChangedSettings.VideoDevice),
GetAudioDevice(csChangedSettings.AudioDevice), sFullPath);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tCaptureObject created successfully.");
}
catch (Exception ex)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tException caught. Message: " + ex.Message);
CloseInterfaces();
return false;
}
if (m_MediaControl == null)
m_MediaControl = (IMediaControl)m_CaptureObjForCapture.m_FilterGraph;
if (m_FilterState != FilterState.Running)
hr = m_MediaControl.Run();
m_MediaControl.GetState(50, out m_FilterState);
sError = DsError.GetErrorText(hr);
Trace.WriteLineIf(Tracer.TracerSwitch.TraceInfo, "\tMediaControl.Run() returned message: " + sError);
if (hr != 0)
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "\tThe previous error can safely be ignored unless other errors are occurring.");
m_enCurrentState = PlayState.Running;
return true;
}
#endregion
#region Changed Configuration Event handlers
private void cboVideoDevices_SelectionChangeCommitted(object sender, EventArgs e)
{
csChangedSettings.VideoDevice = cboVideoDevices.Text;
SetPreviewOrConfigButtonStates();
}
private void cboAudioDevices_SelectionChangeCommitted(object sender, EventArgs e)
{
csChangedSettings.VideoDevice = cboAudioDevices.Text;
SetPreviewOrConfigButtonStates();
}
private void txtOutputDirectory_TextChanged(object sender, EventArgs e)
{
csChangedSettings.OutputDirectory = txtOutputDirectory.Text;
SetPreviewOrConfigButtonStates();
}
private void txtDealershipName_TextChanged(object sender, EventArgs e)
{
csChangedSettings.Dealership = txtDealershipName.Text;
SetPreviewOrConfigButtonStates();
}
private void txtSQLServer_TextChanged(object sender, EventArgs e)
{
csChangedSettings.SqlServer = txtSQLServer.Text;
SetPreviewOrConfigButtonStates();
}
private void chkAppendUserName_CheckedChanged(object sender, EventArgs e)
{
csChangedSettings.AppendUserName = chkAppendUserName.Checked;
SetPreviewOrConfigButtonStates();
}
private void chkUseSQLAuth_CheckedChanged(object sender, EventArgs e)
{
if (chkUseSQLAuth.Checked)
{
txtSqlUser.Enabled = true;
txtPassword.Enabled = true;
}
else
{
txtSqlUser.Enabled = false;
txtPassword.Enabled = false;
}
csChangedSettings.UseSQLAuthentication = chkUseSQLAuth.Checked;
SetPreviewOrConfigButtonStates();
}
private void txtSqlUser_TextChanged(object sender, EventArgs e)
{
csChangedSettings.SQLUserName = txtSqlUser.Text;
SetPreviewOrConfigButtonStates();
}
private void txtPassword_TextChanged(object sender, EventArgs e)
{
csChangedSettings.Password = txtPassword.Text;
SetPreviewOrConfigButtonStates();
}
private void txtDatabaseName_TextChanged(object sender, EventArgs e)
{
csChangedSettings.DatabaseName = txtDatabaseName.Text;
SetPreviewOrConfigButtonStates();
}
private void btnSaveConfig_EnabledChanged(object sender, EventArgs e)
{
if (btnSaveConfig.Enabled)
btnTestSQLConn.Enabled = false;
else
btnTestSQLConn.Enabled = true;
}
#endregion
#region Changed Data Fields Event handlers
private void txtStockNumber_TextChanged(object sender, EventArgs e)
{
DealInfo.vehicleInfo.StockNumber = txtStockNumber.Text;
}
private void txtVinNumber_TextChanged(object sender, EventArgs e)
{
DealInfo.vehicleInfo.VIN = txtVinNumber.Text;
}
private void txtMake_TextChanged(object sender, EventArgs e)
{
DealInfo.vehicleInfo.Make = txtMake.Text;
}
private void txtModel_TextChanged(object sender, EventArgs e)
{
DealInfo.vehicleInfo.Model = txtModel.Text;
}
private void txtYear_TextChanged(object sender, EventArgs e)
{
DealInfo.vehicleInfo.Year = txtYear.Text;
}
private void txtFirstName_TextChanged(object sender, EventArgs e)
{
DealInfo.customerInfo.FirstName = txtFirstName.Text;
}
private void txtLastName_TextChanged(object sender, EventArgs e)
{
DealInfo.customerInfo.LastName = txtLastName.Text;
}
private void chkVSC_CheckedChanged(object sender, EventArgs e)
{
DealInfo.VSC = chkVSC.Checked;
}
private void chkAH_CheckedChanged(object sender, EventArgs e)
{
DealInfo.AH = chkAH.Checked;
}
private void chkETCH_CheckedChanged(object sender, EventArgs e)
{
DealInfo.ETCH = chkETCH.Checked;
}
private void chkGAP_CheckedChanged(object sender, EventArgs e)
{
DealInfo.GAP = chkGAP.Checked;
}
private void chkMaint_CheckedChanged(object sender, EventArgs e)
{
DealInfo.MAINT = chkMaint.Checked;
}
#endregion
#region Implement backgroundWorker
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
SendMessage(m_pHwnd, WM_SAVE_STARTED, IntPtr.Zero, IntPtr.Zero);
CloseInterfaces();
AssignDataValues();
BackgroundWorker bw = sender as BackgroundWorker;
e.Result = SaveData(bw);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Trace.WriteLineIf(Tracer.TracerSwitch.TraceError, "Error occurred during SaveData(). Message :" + e.Error.Message);
SendNotifyMessage(m_sd.Handle, WM_CLOSE, 0, 0);
string sMsg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(sMsg);
}
else
{
SendNotifyMessage(m_sd.Handle, WM_CLOSE, 0, 0);
SendMessage(m_pHwnd, WM_SAVE_COMPLETED, IntPtr.Zero, IntPtr.Zero);
}
}
private string SaveData(BackgroundWorker bw)
{
string sResult = string.Empty;
sResult = DealInfo.ExecuteSQLInserts(csChangedSettings.DatabaseName);
return sResult;
}
private void AssignDataValues()
{
// customer Info
DealInfo.customerInfo.FirstName = txtFirstName.Text;
DealInfo.customerInfo.LastName = txtLastName.Text;
// Address, City, State, Zip, Phone -- Not Implemented
// Dealership Info
DealInfo.DealershipName = txtDealerName.Text;
// Video Info
// vidFilename and vidSaveDir are set in btnStartRecording_Click() method
FileInfo fiVidFile = new FileInfo(DealInfo.videoInfo.VidSaveDir + DealInfo.videoInfo.VidFileName);
DealInfo.videoInfo.VidFileSize = fiVidFile.Length;
// Vehicle Info
DealInfo.vehicleInfo.Make = txtMake.Text;
DealInfo.vehicleInfo.Model = txtModel.Text;
DealInfo.vehicleInfo.StockNumber = txtStockNumber.Text;
DealInfo.vehicleInfo.VIN = txtVinNumber.Text;
DealInfo.vehicleInfo.Year = txtYear.Text;
// Deal Info
// DealInfo.CustomerRecordNumber set in btnStartRecording_Click() method
// DealInfo.IP_Address set in InitDataObjects
// DealInfo.ComputerName set in InitDataObjects
DealInfo.AH = chkAH.Checked;
DealInfo.ETCH = chkETCH.Checked;
DealInfo.GAP = chkGAP.Checked;
DealInfo.MAINT = chkMaint.Checked;
DealInfo.Notes = txtNotes.Text;
DealInfo.VSC = chkVSC.Checked;
}
#endregion
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
btnExit_Click(null, null);
}
private void aboutAgreementTracToolStripMenuItem1_Click(object sender, EventArgs e)
{
//AboutBox ab = new AboutBox();
//ab.ShowDialog();
}
//private void aboutAgreementTracToolStripMenuItem_Click(object sender, EventArgs e)
//{
// CRegisterProduct frmRegister = new CRegisterProduct(m_sCompanyName, m_sProductKey, m_sSerialNumber, m_nLicenseCount);
// frmRegister.ShowDialog();
//}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Format
{
using System;
using System.Text.RegularExpressions;
using System.Text;
using NPOI.SS.Util;
/**
* Formats a date value.
*
* @author Ken Arnold, Industrious Media LLC
*/
internal class CellDateFormatter : CellFormatter
{
private bool amPmUpper;
private bool ShowM;
private bool ShowAmPm;
private FormatBase dateFmt;
private String sFmt;
private static TimeSpan EXCEL_EPOCH_TIME;
private static DateTime EXCEL_EPOCH_DATE;
private static CellFormatter SIMPLE_DATE = new CellDateFormatter(
"mm/d/y");
static CellDateFormatter()
{
DateTime c = new DateTime(1904, 1, 1);
EXCEL_EPOCH_DATE = c;
EXCEL_EPOCH_TIME = c.TimeOfDay;
}
private class DatePartHandler : CellFormatPart.IPartHandler
{
private CellDateFormatter _formatter;
private int mStart = -1;
private int mLen;
private int hStart = -1;
private int hLen;
public DatePartHandler(CellDateFormatter formatter)
{
this._formatter = formatter;
}
public String HandlePart(Match m, String part, CellFormatType type, StringBuilder desc)
{
int pos = desc.Length;
char firstCh = part[0];
switch (firstCh)
{
case 's':
case 'S':
if (mStart >= 0)
{
for (int i = 0; i < mLen; i++)
desc[mStart + i] = 'm';
mStart = -1;
}
return part.ToLower();
case 'h':
case 'H':
mStart = -1;
hStart = pos;
hLen = part.Length;
return part.ToLower();
case 'd':
case 'D':
mStart = -1;
if (part.Length <= 2)
return part.ToLower();
else
return part.ToLower().Replace('d', 'E');
case 'm':
case 'M':
mStart = pos;
mLen = part.Length;
return part.ToUpper();
case 'y':
case 'Y':
mStart = -1;
if (part.Length == 3)
part = "yyyy";
return part.ToLower();
case '0':
mStart = -1;
int sLen = part.Length;
_formatter.sFmt = "%0" + (sLen + 2) + "." + sLen + "f";
return part.Replace('0', 'S');
case 'a':
case 'A':
case 'p':
case 'P':
if (part.Length > 1)
{
// am/pm marker
mStart = -1;
_formatter.ShowAmPm = true;
_formatter.ShowM = char.ToLower(part[1]) == 'm';
// For some reason "am/pm" becomes AM or PM, but "a/p" becomes a or p
_formatter.amPmUpper = _formatter.ShowM || char.IsUpper(part[0]);
return "a";
}
//noinspection fallthrough
return null;
default:
return null;
}
}
public void Finish(StringBuilder toAppendTo)
{
if (hStart >= 0 && !_formatter.ShowAmPm)
{
for (int i = 0; i < hLen; i++)
{
toAppendTo[hStart + i] = 'H';
}
}
}
}
/**
* Creates a new date formatter with the given specification.
*
* @param format The format.
*/
public CellDateFormatter(String format)
: base(format)
{
;
DatePartHandler partHandler = new DatePartHandler(this);
StringBuilder descBuf = CellFormatPart.ParseFormat(format,
CellFormatType.DATE, partHandler);
partHandler.Finish(descBuf);
dateFmt = new SimpleDateFormat(descBuf.ToString());
}
/** {@inheritDoc} */
public override void FormatValue(StringBuilder toAppendTo, Object value)
{
if (value == null)
value = 0.0;
if (value.GetType().IsPrimitive/* is Number*/)
{
double num = (double)value;
double v = num;
if (v == 0.0)
value = EXCEL_EPOCH_DATE;
else
value = new DateTime((long)(EXCEL_EPOCH_TIME.Ticks + v));
}
throw new NotImplementedException();
//AttributedCharacterIterator it = dateFmt.FormatToCharacterIterator(
// value);
//bool doneAm = false;
//bool doneMillis = false;
//it.First();
//for (char ch = it.First();
// ch != CharacterIterator.DONE;
// ch = it.Next())
//{
// if (it.GetAttribute(DateFormat.Field.MILLISECOND) != null)
// {
// if (!doneMillis)
// {
// Date dateObj = (Date)value;
// int pos = toAppendTo.Length();
// Formatter formatter = new Formatter(toAppendTo);
// long msecs = dateObj.Time % 1000;
// formatter.Format(LOCALE, sFmt, msecs / 1000.0);
// toAppendTo.Remove(pos, 2);
// doneMillis = true;
// }
// }
// else if (it.GetAttribute(DateFormat.Field.AM_PM) != null)
// {
// if (!doneAm)
// {
// if (ShowAmPm)
// {
// if (amPmUpper)
// {
// toAppendTo.Append(char.ToUpper(ch));
// if (ShowM)
// toAppendTo.Append('M');
// }
// else
// {
// toAppendTo.Append(char.ToLower(ch));
// if (ShowM)
// toAppendTo.Append('m');
// }
// }
// doneAm = true;
// }
// }
// else
// {
// toAppendTo.Append(ch);
// }
//}
}
/**
* {@inheritDoc}
* <p/>
* For a date, this is <tt>"mm/d/y"</tt>.
*/
public override void SimpleValue(StringBuilder toAppendTo, Object value)
{
SIMPLE_DATE.FormatValue(toAppendTo, value);
}
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
// ReSharper disable ConditionIsAlwaysTrueOrFalse (we're allowing nulls to be passed to the writer where the underlying class doesn't).
// ReSharper disable HeuristicUnreachableCode
namespace osu.Game.IO.Legacy
{
/// <summary> SerializationWriter. Extends BinaryWriter to add additional data types,
/// handle null strings and simplify use with ISerializable. </summary>
public class SerializationWriter : BinaryWriter
{
public SerializationWriter(Stream s)
: base(s, Encoding.UTF8)
{
}
/// <summary> Static method to initialise the writer with a suitable MemoryStream. </summary>
public static SerializationWriter GetWriter()
{
MemoryStream ms = new MemoryStream(1024);
return new SerializationWriter(ms);
}
/// <summary> Writes a string to the buffer. Overrides the base implementation so it can cope with nulls </summary>
public override void Write(string str)
{
if (str == null)
{
Write((byte)ObjType.nullType);
}
else
{
Write((byte)ObjType.stringType);
base.Write(str);
}
}
/// <summary> Writes a byte array to the buffer. Overrides the base implementation to
/// send the length of the array which is needed when it is retrieved </summary>
public override void Write(byte[] b)
{
if (b == null)
{
Write(-1);
}
else
{
int len = b.Length;
Write(len);
if (len > 0) base.Write(b);
}
}
/// <summary> Writes a char array to the buffer. Overrides the base implementation to
/// sends the length of the array which is needed when it is read. </summary>
public override void Write(char[] c)
{
if (c == null)
{
Write(-1);
}
else
{
int len = c.Length;
Write(len);
if (len > 0) base.Write(c);
}
}
/// <summary>
/// Writes DateTime to the buffer.
/// </summary>
/// <param name="dt"></param>
public void Write(DateTime dt)
{
Write(dt.ToUniversalTime().Ticks);
}
/// <summary> Writes a generic ICollection (such as an IList(T)) to the buffer.</summary>
public void Write<T>(List<T> c) where T : ILegacySerializable
{
if (c == null)
{
Write(-1);
}
else
{
int count = c.Count;
Write(count);
for (int i = 0; i < count; i++)
c[i].WriteToStream(this);
}
}
/// <summary> Writes a generic IDictionary to the buffer. </summary>
public void Write<T, U>(IDictionary<T, U> d)
{
if (d == null)
{
Write(-1);
}
else
{
Write(d.Count);
foreach (KeyValuePair<T, U> kvp in d)
{
WriteObject(kvp.Key);
WriteObject(kvp.Value);
}
}
}
/// <summary> Writes an arbitrary object to the buffer. Useful where we have something of type "object"
/// and don't know how to treat it. This works out the best method to use to write to the buffer. </summary>
public void WriteObject(object obj)
{
if (obj == null)
{
Write((byte)ObjType.nullType);
}
else
{
switch (obj.GetType().Name)
{
case "Boolean":
Write((byte)ObjType.boolType);
Write((bool)obj);
break;
case "Byte":
Write((byte)ObjType.byteType);
Write((byte)obj);
break;
case "UInt16":
Write((byte)ObjType.uint16Type);
Write((ushort)obj);
break;
case "UInt32":
Write((byte)ObjType.uint32Type);
Write((uint)obj);
break;
case "UInt64":
Write((byte)ObjType.uint64Type);
Write((ulong)obj);
break;
case "SByte":
Write((byte)ObjType.sbyteType);
Write((sbyte)obj);
break;
case "Int16":
Write((byte)ObjType.int16Type);
Write((short)obj);
break;
case "Int32":
Write((byte)ObjType.int32Type);
Write((int)obj);
break;
case "Int64":
Write((byte)ObjType.int64Type);
Write((long)obj);
break;
case "Char":
Write((byte)ObjType.charType);
base.Write((char)obj);
break;
case "String":
Write((byte)ObjType.stringType);
base.Write((string)obj);
break;
case "Single":
Write((byte)ObjType.singleType);
Write((float)obj);
break;
case "Double":
Write((byte)ObjType.doubleType);
Write((double)obj);
break;
case "Decimal":
Write((byte)ObjType.decimalType);
Write((decimal)obj);
break;
case "DateTime":
Write((byte)ObjType.dateTimeType);
Write((DateTime)obj);
break;
case "Byte[]":
Write((byte)ObjType.byteArrayType);
base.Write((byte[])obj);
break;
case "Char[]":
Write((byte)ObjType.charArrayType);
base.Write((char[])obj);
break;
default:
Write((byte)ObjType.otherType);
BinaryFormatter b = new BinaryFormatter
{
AssemblyFormat = FormatterAssemblyStyle.Simple,
TypeFormat = FormatterTypeStyle.TypesWhenNeeded
};
b.Serialize(BaseStream, obj);
break;
} // switch
} // if obj==null
} // WriteObject
/// <summary> Adds the SerializationWriter buffer to the SerializationInfo at the end of GetObjectData(). </summary>
public void AddToInfo(SerializationInfo info)
{
byte[] b = ((MemoryStream)BaseStream).ToArray();
info.AddValue("X", b, typeof(byte[]));
}
public void WriteRawBytes(byte[] b)
{
base.Write(b);
}
public void WriteByteArray(byte[] b)
{
if (b == null)
{
Write(-1);
}
else
{
int len = b.Length;
Write(len);
if (len > 0) base.Write(b);
}
}
public void WriteUtf8(string str)
{
WriteRawBytes(Encoding.UTF8.GetBytes(str));
}
}
}
| |
using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using ADODB;
namespace MyMeta
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class Database : Single, IDatabase, INameValueItem
{
protected Hashtable dataTypeTables = new Hashtable();
public Database()
{
}
virtual public IResultColumns ResultColumnsFromSQL(string sql)
{
IResultColumns columns = null;
using (OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString))
{
cn.Open();
columns = ResultColumnsFromSQL(sql, cn);
}
return columns;
}
virtual public ADODB.Recordset ExecuteSql(string sql)
{
Recordset oRS = new Recordset();
OleDbConnection cn = null;
OleDbDataReader reader = null;
try
{
cn = new OleDbConnection(dbRoot.ConnectionString);
cn.Open();
try
{
cn.ChangeDatabase(this.Name);
}
catch { } // some databases don't have the concept of catalogs. Catch this and throw it out
OleDbCommand command = new OleDbCommand(sql, cn);
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
DataTable schema;
string dataType, fieldname;
int length;
bool firstTime = true;
while (reader.Read())
{
if (firstTime)
{
schema = reader.GetSchemaTable();
foreach (DataRow row in schema.Rows)
{
fieldname = row["ColumnName"].ToString();
dataType = row["DataType"].ToString();
length = Convert.ToInt32(row["ColumnSize"]);
oRS.Fields.Append(fieldname, GetADOType(dataType), length,
FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value);
}
oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value,
CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1);
firstTime = false;
}
oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value);
for(int i = 0; i < reader.FieldCount; i++)
{
if (reader[i] is System.Guid)
{
oRS.Fields[i].Value = "{" + reader[i].ToString() + "}";
}
else
{
oRS.Fields[i].Value = reader[i];
}
}
}
cn.Close();
//Move to the first record
if (!firstTime)
{
oRS.MoveFirst();
}
else
{
oRS = null;
}
}
catch (Exception ex)
{
if ((reader != null) && (!reader.IsClosed))
{
reader.Close();
reader = null;
}
if ((cn != null) && (cn.State == ConnectionState.Open))
{
cn.Close();
cn = null;
}
throw ex;
}
return oRS;
}
/// <summary>
///
/// </summary>
/// <param name="oledbType"></param>
/// <param name="providerTypeInt"></param>
/// <param name="dataType"></param>
/// <param name="length"></param>
/// <param name="numericPrecision"></param>
/// <param name="numericScale"></param>
/// <param name="isLong"></param>
/// <param name="dbTypeName"></param>
/// <param name="dbTypeNameComplete"></param>
/// <returns></returns>
protected virtual bool GetNativeType(
OleDbType oledbType, int providerTypeInt, string dataType,
int length, int numericPrecision, int numericScale, bool isLong,
out string dbTypeName, out string dbTypeNameComplete)
{
bool rval = false;
IProviderType provType = null;
if (providerTypeInt >= 0)
{
if (!dataTypeTables.ContainsKey(providerTypeInt))
{
foreach (IProviderType ptypeLoop in dbRoot.ProviderTypes)
{
if (ptypeLoop.DataType == providerTypeInt)
{
if ((provType == null) ||
(ptypeLoop.BestMatch && !provType.BestMatch) ||
(isLong && ptypeLoop.IsLong && !provType.IsLong) ||
(!ptypeLoop.IsFixedLength && provType.IsFixedLength))
{
provType = ptypeLoop;
}
}
}
dataTypeTables[providerTypeInt] = provType;
}
else
{
provType = dataTypeTables[providerTypeInt] as IProviderType;
}
}
if (provType != null)
{
string dtype = provType.Type;
string[] parms = provType.CreateParams.Split(',');
if (parms.Length > 0)
{
dtype += "(";
int xx = 0;
for (int i = 0; i < parms.Length; i++)
{
switch (parms[i])
{
case "precision":
dtype += (xx > 0 ? ", " : "") + numericPrecision.ToString();
xx++;
break;
case "scale":
dtype += (xx > 0 ? ", " : "") + numericScale.ToString();
xx++;
break;
case "length":
case "max length":
dtype += (xx > 0 ? ", " : "") + length.ToString();
xx++;
break;
}
}
dtype += ")";
if (xx == 0) dtype = dtype.Substring(0, dtype.Length - 2);
}
dbTypeName = provType.Type;
dbTypeNameComplete = dtype;
rval = true;
}
else
{
dbTypeName = string.Empty;
dbTypeNameComplete = string.Empty;
}
return rval;
}
protected IResultColumns ResultColumnsFromSQL(string sql, IDbConnection cn)
{
MyMetaPluginContext context = new MyMetaPluginContext(null, null);
DataTable metaData = context.CreateResultColumnsDataTable();
Plugin.PluginResultColumns resultCols = new Plugin.PluginResultColumns(null);
resultCols.dbRoot = dbRoot;
IDbCommand command = cn.CreateCommand();
command.CommandText = sql;
command.CommandType = CommandType.Text;
using (IDataReader reader = command.ExecuteReader())
{
DataTable schema;
//DataTable data;
string dataType, fieldname;
int length;
// Skip columns contains the index of any columns that we cannot handle, array types and such ...
Hashtable skipColumns = null;
reader.Read();
schema = reader.GetSchemaTable();
IProviderType provType = null;
int columnOrdinal = 0, numericPrecision = 0, numericScale = 0, providerTypeInt = -1, colID = 0;
bool isLong = false;
string dbTypeName = string.Empty, dbTypeNameComplete = string.Empty;
foreach (DataRow row in schema.Rows)
{
DataRow metarow = metaData.NewRow();
fieldname = row["ColumnName"].ToString();
dataType = row["DataType"].ToString();
length = 0;
provType = null;
columnOrdinal = 0;
numericPrecision = 0;
numericScale = 0;
providerTypeInt = -1;
isLong = false;
if (row["ColumnSize"] != DBNull.Value) length = Convert.ToInt32(row["ColumnSize"]);
if (row["ColumnOrdinal"] != DBNull.Value) columnOrdinal = Convert.ToInt32(row["ColumnOrdinal"]);
if (row["NumericPrecision"] != DBNull.Value) numericPrecision = Convert.ToInt32(row["NumericPrecision"]);
if (row["NumericScale"] != DBNull.Value) numericScale = Convert.ToInt32(row["NumericScale"]);
if (row["IsLong"] != DBNull.Value) isLong = Convert.ToBoolean(row["IsLong"]);
if (row["ProviderType"] != DBNull.Value) providerTypeInt = Convert.ToInt32(row["ProviderType"]);
OleDbType oledbType;
try { oledbType = (OleDbType)providerTypeInt; }
catch { oledbType = OleDbType.IUnknown; }
this.GetNativeType(oledbType, providerTypeInt, dataType, length, numericPrecision, numericScale, isLong, out dbTypeName, out dbTypeNameComplete);
metarow["COLUMN_NAME"] = fieldname;
metarow["ORDINAL_POSITION"] = columnOrdinal;
metarow["DATA_TYPE"] = providerTypeInt;
metarow["TYPE_NAME"] = dbTypeName;
metarow["TYPE_NAME_COMPLETE"] = dbTypeNameComplete;
metaData.Rows.Add(metarow);
}
resultCols.Populate(metaData);
}
return resultCols;
}
protected ADODB.Recordset ExecuteIntoRecordset(string sql, IDbConnection cn)
{
Recordset oRS = new Recordset();
IDataReader reader = null;
try
{
IDbCommand command = cn.CreateCommand();
command.CommandText = sql;
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
DataTable schema;
string dataType, fieldname;
int length;
bool firstTime = true;
// Skip columns contains the index of any columns that we cannot handle, array types and such ...
Hashtable skipColumns = null;
while (reader.Read())
{
if (firstTime)
{
skipColumns = new Hashtable();
schema = reader.GetSchemaTable();
int colID = 0;
foreach (DataRow row in schema.Rows)
{
fieldname = row["ColumnName"].ToString();
dataType = row["DataType"].ToString();
length = Convert.ToInt32(row["ColumnSize"]);
try
{
oRS.Fields.Append(fieldname, GetADOType(dataType), length,
FieldAttributeEnum.adFldIsNullable, System.Reflection.Missing.Value);
}
catch
{
// We can't handle this column type, ie, Firebird array types
skipColumns[colID] = colID;
}
colID++;
}
oRS.Open(System.Reflection.Missing.Value, System.Reflection.Missing.Value,
CursorTypeEnum.adOpenStatic, LockTypeEnum.adLockOptimistic, 1);
firstTime = false;
}
oRS.AddNew(System.Reflection.Missing.Value, System.Reflection.Missing.Value);
for(int i = 0, j = 0; i < reader.FieldCount; i++)
{
// Skip columns that we cannot handle
if(!skipColumns.ContainsKey(i))
{
if (reader[j] is System.Guid)
{
oRS.Fields[j].Value = "{" + reader[j].ToString() + "}";
}
else
{
try
{
oRS.Fields[j].Value = reader[j];
}
catch
{
// For some reason it wouldn't accept this value?
oRS.Fields[j].Value = DBNull.Value;
}
}
j++;
}
}
}
cn.Close();
//Move to the first record
if (!firstTime)
{
oRS.MoveFirst();
}
else
{
oRS = null;
}
}
catch (Exception ex)
{
if ((reader != null) && (!reader.IsClosed))
{
reader.Close();
reader = null;
}
if ((cn != null) && (cn.State == ConnectionState.Open))
{
cn.Close();
cn = null;
}
throw ex;
}
return oRS;
}
protected DataTypeEnum GetADOType(string sType)
{
switch(sType)
{
case null:
return DataTypeEnum.adEmpty;
case "System.Byte":
return DataTypeEnum.adUnsignedTinyInt;
case "System.SByte":
return DataTypeEnum.adTinyInt;
case "System.Boolean":
return DataTypeEnum.adBoolean;
case "System.Int16":
return DataTypeEnum.adSmallInt;
case "System.Int32":
return DataTypeEnum.adInteger;
case "System.Int64":
return DataTypeEnum.adBigInt;
case "System.Single":
return DataTypeEnum.adSingle;
case "System.Double":
return DataTypeEnum.adDouble;
case "System.Decimal":
return DataTypeEnum.adDecimal;
case "System.DateTime":
return DataTypeEnum.adDate;
case "System.Guid":
return DataTypeEnum.adGUID;
case "System.String":
return DataTypeEnum.adBSTR; //.adChar;
case "System.Byte[]":
return DataTypeEnum.adBinary;
case "System.Array":
return DataTypeEnum.adArray;
case "System.Object":
return DataTypeEnum.adVariant;
default:
return 0;
}
}
virtual public ITables Tables
{
get
{
if(null == _tables)
{
_tables = (Tables)this.dbRoot.ClassFactory.CreateTables();
_tables.dbRoot = this._dbRoot;
_tables.Database = this;
_tables.LoadAll();
}
return _tables;
}
}
virtual public IViews Views
{
get
{
if(null == _views)
{
_views = (Views)this.dbRoot.ClassFactory.CreateViews();
_views.dbRoot = this._dbRoot;
_views.Database = this;
_views.LoadAll();
}
return _views;
}
}
virtual public IProcedures Procedures
{
get
{
if(null == _procedures)
{
_procedures = (Procedures)this.dbRoot.ClassFactory.CreateProcedures();
_procedures.dbRoot = this._dbRoot;
_procedures.Database = this;
_procedures.LoadAll();
}
return _procedures;
}
}
virtual public IDomains Domains
{
get
{
if(null == _domains)
{
_domains = (Domains)this.dbRoot.ClassFactory.CreateDomains();
_domains.dbRoot = this._dbRoot;
_domains.Database = this;
_domains.LoadAll();
}
return _domains;
}
}
// virtual public IPropertyCollection GlobalProperties
// {
// get
// {
// Database db = this as Database;
// if(null == db._columnProperties)
// {
// db._columnProperties = new PropertyCollection();
// db._columnProperties.Parent = this;
//
// string xPath = this.GlobalUserDataXPath;
// XmlNode xmlNode = this.dbRoot.UserData.SelectSingleNode(xPath, null);
//
// if(xmlNode == null)
// {
// XmlNode parentNode = db.CreateGlobalXmlNode();
//
// xmlNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Database", null);
// parentNode.AppendChild(xmlNode);
// }
//
// db._columnProperties.LoadAllGlobal(xmlNode);
// }
//
// return db._columnProperties;
// }
// }
#if ENTERPRISE
[DispId(0)]
#endif
override public string Alias
{
get
{
XmlNode node = null;
if(this.GetXmlNode(out node, false))
{
string niceName = null;
if(this.GetUserData(node, "n", out niceName))
{
if(string.Empty != niceName)
return niceName;
}
}
// There was no nice name
return this.Name;
}
set
{
XmlNode node = null;
if(this.GetXmlNode(out node, true))
{
this.SetUserData(node, "n", value);
}
}
}
public virtual string XmlMetaDataKey
{
get
{
if (dbRoot.UserDataDatabaseMappings.ContainsKey(Name))
{
return dbRoot.UserDataDatabaseMappings[Name];
}
else
{
return Name;
}
}
}
override public string Name
{
get
{
return this.GetString(Databases.f_Catalog);
}
}
virtual public string Description
{
get
{
return this.GetString(Databases.f_Description);
}
}
virtual public string SchemaName
{
get
{
return this.GetString(Databases.f_SchemaName);
}
}
virtual public string SchemaOwner
{
get
{
return this.GetString(Databases.f_SchemaOwner);
}
}
virtual public string DefaultCharSetCatalog
{
get
{
return this.GetString(Databases.f_DefCharSetCat);
}
}
virtual public string DefaultCharSetSchema
{
get
{
return this.GetString(Databases.f_DefCharSetSchema);
}
}
virtual public string DefaultCharSetName
{
get
{
return this.GetString(Databases.f_DefCharSetName);
}
}
virtual public dbRoot Root
{
get
{
return this.dbRoot;
}
}
#region XML User Data
#if ENTERPRISE
[ComVisible(false)]
#endif
override public string UserDataXPath
{
get
{
return Databases.UserDataXPath + @"/Database[@p='" + this.XmlMetaDataKey + "']";
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override public string GlobalUserDataXPath
{
get
{
return @"//MyMeta/Global/Databases/Database[@p='" + this.XmlMetaDataKey + "']";
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override internal bool GetXmlNode(out XmlNode node, bool forceCreate)
{
node = null;
bool success = false;
if(null == _xmlNode)
{
// Get the parent node
XmlNode parentNode = null;
if(this.Databases.GetXmlNode(out parentNode, forceCreate))
{
// See if our user data already exists
string xPath = @"./Database[@p='" + this.XmlMetaDataKey + "']";
if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate)
{
// Create it, and try again
this.CreateUserMetaData(parentNode);
GetUserData(xPath, parentNode, out _xmlNode);
}
}
}
if(null != _xmlNode)
{
node = _xmlNode;
success = true;
}
return success;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
internal XmlNode CreateGlobalXmlNode()
{
XmlNode node = null;
XmlNode parentNode = null;
this.dbRoot.GetXmlNode(out parentNode, true);
node = parentNode.SelectSingleNode(@"./Global");
if(node == null)
{
node = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Global", null);
parentNode.AppendChild(node);
}
parentNode = node;
node = parentNode.SelectSingleNode(@"./Databases");
if(node == null)
{
node = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Databases", null);
parentNode.AppendChild(node);
}
parentNode = node;
node = parentNode.SelectSingleNode(@"./Database[@p='" + this.XmlMetaDataKey + "']");
if(node == null)
{
node = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Database", null);
parentNode.AppendChild(node);
XmlAttribute attr;
attr = node.OwnerDocument.CreateAttribute("p");
attr.Value = this.XmlMetaDataKey;
node.Attributes.Append(attr);
}
return node;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override public void CreateUserMetaData(XmlNode parentNode)
{
XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Database", null);
parentNode.AppendChild(myNode);
XmlAttribute attr;
attr = parentNode.OwnerDocument.CreateAttribute("p");
attr.Value = this.XmlMetaDataKey;
myNode.Attributes.Append(attr);
attr = parentNode.OwnerDocument.CreateAttribute("n");
attr.Value = "";
myNode.Attributes.Append(attr);
}
#endregion
#region INameValueCollection Members
public string ItemName
{
get
{
return this.Name;
}
}
public string ItemValue
{
get
{
return this.Name;
}
}
#endregion
internal Databases Databases = null;
protected Tables _tables = null;
protected Views _views = null;
protected Procedures _procedures = null;
protected Domains _domains = null;
// Global properties are per Database
internal PropertyCollection _columnProperties = null;
internal PropertyCollection _databaseProperties = null;
internal PropertyCollection _foreignkeyProperties = null;
internal PropertyCollection _indexProperties = null;
internal PropertyCollection _parameterProperties = null;
internal PropertyCollection _procedureProperties = null;
internal PropertyCollection _resultColumnProperties = null;
internal PropertyCollection _tableProperties = null;
internal PropertyCollection _viewProperties = null;
internal PropertyCollection _domainProperties = null;
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure.Management.SiteRecovery
{
/// <summary>
/// Definition of server operations for the Site Recovery extension.
/// </summary>
internal partial class ServerOperations : IServiceOperations<SiteRecoveryManagementClient>, Microsoft.WindowsAzure.Management.SiteRecovery.IServerOperations
{
/// <summary>
/// Initializes a new instance of the ServerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerOperations(SiteRecoveryManagementClient client)
{
this._client = client;
}
private SiteRecoveryManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.SiteRecoveryManagementClient.
/// </summary>
public SiteRecoveryManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get the server object by Id.
/// </summary>
/// <param name='serverId'>
/// Required. Server ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the server object
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.SiteRecovery.Models.ServerResponse> GetAsync(string serverId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (serverId == null)
{
throw new ArgumentNullException("serverId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverId", serverId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + this.Client.CloudServiceName.Trim() + "/resources/WAHyperVRecoveryManager/~/HyperVRecoveryManagerVault/" + this.Client.ResourceName.Trim() + "/Servers/" + serverId.Trim() + "?";
url = url + "api-version=2014-10-27";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (serviceResourceElement != null)
{
Server serviceResourceInstance = new Server();
result.Server = serviceResourceInstance;
XElement providerVersionElement = serviceResourceElement.Element(XName.Get("ProviderVersion", "http://schemas.microsoft.com/windowsazure"));
if (providerVersionElement != null)
{
string providerVersionInstance = providerVersionElement.Value;
serviceResourceInstance.ProviderVersion = providerVersionInstance;
}
XElement serverVersionElement = serviceResourceElement.Element(XName.Get("ServerVersion", "http://schemas.microsoft.com/windowsazure"));
if (serverVersionElement != null)
{
string serverVersionInstance = serverVersionElement.Value;
serviceResourceInstance.ServerVersion = serverVersionInstance;
}
XElement lastHeartbeatElement = serviceResourceElement.Element(XName.Get("LastHeartbeat", "http://schemas.microsoft.com/windowsazure"));
if (lastHeartbeatElement != null)
{
DateTime lastHeartbeatInstance = DateTime.Parse(lastHeartbeatElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.LastHeartbeat = lastHeartbeatInstance;
}
XElement connectedElement = serviceResourceElement.Element(XName.Get("Connected", "http://schemas.microsoft.com/windowsazure"));
if (connectedElement != null)
{
bool connectedInstance = bool.Parse(connectedElement.Value);
serviceResourceInstance.Connected = connectedInstance;
}
XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement idElement = serviceResourceElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
serviceResourceInstance.ID = idInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all servers under the vault.
/// </summary>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list servers operation.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.SiteRecovery.Models.ServerListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + this.Client.CloudServiceName.Trim() + "/resources/WAHyperVRecoveryManager/~/HyperVRecoveryManagerVault/" + this.Client.ResourceName.Trim() + "/Servers?";
url = url + "api-version=2014-10-27";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/xml");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement arrayOfServiceResourceSequenceElement = responseDoc.Element(XName.Get("ArrayOfServiceResource", "http://schemas.microsoft.com/windowsazure"));
if (arrayOfServiceResourceSequenceElement != null)
{
foreach (XElement arrayOfServiceResourceElement in arrayOfServiceResourceSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")))
{
Server serviceResourceInstance = new Server();
result.Servers.Add(serviceResourceInstance);
XElement providerVersionElement = arrayOfServiceResourceElement.Element(XName.Get("ProviderVersion", "http://schemas.microsoft.com/windowsazure"));
if (providerVersionElement != null)
{
string providerVersionInstance = providerVersionElement.Value;
serviceResourceInstance.ProviderVersion = providerVersionInstance;
}
XElement serverVersionElement = arrayOfServiceResourceElement.Element(XName.Get("ServerVersion", "http://schemas.microsoft.com/windowsazure"));
if (serverVersionElement != null)
{
string serverVersionInstance = serverVersionElement.Value;
serviceResourceInstance.ServerVersion = serverVersionInstance;
}
XElement lastHeartbeatElement = arrayOfServiceResourceElement.Element(XName.Get("LastHeartbeat", "http://schemas.microsoft.com/windowsazure"));
if (lastHeartbeatElement != null)
{
DateTime lastHeartbeatInstance = DateTime.Parse(lastHeartbeatElement.Value, CultureInfo.InvariantCulture);
serviceResourceInstance.LastHeartbeat = lastHeartbeatInstance;
}
XElement connectedElement = arrayOfServiceResourceElement.Element(XName.Get("Connected", "http://schemas.microsoft.com/windowsazure"));
if (connectedElement != null)
{
bool connectedInstance = bool.Parse(connectedElement.Value);
serviceResourceInstance.Connected = connectedInstance;
}
XElement nameElement = arrayOfServiceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serviceResourceInstance.Name = nameInstance;
}
XElement idElement = arrayOfServiceResourceElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
serviceResourceInstance.ID = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using XSerializer.Encryption;
namespace XSerializer
{
internal sealed class CustomJsonSerializer : IJsonSerializerInternal
{
private static readonly ConcurrentDictionary<Tuple<Type, bool, JsonMappings>, CustomJsonSerializer> _cache = new ConcurrentDictionary<Tuple<Type, bool, JsonMappings>, CustomJsonSerializer>();
private readonly ConcurrentDictionary<Type, List<SerializableJsonProperty>> _serializingPropertiesMap = new ConcurrentDictionary<Type, List<SerializableJsonProperty>>();
private readonly Dictionary<string, SerializableJsonProperty> _deserializingPropertiesMap;
private readonly Type _type;
private readonly JsonMappings _mappings;
private readonly bool _encrypt;
private readonly Lazy<Func<IObjectFactory>> _createObjectFactory;
private CustomJsonSerializer(Type type, bool encrypt, JsonMappings mappings)
{
_mappings = mappings;
_type = type;
if (_mappings.MappingsByType.ContainsKey(type))
{
_type = _mappings.MappingsByType[type];
}
else
{
var mappingAttribute = (JsonMappingAttribute)Attribute.GetCustomAttribute(_type, typeof(JsonMappingAttribute));
if (mappingAttribute != null)
{
_type = mappingAttribute.Type;
}
}
_encrypt = encrypt || Attribute.GetCustomAttribute(type, typeof(EncryptAttribute)) != null;
var serializableProperties = GetSerializableProperties(_type);
_deserializingPropertiesMap = serializableProperties.ToDictionary(p => p.Name);
if (!_type.IsAbstract)
{
_serializingPropertiesMap[_type] = serializableProperties;
}
_createObjectFactory = new Lazy<Func<IObjectFactory>>(GetCreateObjectFactoryFunc);
}
private List<SerializableJsonProperty> GetSerializableProperties(Type type)
{
return type.GetProperties()
.Where(p => p.IsJsonSerializable(type.GetConstructors().SelectMany(c => c.GetParameters())))
.Select(p => new SerializableJsonProperty(p, _encrypt || p.GetCustomAttributes(typeof(EncryptAttribute), false).Any(), _mappings)).ToList();
}
public static CustomJsonSerializer Get(Type type, bool encrypt, JsonMappings mappings)
{
return _cache.GetOrAdd(Tuple.Create(type, encrypt, mappings), t => new CustomJsonSerializer(t.Item1, t.Item2, t.Item3));
}
public void SerializeObject(JsonWriter writer, object instance, IJsonSerializeOperationInfo info)
{
if (instance == null)
{
writer.WriteNull();
}
else
{
if (_encrypt)
{
var toggler = new EncryptWritesToggler(writer);
toggler.Toggle();
Write(writer, instance, info);
toggler.Revert();
}
else
{
Write(writer, instance, info);
}
}
}
private void Write(JsonWriter writer, object instance, IJsonSerializeOperationInfo info)
{
writer.WriteOpenObject();
var first = true;
var serializingProperties = _serializingPropertiesMap.GetOrAdd(instance.GetType(), GetSerializableProperties);
foreach (var property in serializingProperties)
{
if (first)
{
first = false;
}
else
{
writer.WriteItemSeparator();
}
property.WriteValue(writer, instance, info);
}
writer.WriteCloseObject();
}
public object DeserializeObject(JsonReader reader, IJsonSerializeOperationInfo info)
{
if (!reader.ReadContent())
{
throw new XSerializerException("Unexpected end of input while attempting to parse '{' character.");
}
if (reader.NodeType == JsonNodeType.Null)
{
return null;
}
if (_encrypt)
{
var toggler = new DecryptReadsToggler(reader);
toggler.Toggle();
try
{
return Read(reader, info);
}
finally
{
toggler.Revert();
}
}
return Read(reader, info);
}
private object Read(JsonReader reader, IJsonSerializeOperationInfo info)
{
var factory = _createObjectFactory.Value.Invoke();
foreach (var propertyName in reader.ReadProperties())
{
if (!factory.SetValue(reader, propertyName, info))
{
reader.Discard();
}
}
return factory.GetInstance();
}
private Func<IObjectFactory> GetCreateObjectFactoryFunc()
{
var constructor = GetConstructor(_type);
var parameters = constructor.GetParameters();
if (parameters.Length == 0)
{
var createInstance = GetCreateInstanceFunc(constructor);
return () => new DefaultConstructorObjectFactory(_deserializingPropertiesMap, createInstance());
}
else
{
var createInstance = GetCreateInstanceFunc(constructor, parameters);
var getSerializerAndArgIndex = GetGetSerializerAndArgIndexFunc(parameters);
var parametersLength = parameters.Length;
return () => new NonDefaultConstructorObjectFactory(
_deserializingPropertiesMap,
createInstance,
getSerializerAndArgIndex,
parametersLength);
}
}
private Func<object> GetCreateInstanceFunc(ConstructorInfo constructor)
{
Expression invokeConstructor = Expression.New(constructor);
if (_type.IsValueType) // Boxing is necessary
{
invokeConstructor = Expression.Convert(invokeConstructor, typeof(object));
}
var lambda = Expression.Lambda<Func<object>>(invokeConstructor);
var createInstance = lambda.Compile();
return createInstance;
}
private Func<object[], object> GetCreateInstanceFunc(ConstructorInfo constructor, ParameterInfo[] parameters)
{
var argsParameter = Expression.Parameter(typeof(object[]), "args");
var constructorArgs = new Expression[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
constructorArgs[i] =
Expression.Convert(
Expression.ArrayAccess(argsParameter, Expression.Constant(i)),
parameters[i].ParameterType);
}
Expression invokeConstructor = Expression.New(constructor, constructorArgs);
if (_type.IsValueType) // Boxing is necessary
{
invokeConstructor = Expression.Convert(invokeConstructor, typeof(object));
}
var createInstanceLambda = Expression.Lambda<Func<object[], object>>(invokeConstructor, argsParameter);
var createInstance = createInstanceLambda.Compile();
return createInstance;
}
private Func<string, Tuple<IJsonSerializerInternal, int>> GetGetSerializerAndArgIndexFunc(ParameterInfo[] parameters)
{
var propertyNameParameter = Expression.Parameter(typeof(string), "propertyName");
var switchCases = new SwitchCase[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
var serializer = JsonSerializerFactory.GetSerializer(parameters[i].ParameterType, _encrypt, _mappings);
var serializerAndArgIndex = Tuple.Create(serializer, i);
var matchingProperties =
_type.GetProperties().Where(p =>
p.Name.Equals(parameters[i].Name, StringComparison.OrdinalIgnoreCase)).ToList();
var switchLabel = matchingProperties.Count == 1 ? matchingProperties[0].GetName() : parameters[i].Name;
switchCases[i] = Expression.SwitchCase(
Expression.Constant(serializerAndArgIndex),
Expression.Constant(switchLabel));
}
var defaultCase = Expression.Constant(null, typeof(Tuple<IJsonSerializerInternal, int>));
var switchExpression = Expression.Switch(propertyNameParameter, defaultCase, switchCases);
var getSerializerAndArgIndexLambda =
Expression.Lambda<Func<string, Tuple<IJsonSerializerInternal, int>>>(
switchExpression, propertyNameParameter);
var getSerializerAndArgIndex = getSerializerAndArgIndexLambda.Compile();
return getSerializerAndArgIndex;
}
private static ConstructorInfo GetConstructor(Type type)
{
if (type.IsAbstract)
{
throw new XSerializerException("Cannot instantiate abstract type: " + type.FullName);
}
var constructors = type.GetConstructors();
if (constructors.Length == 0)
{
constructors = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
if (constructors.Length == 0)
{
throw new XSerializerException("Cannot instantiate static class: " + type.FullName);
}
}
if (constructors.Length == 1)
{
return constructors[0];
}
var decoratedConstructors = constructors.Where(IsDecoratedWithJsonConstructorAttribute).ToArray();
if (decoratedConstructors.Length == 1)
{
return decoratedConstructors[0];
}
if (decoratedConstructors.Length > 1)
{
throw new XSerializerException("More than one constructor is decorated with the JsonConstructor attribute: " + type.FullName);
}
var defaultConstructor = constructors.FirstOrDefault(c => c.GetParameters().Length == 0);
if (defaultConstructor != null)
{
return defaultConstructor;
}
throw new XSerializerException("More than one non-default constructor defined in type: " + type.FullName);
}
private static bool IsDecoratedWithJsonConstructorAttribute(ConstructorInfo constructor)
{
return Attribute.IsDefined(constructor, typeof(JsonConstructorAttribute))
|| Attribute.GetCustomAttributes(constructor).Any(attribute =>
attribute.GetType().FullName == "Newtonsoft.Json.JsonConstructorAttribute");
}
private interface IObjectFactory
{
bool SetValue(JsonReader reader, string propertyName, IJsonSerializeOperationInfo info);
object GetInstance();
}
private class DefaultConstructorObjectFactory : IObjectFactory
{
private readonly Dictionary<string, SerializableJsonProperty> _serializablePropertiesMap;
private readonly object _instance;
public DefaultConstructorObjectFactory(
Dictionary<string, SerializableJsonProperty> serializablePropertiesMap,
object instance)
{
_serializablePropertiesMap = serializablePropertiesMap;
_instance = instance;
}
public bool SetValue(JsonReader reader, string propertyName, IJsonSerializeOperationInfo info)
{
SerializableJsonProperty property;
if (_serializablePropertiesMap.TryGetValue(propertyName, out property))
{
property.SetValue(_instance, reader, info);
return true;
}
return false;
}
public object GetInstance()
{
return _instance;
}
}
private class NonDefaultConstructorObjectFactory : IObjectFactory
{
private readonly Dictionary<string, SerializableJsonProperty> _serializablePropertiesMap;
private readonly Func<object[], object> _createInstance;
private readonly Func<string, Tuple<IJsonSerializerInternal, int>> _getSerializerAndArgIndex;
private readonly object[] _constructorArguments;
private readonly List<Action<object>> _setPropertyValueActions = new List<Action<object>>();
public NonDefaultConstructorObjectFactory(
Dictionary<string, SerializableJsonProperty> serializablePropertiesMap,
Func<object[], object> createInstance,
Func<string, Tuple<IJsonSerializerInternal, int>> getSerializerAndArgIndex,
int argumentsLength)
{
_serializablePropertiesMap = serializablePropertiesMap;
_createInstance = createInstance;
_getSerializerAndArgIndex = getSerializerAndArgIndex;
_constructorArguments = new object[argumentsLength];
}
public bool SetValue(JsonReader reader, string propertyName, IJsonSerializeOperationInfo info)
{
var serializerAndArgIndex = _getSerializerAndArgIndex(propertyName);
if (serializerAndArgIndex != null)
{
var value = serializerAndArgIndex.Item1.DeserializeObject(reader, info);
_constructorArguments[serializerAndArgIndex.Item2] = value;
return true;
}
SerializableJsonProperty property;
if (_serializablePropertiesMap.TryGetValue(propertyName, out property))
{
var value = property.ReadValue(reader, info);
_setPropertyValueActions.Add(instance => property.SetValue(instance, value));
return true;
}
return false;
}
public object GetInstance()
{
var instance = _createInstance(_constructorArguments);
foreach (var setPropertyValue in _setPropertyValueActions)
{
setPropertyValue(instance);
}
return instance;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
[TestFixture]
public class ElementFindingTest : DriverTestFixture
{
[Test]
public void ShouldReturnTitleOfPageIfSet()
{
driver.Url = xhtmlTestPage;
Assert.AreEqual(driver.Title, "XHTML Test Page");
driver.Url = simpleTestPage;
Assert.AreEqual(driver.Title, "Hello WebDriver");
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateASingleElementThatDoesNotExist()
{
driver.Url = formsPage;
driver.FindElement(By.Id("nonExistantButton"));
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedByText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
//TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented.
System.Threading.Thread.Sleep(500);
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void DriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATime()
{
driver.Url = formsPage;
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("click me")).Click();
//TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented.
System.Threading.Thread.Sleep(500);
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToClickOnLinkIdentifiedById()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
//TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented.
System.Threading.Thread.Sleep(500);
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldThrowAnExceptionWhenThereIsNoLinkToClickAndItIsFoundWithLinkText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.LinkText("Not here either"));
}
[Test]
public void ShouldFindAnElementBasedOnId()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Id("checky"));
Assert.IsFalse(element.Selected);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToFindElementsBasedOnIdIfTheElementIsNotThere()
{
driver.Url = formsPage;
driver.FindElement(By.Id("notThere"));
}
[Test]
public void ShouldBeAbleToFindChildrenOfANode()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("/html/head"));
IWebElement head = elements[0];
ReadOnlyCollection<IWebElement> importedScripts = head.FindElements(By.TagName("script"));
Assert.AreEqual(importedScripts.Count, 2);
}
[Test]
public void ReturnAnEmptyListWhenThereAreNoChildrenOfANode()
{
driver.Url = xhtmlTestPage;
IWebElement table = driver.FindElement(By.Id("table"));
ReadOnlyCollection<IWebElement> rows = table.FindElements(By.TagName("tr"));
Assert.AreEqual(rows.Count, 0);
}
[Test]
public void ShouldFindElementsByName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("checky"));
Assert.AreEqual(element.Value, "furrfu");
}
[Test]
public void ShouldFindElementsByClass()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("extraDiv"));
Assert.IsTrue(element.Text.StartsWith("Another div starts here."));
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheFirstNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameA"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsTheLastNameAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameC"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementsByClassWhenItIsInTheMiddleAmongMany()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("nameBnoise"));
Assert.AreEqual(element.Text, "An H2 title");
}
[Test]
public void ShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
IWebElement element = driver.FindElement(By.ClassName("spaceAround"));
Assert.AreEqual("Spaced out", element.Text);
}
[Test]
public void ShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("spaceAround"));
Assert.AreEqual(1, elements.Count);
Assert.AreEqual("Spaced out", elements[0].Text);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementsByClassWhenTheNameQueriedIsShorterThanCandidateName()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.ClassName("nameB"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByXPath()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.XPath("//div"));
Assert.IsTrue(elements.Count > 1);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.LinkText("click me"));
Assert.IsTrue(elements.Count == 2, "Expected 2 links, got " + elements.Count);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByPartialLinkText()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.PartialLinkText("ick me"));
Assert.IsTrue(elements.Count == 2);
}
[Test]
public void ShouldBeAbleToFindElementByPartialLinkText()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.PartialLinkText("anon"));
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByName()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Name("checky"));
Assert.IsTrue(elements.Count > 1);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsById()
{
driver.Url = nestedPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.Id("2"));
Assert.AreEqual(8, elements.Count);
}
[Test]
public void ShouldBeAbleToFindMultipleElementsByClassName()
{
driver.Url = xhtmlTestPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.ClassName("nameC"));
Assert.IsTrue(elements.Count > 1);
}
[Test]
// You don't want to ask why this is here
public void WhenFindingByNameShouldNotReturnById()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.AreEqual(element.Value, "name");
element = driver.FindElement(By.Id("id-name1"));
Assert.AreEqual(element.Value, "id");
element = driver.FindElement(By.Name("id-name2"));
Assert.AreEqual(element.Value, "name");
element = driver.FindElement(By.Id("id-name2"));
Assert.AreEqual(element.Value, "id");
}
[Test]
public void ShouldFindGrandChildren()
{
driver.Url = formsPage;
IWebElement form = driver.FindElement(By.Id("nested_form"));
form.FindElement(By.Name("x"));
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotFindElementOutSideTree()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.Name("login"));
element.FindElement(By.Name("x"));
}
[Test]
public void ShouldReturnElementsThatDoNotSupportTheNameProperty()
{
driver.Url = nestedPage;
driver.FindElement(By.Name("div1"));
// If this works, we're all good
}
[Test]
public void ShouldFindHiddenElementsByName()
{
driver.Url = formsPage;
driver.FindElement(By.Name("hidden"));
}
[Test]
public void ShouldFindAnElementBasedOnTagName()
{
driver.Url = formsPage;
IWebElement element = driver.FindElement(By.TagName("input"));
Assert.IsNotNull(element);
}
[Test]
public void ShouldfindElementsBasedOnTagName()
{
driver.Url = formsPage;
ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("input"));
Assert.IsNotNull(elements);
}
[Test]
[ExpectedException(typeof(IllegalLocatorException))]
public void FindingElementByCompoundClassNameIsAnError()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.ClassName("a b"));
}
[Test]
[ExpectedException(typeof(IllegalLocatorException))]
public void FindingElementCollectionByCompoundClassNameIsAnError()
{
driver.FindElements(By.ClassName("a b"));
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.LinkText("No href"));
element.Click();
// if any exception is thrown, we won't get this far. Sanity check
Assert.AreEqual("Changed", driver.Title);
}
[Test]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToFindAnElementOnABlankPage()
{
driver.Url = "about:blank";
driver.FindElement(By.TagName("a"));
}
[Test]
[NeedsFreshDriver(BeforeTest = true)]
[ExpectedException(typeof(NoSuchElementException))]
public void ShouldNotBeAbleToLocateASingleElementOnABlankPage()
{
// Note we're on the default start page for the browser at this point.
driver.FindElement(By.Id("nonExistantButton"));
}
[Test]
[Category("Javascript")]
[ExpectedException(typeof(StaleElementReferenceException))]
public void RemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefException()
{
driver.Url = javascriptPage;
IRenderedWebElement toBeDeleted = (IRenderedWebElement)driver.FindElement(By.Id("deleted"));
Assert.IsTrue(toBeDeleted.Displayed);
driver.FindElement(By.Id("delete")).Click();
//TODO (jimevan): this is an ugly sleep. Remove when implicit waiting is implemented.
System.Threading.Thread.Sleep(500);
bool displayedAfterDelete = toBeDeleted.Displayed;
}
[Test]
public void FindingALinkByXpathUsingContainsKeywordShouldWork()
{
driver.Url = nestedPage;
driver.FindElement(By.XPath("//a[contains(.,'hello world')]"));
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToFindAnElementByCssSelector()
{
if (!SupportsSelectorApi())
{
Assert.Ignore("Skipping test: selector API not supported");
}
driver.Url = xhtmlTestPage;
driver.FindElement(By.CssSelector("div.content"));
}
[Test]
[Category("Javascript")]
public void ShouldBeAbleToFindAnElementsByCssSelector()
{
if (!SupportsSelectorApi())
{
Assert.Ignore("Skipping test: selector API not supported");
}
driver.Url = xhtmlTestPage;
driver.FindElements(By.CssSelector("p"));
}
private bool SupportsSelectorApi()
{
return driver is IFindsByCssSelector &&
(bool)((IJavaScriptExecutor)driver).ExecuteScript("return document['querySelector'] !== undefined;");
}
}
}
| |
// 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.Graph.RBAC
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// GroupsOperations operations.
/// </summary>
public partial interface IGroupsOperations
{
/// <summary>
/// Checks whether the specified user, group, contact, or service
/// principal is a direct or a transitive member of the specified
/// group.
/// </summary>
/// <param name='parameters'>
/// Check group membership parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CheckGroupMembershipResult>> IsMemberOfWithHttpMessagesAsync(CheckGroupMembershipParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Remove a memeber from a group. Reference:
/// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#DeleteGroupMember
/// </summary>
/// <param name='groupObjectId'>
/// Group object id
/// </param>
/// <param name='memberObjectId'>
/// Member Object id
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> RemoveMemberWithHttpMessagesAsync(string groupObjectId, string memberObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add a memeber to a group. Reference:
/// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#AddGroupMembers
/// </summary>
/// <param name='groupObjectId'>
/// Group object id
/// </param>
/// <param name='parameters'>
/// Member Object Url as
/// https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> AddMemberWithHttpMessagesAsync(string groupObjectId, GroupAddMemberParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a group in the directory. Reference:
/// http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx
/// </summary>
/// <param name='groupObjectId'>
/// Object id
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string groupObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create a group in the directory. Reference:
/// http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx
/// </summary>
/// <param name='parameters'>
/// Parameters to create a group
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ADGroup>> CreateWithHttpMessagesAsync(GroupCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets list of groups for the current tenant.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ADGroup>>> ListWithHttpMessagesAsync(ODataQuery<ADGroup> odataQuery = default(ODataQuery<ADGroup>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the members of a group.
/// </summary>
/// <param name='objectId'>
/// Group object Id who's members should be retrieved.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AADObject>>> GetGroupMembersWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets group information from the directory.
/// </summary>
/// <param name='objectId'>
/// User objectId to get group information.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ADGroup>> GetWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a collection that contains the Object IDs of the groups of
/// which the group is a member.
/// </summary>
/// <param name='objectId'>
/// Group filtering parameters.
/// </param>
/// <param name='parameters'>
/// Group filtering parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<string>>> GetMemberGroupsWithHttpMessagesAsync(string objectId, GroupGetMemberGroupsParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets list of groups for the current tenant.
/// </summary>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ADGroup>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the members of a group.
/// </summary>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<AADObject>>> GetGroupMembersNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// System.Net.RequestStream
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Reactor.Net
{
public class RequestStream : Stream
{
private byte[] buffer;
private int offset;
private int length;
private long remaining_body;
private bool disposed;
private Stream stream;
internal RequestStream(Stream stream, byte[] buffer, int offset, int length) : this(stream, buffer, offset, length, -1)
{
}
internal RequestStream(Stream stream, byte[] buffer, int offset, int length, long contentlength)
{
this.stream = stream;
this.buffer = buffer;
this.offset = offset;
this.length = length;
this.remaining_body = contentlength;
}
public override bool CanRead
{
get
{
return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
public override void Close()
{
disposed = true;
}
public override void Flush()
{
}
// Returns 0 if we can keep reading from the base stream,
// > 0 if we read something from the buffer.
// -1 if we had a content length set and we finished reading that many bytes.
int FillFromBuffer(byte[] buffer, int off, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (off < 0)
{
throw new ArgumentOutOfRangeException("offset", "< 0");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", "< 0");
}
int len = buffer.Length;
if (off > len)
{
throw new ArgumentException("destination offset is beyond array size");
}
if (off > len - count)
{
throw new ArgumentException("Reading would overrun buffer");
}
if (this.remaining_body == 0)
{
return -1;
}
if (this.length == 0)
{
return 0;
}
int size = Math.Min(this.length, count);
if (this.remaining_body > 0)
{
size = (int)Math.Min(size, this.remaining_body);
}
if (this.offset > this.buffer.Length - size)
{
size = Math.Min(size, this.buffer.Length - this.offset);
}
if (size == 0)
{
return 0;
}
System.Buffer.BlockCopy(this.buffer, this.offset, buffer, off, size);
this.offset += size;
this.length -= size;
if (this.remaining_body > 0)
{
remaining_body -= size;
}
return size;
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (disposed)
{
throw new ObjectDisposedException(typeof(RequestStream).ToString());
}
// Call FillFromBuffer to check for buffer boundaries even when remaining_body is 0
int nread = FillFromBuffer(buffer, offset, count);
if (nread == -1)
{ // No more bytes available (Content-Length)
return 0;
}
else if (nread > 0)
{
return nread;
}
nread = stream.Read(buffer, offset, count);
if (nread > 0 && remaining_body > 0)
{
remaining_body -= nread;
}
return nread;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
{
if (disposed)
{
throw new ObjectDisposedException(typeof(RequestStream).ToString());
}
int nread = FillFromBuffer(buffer, offset, count);
if (nread > 0 || nread == -1)
{
HttpStreamAsyncResult ares = new HttpStreamAsyncResult();
ares.Buffer = buffer;
ares.Offset = offset;
ares.Count = count;
ares.Callback = cback;
ares.State = state;
ares.SynchRead = Math.Max(0, nread);
ares.Complete();
return ares;
}
// Avoid reading past the end of the request to allow
// for HTTP pipelining
if (remaining_body >= 0 && count > remaining_body)
{
count = (int)Math.Min(Int32.MaxValue, remaining_body);
}
return stream.BeginRead(buffer, offset, count, cback, state);
}
public override int EndRead(IAsyncResult ares)
{
if (disposed)
{
throw new ObjectDisposedException(typeof(RequestStream).ToString());
}
if (ares == null)
{
throw new ArgumentNullException("async_result");
}
if (ares is HttpStreamAsyncResult)
{
HttpStreamAsyncResult r = (HttpStreamAsyncResult)ares;
if (!ares.IsCompleted)
{
ares.AsyncWaitHandle.WaitOne();
}
return r.SynchRead;
}
// Close on exception?
int nread = stream.EndRead(ares);
if (remaining_body > 0 && nread > 0)
{
remaining_body -= nread;
}
return nread;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
{
throw new NotSupportedException();
}
public override void EndWrite(IAsyncResult async_result)
{
throw new NotSupportedException();
}
}
}
| |
using Microsoft.CodeAnalysis;
using Semmle.Extraction.CSharp.Entities;
using Semmle.Util;
using System.Collections.Generic;
using System.Linq;
namespace Semmle.Extraction.CSharp
{
/// <summary>
/// Implements the comment processor for associating comments with program elements.
/// Registers locations of comments and program elements,
/// then generates binding information.
/// </summary>
internal class CommentProcessor
{
public void AddComment(CommentLine comment)
{
comments[comment.Location] = comment;
}
// Comments sorted by location.
private readonly SortedDictionary<Location, CommentLine> comments = new SortedDictionary<Location, CommentLine>(new LocationComparer());
// Program elements sorted by location.
private readonly SortedDictionary<Location, Label> elements = new SortedDictionary<Location, Label>(new LocationComparer());
private readonly Dictionary<Label, Key> duplicationGuardKeys = new Dictionary<Label, Key>();
private Key? GetDuplicationGuardKey(Label label)
{
if (duplicationGuardKeys.TryGetValue(label, out var duplicationGuardKey))
return duplicationGuardKey;
return null;
}
private class LocationComparer : IComparer<Location>
{
public int Compare(Location? l1, Location? l2) => CommentProcessor.Compare(l1, l2);
}
/// <summary>
/// Comparer for two locations, allowing them to be inserted into a sorted list.
/// </summary>
/// <param name="l1">First location</param>
/// <param name="l2">Second location</param>
/// <returns><0 if l1 before l2, >0 if l1 after l2, else 0.</returns>
private static int Compare(Location? l1, Location? l2)
{
if (object.ReferenceEquals(l1, l2))
return 0;
if (l1 is null)
return -1;
if (l2 is null)
return 1;
var diff = l1.SourceTree == l2.SourceTree ? 0 : l1.SourceTree!.FilePath.CompareTo(l2.SourceTree!.FilePath);
if (diff != 0)
return diff;
diff = l1.SourceSpan.Start - l2.SourceSpan.Start;
if (diff != 0)
return diff;
return l1.SourceSpan.End - l2.SourceSpan.End;
}
/// <summary>
/// Called by the populator when there is a program element which can have comments.
/// </summary>
/// <param name="elementLabel">The label of the element in the trap file.</param>
/// <param name="duplicationGuardKey">The duplication guard key of the element, if any.</param>
/// <param name="loc">The location of the element.</param>
public void AddElement(Label elementLabel, Key? duplicationGuardKey, Location? loc)
{
if (loc is not null && loc.IsInSource)
elements[loc] = elementLabel;
if (duplicationGuardKey is not null)
duplicationGuardKeys[elementLabel] = duplicationGuardKey;
}
// Ensure that commentBlock and element refer to the same file
// which can happen when processing multiple files.
private static void EnsureSameFile(Comments.CommentBlock commentBlock, ref KeyValuePair<Location, Label>? element)
{
if (element is not null && element.Value.Key.SourceTree != commentBlock.Location.SourceTree)
element = null;
}
/// <summary>
/// Generate the bindings between a comment and program elements.
/// Called once for each commentBlock.
/// </summary>
///
/// <param name="commentBlock">The comment block.</param>
/// <param name="previousElement">The element before the comment block.</param>
/// <param name="nextElement">The element after the comment block.</param>
/// <param name="parentElement">The parent element of the comment block.</param>
/// <param name="callback">Output binding information.</param>
private void GenerateBindings(
Comments.CommentBlock commentBlock,
KeyValuePair<Location, Label>? previousElement,
KeyValuePair<Location, Label>? nextElement,
KeyValuePair<Location, Label>? parentElement,
CommentBindingCallback callback
)
{
EnsureSameFile(commentBlock, ref previousElement);
EnsureSameFile(commentBlock, ref nextElement);
EnsureSameFile(commentBlock, ref parentElement);
if (previousElement is not null)
{
var key = previousElement.Value.Value;
callback(key, GetDuplicationGuardKey(key), commentBlock, CommentBinding.Before);
}
if (nextElement is not null)
{
var key = nextElement.Value.Value;
callback(key, GetDuplicationGuardKey(key), commentBlock, CommentBinding.After);
}
if (parentElement is not null)
{
var key = parentElement.Value.Value;
callback(key, GetDuplicationGuardKey(key), commentBlock, CommentBinding.Parent);
}
// Heuristic to decide which is the "best" element associated with the comment.
KeyValuePair<Location, Label>? bestElement;
if (previousElement is not null && previousElement.Value.Key.EndLine() == commentBlock.Location.StartLine())
{
// 1. If the comment is on the same line as the previous element, use that
bestElement = previousElement;
}
else if (nextElement is not null && nextElement.Value.Key.StartLine() == commentBlock.Location.EndLine())
{
// 2. If the comment is on the same line as the next element, use that
bestElement = nextElement;
}
else if (nextElement is not null && previousElement is not null &&
previousElement.Value.Key.EndLine() + 1 == commentBlock.Location.StartLine() &&
commentBlock.Location.EndLine() + 1 == nextElement.Value.Key.StartLine())
{
// 3. If comment is equally between two elements, use the parentElement
// because it's ambiguous whether the comment refers to the next or previous element
bestElement = parentElement;
}
else if (nextElement is not null && nextElement.Value.Key.StartLine() == commentBlock.Location.EndLine() + 1)
{
// 4. If there is no gap after the comment, use "nextElement"
bestElement = nextElement;
}
else if (previousElement is not null && previousElement.Value.Key.EndLine() + 1 == commentBlock.Location.StartLine())
{
// 5. If there is no gap before the comment, use previousElement
bestElement = previousElement;
}
else
{
// 6. Otherwise, bind the comment to the parent block.
bestElement = parentElement;
/* if parentElement==null, then there is no best element. The comment is effectively orphaned.
*
* This can be caused by comments that are not in a type declaration.
* Due to restrictions in the dbscheme, the comment cannot be associated with the "file"
* which is not an element, and the "using" declarations are not emitted by the extractor.
*/
}
if (bestElement is not null)
{
var label = bestElement.Value.Value;
callback(label, GetDuplicationGuardKey(label), commentBlock, CommentBinding.Best);
}
}
// Stores element nesting information in a stack.
// Top of stack = most nested element, based on Location.
private class ElementStack
{
// Invariant: the top of the stack must be contained by items below it.
private readonly Stack<KeyValuePair<Location, Label>> elementStack = new Stack<KeyValuePair<Location, Label>>();
/// <summary>
/// Add a new element to the stack.
/// </summary>
/// The stack is maintained.
/// <param name="value">The new element to push.</param>
public void Push(KeyValuePair<Location, Label> value)
{
// Maintain the invariant by popping existing elements
while (elementStack.Count > 0 && !elementStack.Peek().Key.Contains(value.Key))
elementStack.Pop();
elementStack.Push(value);
}
/// <summary>
/// Locate the parent of a comment with location l.
/// </summary>
/// <param name="l">The location of the comment.</param>
/// <returns>An element completely containing l, or null if none found.</returns>
public KeyValuePair<Location, Label>? FindParent(Location l) =>
elementStack.Where(v => v.Key.Contains(l)).FirstOrNull();
/// <summary>
/// Finds the element on the stack immediately preceding the comment at l.
/// </summary>
/// <param name="l">The location of the comment.</param>
/// <returns>The element before l, or null.</returns>
public KeyValuePair<Location, Label>? FindBefore(Location l)
{
return elementStack
.Where(v => v.Key.SourceSpan.End < l.SourceSpan.Start)
.LastOrNull();
}
/// <summary>
/// Finds the element after the comment.
/// </summary>
/// <param name="comment">The location of the comment.</param>
/// <param name="next">The next element.</param>
/// <returns>The next element.</returns>
public KeyValuePair<Location, Label>? FindAfter(Location comment, KeyValuePair<Location, Label>? next)
{
var p = FindParent(comment);
return next.HasValue && p.HasValue && p.Value.Key.Before(next.Value.Key) ? null : next;
}
}
// Generate binding information for one CommentBlock.
private void GenerateBindings(
Comments.CommentBlock block,
ElementStack elementStack,
KeyValuePair<Location, Label>? nextElement,
CommentBindingCallback cb
)
{
if (block.CommentLines.Any())
{
GenerateBindings(
block,
elementStack.FindBefore(block.Location),
elementStack.FindAfter(block.Location, nextElement),
elementStack.FindParent(block.Location),
cb);
}
}
/// <summary>
/// Process comments up until nextElement.
/// Group comments into blocks, and associate blocks with elements.
/// </summary>
///
/// <param name="commentEnumerator">Enumerator for all comments in the program.</param>
/// <param name="nextElement">The next element in the list.</param>
/// <param name="elementStack">A stack of nested program elements.</param>
/// <param name="cb">Where to send the results.</param>
/// <returns>true if there are more comments to process, false otherwise.</returns>
private bool GenerateBindings(
IEnumerator<KeyValuePair<Location, CommentLine>> commentEnumerator,
KeyValuePair<Location, Label>? nextElement,
ElementStack elementStack,
CommentBindingCallback cb
)
{
Comments.CommentBlock? block = null;
// Iterate comments until the commentEnumerator has gone past nextElement
while (nextElement is null || Compare(commentEnumerator.Current.Value.Location, nextElement.Value.Key) < 0)
{
if (block is null)
block = new Comments.CommentBlock(commentEnumerator.Current.Value);
if (!block.CombinesWith(commentEnumerator.Current.Value))
{
// Start of a new block, so generate the bindings for the old block first.
GenerateBindings(block, elementStack, nextElement, cb);
block = new Comments.CommentBlock(commentEnumerator.Current.Value);
}
else
{
block.AddCommentLine(commentEnumerator.Current.Value);
}
// Get the next comment.
if (!commentEnumerator.MoveNext())
{
// If there are no more comments, generate the remaining bindings and return false.
GenerateBindings(block, elementStack, nextElement, cb);
return false;
}
}
if (!(block is null))
GenerateBindings(block, elementStack, nextElement, cb);
return true;
}
/// <summary>
/// Merge comments into blocks and associate comment blocks with program elements.
/// </summary>
/// <param name="cb">Callback for the binding information</param>
public void GenerateBindings(CommentBindingCallback cb)
{
/* Algorithm:
* Do a merge of elements and comments, which are both sorted in location order.
*
* Iterate through all elements, and iterate all comment lines between adjacent pairs of elements.
* Maintain a stack of elements, such that the top of the stack must be fully nested in the
* element below it. This enables comments to be associated with the "parent" element, as well as
* elements before, after and "best" element match for a comment.
*
* This is an O(n) algorithm because the list of elements and comments are traversed once.
* (Note that comment processing is O(n.log n) overall due to dictionary of elements and comments.)
*/
var elementStack = new ElementStack();
using IEnumerator<KeyValuePair<Location, Label>> elementEnumerator = elements.GetEnumerator();
using IEnumerator<KeyValuePair<Location, CommentLine>> commentEnumerator = comments.GetEnumerator();
if (!commentEnumerator.MoveNext())
{
// There are no comments to process.
return;
}
while (elementEnumerator.MoveNext())
{
if (!GenerateBindings(commentEnumerator, elementEnumerator.Current, elementStack, cb))
{
// No more comments to process.
return;
}
elementStack.Push(elementEnumerator.Current);
}
// Generate remaining comments at end of file
GenerateBindings(commentEnumerator, null, elementStack, cb);
}
}
/// <summary>
/// Callback for generated comment associations.
/// </summary>
/// <param name="elementLabel">The label of the element</param>
/// <param name="duplicationGuardKey">The duplication guard key of the element, if any</param>
/// <param name="commentBlock">The comment block associated with the element</param>
/// <param name="binding">The relationship between the commentblock and the element</param>
internal delegate void CommentBindingCallback(Label elementLabel, Key? duplicationGuardKey, Comments.CommentBlock commentBlock, CommentBinding binding);
}
| |
//
// SourceWatcher.cs
//
// Authors:
// Christian Martellini <christian.martellini@gmail.com>
// Alexander Kojevnikov <alexander@kojevnikov.com>
//
// Copyright (C) 2009 Christian Martellini
// Copyright (C) 2009 Alexander Kojevnikov
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Library;
using Banshee.Metadata;
using Banshee.Query;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Streaming;
namespace Banshee.LibraryWatcher
{
public class SourceWatcher : IDisposable
{
private readonly LibraryImportManager import_manager;
private readonly LibrarySource library;
private readonly FileSystemWatcher watcher;
private readonly ManualResetEvent handle;
private readonly Thread watch_thread;
private readonly Queue<QueueItem> queue = new Queue<QueueItem> ();
private readonly TimeSpan delay = TimeSpan.FromMilliseconds (1000);
private bool active;
private bool disposed;
private class QueueItem
{
public DateTime When;
public WatcherChangeTypes ChangeType;
public string OldFullPath;
public string FullPath;
public string MetadataHash;
}
public SourceWatcher (LibrarySource library)
{
this.library = library;
handle = new ManualResetEvent(false);
string path = library.BaseDirectoryWithSeparator;
if (String.IsNullOrEmpty (path)) {
throw new Exception ("Will not create LibraryWatcher for the blank directory");
}
string home = Environment.GetFolderPath (Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
if (path == home) {
throw new Exception ("Will not create LibraryWatcher for the entire home directory");
}
string root = Path.GetPathRoot (Environment.CurrentDirectory);
if (path == root || path == root + Path.DirectorySeparatorChar) {
throw new Exception ("Will not create LibraryWatcher for the entire root directory");
}
if (!Banshee.IO.Directory.Exists (path)) {
throw new Exception ("Will not create LibraryWatcher for non-existent directory");
}
import_manager = ServiceManager.Get<LibraryImportManager> ();
watcher = new FileSystemWatcher (path);
watcher.IncludeSubdirectories = true;
watcher.Changed += OnModified;
watcher.Created += OnModified;
watcher.Deleted += OnModified;
watcher.Renamed += OnModified;
active = true;
watch_thread = new Thread (new ThreadStart (Watch));
watch_thread.Name = String.Format ("LibraryWatcher for {0}", library.Name);
watch_thread.IsBackground = true;
watch_thread.Start ();
}
#region Public Methods
public void Dispose ()
{
if (!disposed) {
active = false;
watcher.Changed -= OnModified;
watcher.Created -= OnModified;
watcher.Deleted -= OnModified;
watcher.Renamed -= OnModified;
lock (queue) {
queue.Clear ();
}
watcher.Dispose ();
disposed = true;
}
}
#endregion
#region Private Methods
private readonly double MAX_TIME_BETWEEN_CHANGED_EVENTS = TimeSpan.FromSeconds (10).TotalMilliseconds;
Dictionary<string, System.Timers.Timer> created_items_bag = new Dictionary<string, System.Timers.Timer> ();
private System.Timers.Timer CreateTimer (string fullpath)
{
var timer = new System.Timers.Timer (MAX_TIME_BETWEEN_CHANGED_EVENTS);
timer.Elapsed += (sender, e) => TimeUpForChangedEvent (fullpath);
return timer;
}
private void OnCreation (string fullpath)
{
var timer = CreateTimer (fullpath);
lock (created_items_bag) {
created_items_bag [fullpath] = timer;
}
timer.AutoReset = false;
timer.Start ();
}
private void TimeUpForChangedEvent (string fullpath)
{
lock (created_items_bag) {
created_items_bag [fullpath].Stop ();
created_items_bag [fullpath].Dispose ();
created_items_bag.Remove (fullpath);
}
var fake_args = new FileSystemEventArgs (WatcherChangeTypes.Created,
System.IO.Path.GetDirectoryName (fullpath),
System.IO.Path.GetFileName (fullpath));
EnqueueAffectedElement (fake_args);
}
private void OnModified (object source, FileSystemEventArgs args)
{
if (args.ChangeType == WatcherChangeTypes.Created) {
OnCreation (args.FullPath);
return;
} else if (args.ChangeType == WatcherChangeTypes.Changed) {
lock (created_items_bag) {
System.Timers.Timer timer;
if (created_items_bag.TryGetValue (args.FullPath, out timer)) {
// A file we saw being created was modified, restart the timer
timer.Stop ();
timer.Start ();
return;
}
}
}
EnqueueAffectedElement (args);
}
private void EnqueueAffectedElement (FileSystemEventArgs args)
{
var item = new QueueItem {
When = DateTime.Now,
ChangeType = args.ChangeType,
FullPath = args.FullPath,
OldFullPath = args is RenamedEventArgs ? ((RenamedEventArgs)args).OldFullPath : args.FullPath
};
lock (queue) {
queue.Enqueue (item);
}
handle.Set ();
Hyena.Log.DebugFormat ("Watcher: {0} {1}{2}",
item.ChangeType, args is RenamedEventArgs ? item.OldFullPath + " => " : "", item.FullPath);
}
private void Watch ()
{
watcher.EnableRaisingEvents = true;
while (active) {
WatcherChangeTypes change_types = 0;
while (queue.Count > 0) {
QueueItem item;
lock (queue) {
item = queue.Dequeue ();
}
int sleep = (int) (item.When + delay - DateTime.Now).TotalMilliseconds;
if (sleep > 0) {
Hyena.Log.DebugFormat ("Watcher: sleeping {0}ms", sleep);
Thread.Sleep (sleep);
}
try {
if (item.ChangeType == WatcherChangeTypes.Changed) {
UpdateTrack (item.FullPath);
} else if (item.ChangeType == WatcherChangeTypes.Created) {
AddTrack (item.FullPath);
} else if (item.ChangeType == WatcherChangeTypes.Deleted) {
RemoveTrack (item.FullPath);
} else if (item.ChangeType == WatcherChangeTypes.Renamed) {
RenameTrack (item.OldFullPath, item.FullPath);
}
change_types |= item.ChangeType;
} catch (Exception e) {
Log.Error (String.Format ("Watcher: Error processing {0}", item.FullPath), e.Message, false);
}
}
if ((change_types & WatcherChangeTypes.Deleted) > 0) {
library.NotifyTracksDeleted ();
}
if ((change_types & (WatcherChangeTypes.Renamed |
WatcherChangeTypes.Created | WatcherChangeTypes.Changed)) > 0) {
library.NotifyTracksChanged ();
}
handle.WaitOne ();
handle.Reset ();
}
}
private void UpdateTrack (string track)
{
using (var reader = ServiceManager.DbConnection.Query (
DatabaseTrackInfo.Provider.CreateFetchCommand (String.Format (
"CoreTracks.PrimarySourceID = ? AND {0} = ? LIMIT 1",
BansheeQuery.UriField.Column)),
library.DbId, new SafeUri (track).AbsoluteUri)) {
if (reader.Read ()) {
var track_info = DatabaseTrackInfo.Provider.Load (reader);
if (Banshee.IO.File.GetModifiedTime (track_info.Uri) > track_info.FileModifiedStamp) {
using (var file = StreamTagger.ProcessUri (track_info.Uri)) {
StreamTagger.TrackInfoMerge (track_info, file, false,
SaveTrackMetadataService.WriteRatingsEnabled.Value,
SaveTrackMetadataService.WritePlayCountsEnabled.Value);
}
track_info.LastSyncedStamp = DateTime.Now;
track_info.Save (false);
}
}
}
}
private void AddTrack (string track)
{
import_manager.ImportTrack (track);
// Trigger file rename.
string uri = new SafeUri(track).AbsoluteUri;
var command = new HyenaSqliteCommand (String.Format (@"
UPDATE CoreTracks
SET DateUpdatedStamp = LastSyncedStamp + 1
WHERE {0} = ?",
BansheeQuery.UriField.Column), uri);
ServiceManager.DbConnection.Execute (command);
}
private void RemoveTrack (string track)
{
string uri = new SafeUri(track).AbsoluteUri;
string hash_sql = String.Format (
@"SELECT TrackID, MetadataHash FROM CoreTracks WHERE {0} = ? LIMIT 1",
BansheeQuery.UriField.Column
);
long track_id = 0;
string hash = null;
using (var reader = new HyenaDataReader (ServiceManager.DbConnection.Query (hash_sql, uri))) {
if (reader.Read ()) {
track_id = reader.Get<long> (0);
hash = reader.Get<string> (1);
}
}
if (hash != null) {
lock (queue) {
var item = queue.FirstOrDefault (
i => i.ChangeType == WatcherChangeTypes.Created && GetMetadataHash (i) == hash);
if (item != null) {
item.ChangeType = WatcherChangeTypes.Renamed;
item.OldFullPath = track;
return;
}
}
}
string delete_sql = @"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, " + BansheeQuery.UriField.Column + @"
FROM CoreTracks WHERE TrackID IN ({0})
;
DELETE FROM CoreTracks WHERE TrackID IN ({0})";
// If track_id is 0, it's a directory.
HyenaSqliteCommand delete_command;
if (track_id > 0) {
delete_command = new HyenaSqliteCommand (String.Format (delete_sql,
"?"), DateTime.Now, track_id, track_id);
} else {
string pattern = StringUtil.EscapeLike (uri) + "/_%";
string select_sql = String.Format (@"SELECT TrackID FROM CoreTracks WHERE {0} LIKE ? ESCAPE '\'",
BansheeQuery.UriField.Column);
delete_command = new HyenaSqliteCommand (String.Format (delete_sql, select_sql),
DateTime.Now, pattern, pattern);
}
ServiceManager.DbConnection.Execute (delete_command);
}
private void RenameTrack(string oldFullPath, string fullPath)
{
if (oldFullPath == fullPath) {
// FIXME: bug in Mono, see bnc#322330
return;
}
string old_uri = new SafeUri (oldFullPath).AbsoluteUri;
string new_uri = new SafeUri (fullPath).AbsoluteUri;
string pattern = StringUtil.EscapeLike (old_uri) + "%";
var rename_command = new HyenaSqliteCommand (String.Format (@"
UPDATE CoreTracks
SET Uri = REPLACE ({0}, ?, ?),
DateUpdatedStamp = ?
WHERE {0} LIKE ? ESCAPE '\'",
BansheeQuery.UriField.Column),
old_uri, new_uri, DateTime.Now, pattern);
ServiceManager.DbConnection.Execute (rename_command);
}
private string GetMetadataHash (QueueItem item)
{
if (item.ChangeType == WatcherChangeTypes.Created && item.MetadataHash == null) {
var uri = new SafeUri (item.FullPath);
if (DatabaseImportManager.IsWhiteListedFile (item.FullPath) && Banshee.IO.File.Exists (uri)) {
var track = new TrackInfo ();
using (var file = StreamTagger.ProcessUri (uri)) {
StreamTagger.TrackInfoMerge (track, file);
}
item.MetadataHash = track.MetadataHash;
}
}
return item.MetadataHash;
}
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using Windows.Security.Credentials;
using Windows.Security.Authentication.Web.Core;
using System;
using Windows.Storage;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.Security.Authentication.Web.Provider;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Accounts
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class SingleMicrosoftAccountScenario : Page
{
private MainPage rootPage;
// To obtain Microsoft account tokens, you must register your application online
// Then, you must associate the app with the store.
const string MicrosoftAccountProviderId = "https://login.microsoft.com";
const string ConsumerAuthority = "consumers";
const string AccountScopeRequested = "service::wl.basic::DELEGATION";
const string AccountClientId = "none";
const string StoredAccountKey = "accountid";
public SingleMicrosoftAccountScenario()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
// The AccountCommandsRequested event triggers before the Accounts settings pane is displayed
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;
}
private void Button_ShowAccountSettings(object sender, RoutedEventArgs e)
{
((Button)sender).IsEnabled = false;
rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage);
AccountsSettingsPane.Show();
((Button)sender).IsEnabled = true;
}
private async void Button_Reset(object sender, RoutedEventArgs e)
{
((Button)sender).IsEnabled = false;
rootPage.NotifyUser("Resetting...", NotifyType.StatusMessage);
await LogoffAndRemoveAccount();
((Button)sender).IsEnabled = true;
}
// This event handler is called when the Account settings pane is to be launched.
private async void OnAccountCommandsRequested(
AccountsSettingsPane sender,
AccountsSettingsPaneCommandsRequestedEventArgs e)
{
// In order to make async calls within this callback, the deferral object is needed
AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
// This scenario only lets the user have one account at a time.
// If there already is an account, we do not include a provider in the list
// This will prevent the add account button from showing up.
bool isPresent = ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey);
if (isPresent)
{
await AddWebAccount(e);
}
else
{
await AddWebAccountProvider(e);
}
AddLinksAndDescription(e);
deferral.Complete();
}
private async Task AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
// FindAccountProviderAsync returns the WebAccountProvider of an installed plugin
// The Provider and Authority specifies the specific plugin
// This scenario only supports Microsoft accounts.
// The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin.
// If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null
WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
e.WebAccountProviderCommands.Add(providerCommand);
}
private async Task AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
String accountID = (String)ApplicationData.Current.LocalSettings.Values[StoredAccountKey];
WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID);
if (account == null)
{
// The account has most likely been deleted in Windows settings
// Unless there would be significant data loss, you should just delete the account
// If there would be significant data loss, prompt the user to either re-add the account, or to remove it
ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey);
}
WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove);
e.WebAccountCommands.Add(command);
}
private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
e.HeaderText = "Describe what adding an account to your application will do for the user";
// You can add links such as privacy policy, help, general account settings
e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy Policy", PrivacyPolicyInvoked));
e.Commands.Add(new SettingsCommand("otherlink", "Other Link", OtherLinkInvoked));
}
private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
{
// ClientID is ignored by MSA
await RequestTokenAndSaveAccount(command.WebAccountProvider, AccountScopeRequested, AccountClientId);
}
private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args)
{
if (args.Action == WebAccountAction.Remove)
{
rootPage.NotifyUser("Removing account", NotifyType.StatusMessage);
await LogoffAndRemoveAccount();
}
}
private void PrivacyPolicyInvoked(IUICommand command)
{
rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage);
}
private void OtherLinkInvoked(IUICommand command)
{
rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage);
}
private async Task RequestTokenAndSaveAccount(WebAccountProvider Provider, String Scope, String ClientID)
{
try
{
WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);
rootPage.NotifyUser("Requesting Web Token", NotifyType.StatusMessage);
// If the user selected a specific account, RequestTokenAsync will return a token for that account.
// The user may be prompted for credentials or to authorize using that account with your app
// If the user selected a provider, the user will be prompted for credentials to login to a new account
WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
// If a token was successfully returned, then store the WebAccount Id into local app data
// This Id can be used to retrieve the account whenever needed. To later get a token with that account
// First retrieve the account with FindAccountAsync, and include that webaccount
// as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync
if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
{
ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey);
ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = webTokenRequestResult.ResponseData[0].WebAccount.Id;
}
OutputTokenResult(webTokenRequestResult);
}
catch (Exception ex)
{
rootPage.NotifyUser("Web Token request failed: " + ex.Message, NotifyType.ErrorMessage);
}
}
private void OutputTokenResult(WebTokenRequestResult result)
{
if (result.ResponseStatus == WebTokenRequestStatus.Success)
{
rootPage.NotifyUser("Web Token request successful for user: " + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
SignInButton.Content = "Account";
}
else
{
rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage);
}
}
private async Task LogoffAndRemoveAccount()
{
if (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey))
{
WebAccountProvider providertoDelete = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
WebAccount accountToDelete = await WebAuthenticationCoreManager.FindAccountAsync(providertoDelete, (string)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]);
if(accountToDelete != null)
{
await accountToDelete.SignOutAsync();
}
ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey);
SignInButton.Content = "Sign in";
}
}
}
}
| |
// 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 Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1707: Identifiers should not contain underscores
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class IdentifiersShouldNotContainUnderscoresAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1707";
private static readonly IImmutableSet<string> s_GlobalAsaxSpecialMethodNames =
ImmutableHashSet.Create(
"Application_AuthenticateRequest",
"Application_BeginRequest",
"Application_End",
"Application_EndRequest",
"Application_Error",
"Application_Init",
"Application_Start",
"Session_End",
"Session_Start");
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageAssembly = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeTypeParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMethodTypeParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDelegateParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor AssemblyRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageAssembly,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor NamespaceRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageNamespace,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageType,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageMember,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor TypeTypeParameterRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageTypeTypeParameter,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MethodTypeParameterRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageMethodTypeParameter,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor MemberParameterRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageMemberParameter,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor DelegateParameterRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageDelegateParameter,
DiagnosticCategory.Naming,
RuleLevel.IdeHidden_BulkConfigurable,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AssemblyRule, NamespaceRule, TypeRule, MemberRule, TypeTypeParameterRule, MethodTypeParameterRule, MemberParameterRule, DelegateParameterRule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterSymbolAction(symbolAnalysisContext =>
{
var symbol = symbolAnalysisContext.Symbol;
// FxCop compat: only analyze externally visible symbols by default
// Note all the descriptors/rules for this analyzer have the same ID and category and hence
// will always have identical configured visibility.
if (!symbol.MatchesConfiguredVisibility(symbolAnalysisContext.Options, AssemblyRule, symbolAnalysisContext.Compilation, symbolAnalysisContext.CancellationToken))
{
return;
}
switch (symbol.Kind)
{
case SymbolKind.Namespace:
{
if (ContainsUnderScore(symbol.Name))
{
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(NamespaceRule, symbol.ToDisplayString()));
}
return;
}
case SymbolKind.NamedType:
{
var namedType = (INamedTypeSymbol)symbol;
AnalyzeTypeParameters(symbolAnalysisContext, namedType.TypeParameters);
if (namedType.TypeKind == TypeKind.Delegate &&
namedType.DelegateInvokeMethod != null)
{
AnalyzeParameters(symbolAnalysisContext, namedType.DelegateInvokeMethod.Parameters);
}
if (!ContainsUnderScore(symbol.Name))
{
return;
}
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(TypeRule, symbol.ToDisplayString()));
return;
}
case SymbolKind.Field:
{
var fieldSymbol = (IFieldSymbol)symbol;
if (ContainsUnderScore(symbol.Name) && (fieldSymbol.IsConst || (fieldSymbol.IsStatic && fieldSymbol.IsReadOnly)))
{
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
return;
}
return;
}
default:
{
if (symbol is IMethodSymbol methodSymbol)
{
if (methodSymbol.IsOperator())
{
// Do not flag for operators.
return;
}
if (methodSymbol.MethodKind == MethodKind.Conversion)
{
// Do not flag for conversion methods generated for operators.
return;
}
AnalyzeParameters(symbolAnalysisContext, methodSymbol.Parameters);
AnalyzeTypeParameters(symbolAnalysisContext, methodSymbol.TypeParameters);
if (s_GlobalAsaxSpecialMethodNames.Contains(methodSymbol.Name) &&
methodSymbol.ContainingType.Inherits(symbolAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebHttpApplication)))
{
// Do not flag the convention based web methods.
return;
}
}
if (symbol is IPropertySymbol propertySymbol)
{
AnalyzeParameters(symbolAnalysisContext, propertySymbol.Parameters);
}
if (!ContainsUnderScore(symbol.Name) || IsInvalidSymbol(symbol, symbolAnalysisContext))
{
return;
}
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
return;
}
}
},
SymbolKind.Namespace, // Namespace
SymbolKind.NamedType, //Type
SymbolKind.Method, SymbolKind.Property, SymbolKind.Field, SymbolKind.Event // Members
);
analysisContext.RegisterCompilationAction(compilationAnalysisContext =>
{
var compilation = compilationAnalysisContext.Compilation;
if (ContainsUnderScore(compilation.AssemblyName))
{
compilationAnalysisContext.ReportDiagnostic(compilation.Assembly.CreateDiagnostic(AssemblyRule, compilation.AssemblyName));
}
});
}
private static bool IsInvalidSymbol(ISymbol symbol, SymbolAnalysisContext context)
{
// Note all the descriptors/rules for this analyzer have the same ID and category and hence
// will always have identical configured visibility.
var matchesConfiguration = symbol.MatchesConfiguredVisibility(context.Options, AssemblyRule, context.Compilation, context.CancellationToken);
return (!(matchesConfiguration && !symbol.IsOverride)) ||
symbol.IsAccessorMethod() || symbol.IsImplementationOfAnyInterfaceMember();
}
private static void AnalyzeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<IParameterSymbol> parameters)
{
foreach (var parameter in parameters)
{
if (ContainsUnderScore(parameter.Name) && !parameter.IsSymbolWithSpecialDiscardName())
{
var containingType = parameter.ContainingType;
// Parameter in Delegate
if (containingType.TypeKind == TypeKind.Delegate)
{
if (containingType.IsPublic())
{
symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(DelegateParameterRule, containingType.ToDisplayString(), parameter.Name));
}
}
else if (!IsInvalidSymbol(parameter.ContainingSymbol, symbolAnalysisContext))
{
symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(MemberParameterRule, parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), parameter.Name));
}
}
}
}
private static void AnalyzeTypeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<ITypeParameterSymbol> typeParameters)
{
foreach (var typeParameter in typeParameters)
{
if (ContainsUnderScore(typeParameter.Name))
{
var containingSymbol = typeParameter.ContainingSymbol;
if (containingSymbol.Kind == SymbolKind.NamedType)
{
if (containingSymbol.IsPublic())
{
symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(TypeTypeParameterRule, containingSymbol.ToDisplayString(), typeParameter.Name));
}
}
else if (containingSymbol.Kind == SymbolKind.Method && !IsInvalidSymbol(containingSymbol, symbolAnalysisContext))
{
symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(MethodTypeParameterRule, containingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), typeParameter.Name));
}
}
}
}
private static bool ContainsUnderScore(string identifier)
{
return identifier.IndexOf('_') != -1;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 10/11/2009 10:08:43 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
namespace DotSpatial.Symbology
{
/// <summary>
/// DrawingScheme
/// </summary>
public abstract class Scheme : LegendItem
{
#region Private Variables
private List<Break> _breaks; // A temporary list for helping construction of schemes.
private EditorSettings _editorSettings;
private Statistics _statistics;
private List<double> _values;
#endregion
#region Nested type: Break
/// <summary>
/// Breaks for value ranges
/// </summary>
protected class Break
{
/// <summary>
/// A double value for the maximum value for the break
/// </summary>
public double? Maximum { get; set; }
/// <summary>
/// The string name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Creates a new instance of a break
/// </summary>
public Break()
{
Name = string.Empty;
Maximum = 0;
}
/// <summary>
/// Creates a new instance of a break with a given name
/// </summary>
/// <param name="name">The string name for the break</param>
public Break(string name)
{
Name = name;
Maximum = 0;
}
}
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DrawingScheme
/// </summary>
protected Scheme()
{
base.LegendSymbolMode = SymbolMode.None;
LegendType = LegendType.Scheme;
_statistics = new Statistics();
}
#endregion
#region Methods
/// <summary>
/// Creates the category using a random fill color
/// </summary>
/// <param name="fillColor">The base color to use for creating the category</param>
/// <param name="size">For points this is the larger dimension, for lines this is the largest width</param>
/// <returns>A new IFeatureCategory that matches the type of this scheme</returns>
public virtual ICategory CreateNewCategory(Color fillColor, double size)
{
// This method should be overridden in child classes
return null;
}
/// <summary>
/// Draws the regular symbolizer for the specified cateogry to the specified graphics
/// surface in the specified bounding rectangle.
/// </summary>
/// <param name="index">The integer index of the feature to draw.</param>
/// <param name="g">The Graphics object to draw to</param>
/// <param name="bounds">The rectangular bounds to draw in</param>
public abstract void DrawCategory(int index, Graphics g, Rectangle bounds);
/// <summary>
/// Adds a new scheme, assuming that the new scheme is the correct type.
/// </summary>
/// <param name="category">The category to add</param>
public abstract void AddCategory(ICategory category);
/// <summary>
/// Reduces the index value of the specified category by 1 by
/// exchaning it with the category before it. If there is no
/// category before it, then this does nothing.
/// </summary>
/// <param name="category">The category to decrease the index of</param>
public abstract bool DecreaseCategoryIndex(ICategory category);
/// <summary>
/// Removes the specified category
/// </summary>
/// <param name="category">The category to insert</param>
public abstract void RemoveCategory(ICategory category);
/// <summary>
/// Inserts the category at the specified index
/// </summary>
/// <param name="index">The integer index where the category should be inserted</param>
/// <param name="category">The category to insert</param>
public abstract void InsertCategory(int index, ICategory category);
/// <summary>
/// Re-orders the specified member by attempting to exchange it with the next higher
/// index category. If there is no higher index, this does nothing.
/// </summary>
/// <param name="category">The category to increase the index of</param>
public abstract bool IncreaseCategoryIndex(ICategory category);
/// <summary>
/// Suspends the category events
/// </summary>
public abstract void SuspendEvents();
/// <summary>
/// Resumes the category events
/// </summary>
public abstract void ResumeEvents();
/// <summary>
/// Clears the categories
/// </summary>
public abstract void ClearCategories();
/// <summary>
/// Generates the break categories for this scheme
/// </summary>
protected void CreateBreakCategories()
{
int count = EditorSettings.NumBreaks;
switch (EditorSettings.IntervalMethod)
{
case IntervalMethod.EqualFrequency:
Breaks = GetQuantileBreaks(count);
break;
case IntervalMethod.NaturalBreaks:
Breaks = GetNaturalBreaks(count);
break;
default:
Breaks = GetEqualBreaks(count);
break;
}
ApplyBreakSnapping();
SetBreakNames(Breaks);
List<Color> colorRamp = GetColorSet(count);
List<double> sizeRamp = GetSizeSet(count);
ClearCategories();
int colorIndex = 0;
Break prevBreak = null;
foreach (Break brk in Breaks)
{
//get the color for the category
Color randomColor = colorRamp[colorIndex];
double randomSize = sizeRamp[colorIndex];
ICategory cat = CreateNewCategory(randomColor, randomSize);
if (cat != null)
{
//cat.SelectionSymbolizer = _selectionSymbolizer.Copy();
cat.LegendText = brk.Name;
if (prevBreak != null) cat.Minimum = prevBreak.Maximum;
cat.Maximum = brk.Maximum;
cat.Range.MaxIsInclusive = true;
cat.ApplyMinMax(EditorSettings);
AddCategory(cat);
}
prevBreak = brk;
colorIndex++;
}
}
/// <summary>
/// THe defaul
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
protected virtual List<double> GetSizeSet(int count)
{
List<double> result = new List<double>();
for (int i = 0; i < count; i++)
{
result.Add(20);
}
return result;
}
/// <summary>
/// Creates a list of generated colors according to the convention
/// specified in the EditorSettings.
/// </summary>
/// <param name="count">The integer count of the number of colors to create.</param>
/// <returns>The list of colors created.</returns>
protected List<Color> GetColorSet(int count)
{
List<Color> colorRamp;
if (EditorSettings.UseColorRange)
{
if (!EditorSettings.RampColors)
{
colorRamp = CreateRandomColors(count);
}
else if (!EditorSettings.HueSatLight)
{
colorRamp = CreateRampColors(count, EditorSettings.StartColor, EditorSettings.EndColor);
}
else
{
Color cStart = EditorSettings.StartColor;
Color cEnd = EditorSettings.EndColor;
colorRamp = CreateRampColors(count, cStart.GetSaturation(), cStart.GetBrightness(),
(int)cStart.GetHue(),
cEnd.GetSaturation(), cEnd.GetBrightness(), (int)cEnd.GetHue(),
EditorSettings.HueShift, cStart.A, cEnd.A);
}
}
else
{
colorRamp = GetDefaultColors(count);
}
return colorRamp;
}
/// <summary>
/// Uses the settings on this scheme to create a random category.
/// </summary>
/// <returns>A new ICategory</returns>
public abstract ICategory CreateRandomCategory();
/// <summary>
/// Creates the colors in the case where the color range controls are not being used.
/// This can be overriddend for handling special cases like ponit and line symbolizers
/// that should be using the template colors.
/// </summary>
/// <param name="count">The integer count to use</param>
/// <returns></returns>
protected virtual List<Color> GetDefaultColors(int count)
{
return EditorSettings.RampColors ? CreateUnboundedRampColors(count) : CreateUnboundedRandomColors(count);
}
/// <summary>
/// The default behavior for creating ramp colors is to create colors in the mid-range for
/// both lightness and saturation, but to have the full range of hue
/// </summary>
/// <param name="numColors"></param>
/// <returns></returns>
private static List<Color> CreateUnboundedRampColors(int numColors)
{
return CreateRampColors(numColors, .25f, .25f, 0, .75f, .75f, 360, 0, 255, 255);
}
private static List<Color> CreateUnboundedRandomColors(int numColors)
{
Random rnd = new Random(DateTime.Now.Millisecond);
List<Color> result = new List<Color>(numColors);
for (int i = 0; i < numColors; i++)
{
result.Add(rnd.NextColor());
}
return result;
}
private List<Color> CreateRandomColors(int numColors)
{
List<Color> result = new List<Color>(numColors);
Random rnd = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < numColors; i++)
{
result.Add(CreateRandomColor(rnd));
}
return result;
}
/// <summary>
/// Creates a random color, but accepts a given random class instead of creating a new one.
/// </summary>
/// <param name="rnd"></param>
/// <returns></returns>
protected Color CreateRandomColor(Random rnd)
{
Color startColor = EditorSettings.StartColor;
Color endColor = EditorSettings.EndColor;
if (EditorSettings.HueSatLight)
{
double hLow = startColor.GetHue();
double dH = endColor.GetHue() - hLow;
double sLow = startColor.GetSaturation();
double ds = endColor.GetSaturation() - sLow;
double lLow = startColor.GetBrightness();
double dl = endColor.GetBrightness() - lLow;
double aLow = (startColor.A) / 255.0;
double da = (endColor.A - aLow) / 255.0;
return SymbologyGlobal.ColorFromHsl(rnd.NextDouble() * dH + hLow, rnd.NextDouble() * ds + sLow,
rnd.NextDouble() * dl + lLow).ToTransparent((float)(rnd.NextDouble() * da + aLow));
}
int rLow = Math.Min(startColor.R, endColor.R);
int rHigh = Math.Max(startColor.R, endColor.R);
int gLow = Math.Min(startColor.G, endColor.G);
int gHigh = Math.Max(startColor.G, endColor.G);
int bLow = Math.Min(startColor.B, endColor.B);
int bHigh = Math.Max(startColor.B, endColor.B);
int iaLow = Math.Min(startColor.A, endColor.A);
int aHigh = Math.Max(startColor.A, endColor.A);
return Color.FromArgb(rnd.Next(iaLow, aHigh), rnd.Next(rLow, rHigh), rnd.Next(gLow, gHigh), rnd.Next(bLow, bHigh));
}
private static List<Color> CreateRampColors(int numColors, Color startColor, Color endColor)
{
List<Color> result = new List<Color>(numColors);
double dR = (endColor.R - (double)startColor.R) / numColors;
double dG = (endColor.G - (double)startColor.G) / numColors;
double dB = (endColor.B - (double)startColor.B) / numColors;
double dA = (endColor.A - (double)startColor.A) / numColors;
for (int i = 0; i < numColors; i++)
{
result.Add(Color.FromArgb((int)(startColor.A + dA * i), (int)(startColor.R + dR * i), (int)(startColor.G + dG * i), (int)(startColor.B + dB * i)));
}
return result;
}
/// <summary>
/// Applies the snapping rule directly to the categories, based on the most recently
/// collected set of values, and the current VectorEditorSettings.
/// </summary>
public void ApplySnapping(ICategory category)
{
category.ApplySnapping(EditorSettings.IntervalSnapMethod, EditorSettings.IntervalRoundingDigits, Values);
}
/// <summary>
/// Uses the currently calculated Values in order to calculate a list of breaks
/// that have equal separations.
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
protected List<Break> GetEqualBreaks(int count)
{
List<Break> result = new List<Break>();
double min = Values[0];
double dx = (Values[Values.Count - 1] - min) / count;
for (int i = 0; i < count; i++)
{
Break brk = new Break();
// max
if (i == count - 1)
{
brk.Maximum = null;
}
else
{
brk.Maximum = min + (i + 1) * dx;
}
result.Add(brk);
}
return result;
}
/// <summary>
/// Applies the snapping type to the given breaks
/// </summary>
protected void ApplyBreakSnapping()
{
if (Values == null || Values.Count == 0) return;
switch (EditorSettings.IntervalSnapMethod)
{
case IntervalSnapMethod.None:
break;
case IntervalSnapMethod.SignificantFigures:
foreach (Break item in Breaks)
{
if (item.Maximum == null) continue;
double val = (double)item.Maximum;
item.Maximum = Utils.SigFig(val, EditorSettings.IntervalRoundingDigits);
}
break;
case IntervalSnapMethod.Rounding:
foreach (Break item in Breaks)
{
if (item.Maximum == null) continue;
item.Maximum = Math.Round((double)item.Maximum, EditorSettings.IntervalRoundingDigits);
}
break;
case IntervalSnapMethod.DataValue:
foreach (Break item in Breaks)
{
if (item.Maximum == null) continue;
item.Maximum = Utils.GetNearestValue((double)item.Maximum, Values);
}
break;
}
}
/// <summary>
/// Attempts to create the specified number of breaks with equal numbers of members in each.
/// </summary>
/// <param name="count">The integer count.</param>
/// <returns>A list of breaks.</returns>
protected List<Break> GetQuantileBreaks(int count)
{
List<Break> result = new List<Break>();
int binSize = (int)Math.Ceiling(Values.Count / (double)count);
for (int iBreak = 1; iBreak <= count; iBreak++)
{
if (binSize * iBreak < Values.Count)
{
Break brk = new Break();
brk.Maximum = Values[binSize * iBreak];
result.Add(brk);
}
else
{
// if num breaks is larger than number of members, this can happen
Break brk = new Break();
brk.Maximum = null;
result.Add(brk);
break;
}
}
return result;
}
protected List<Break> GetNaturalBreaks(int count)
{
var breaks = new JenksBreaksCalcuation(Values, count);
breaks.Optimize();
var results = breaks.GetResults();
var output = new List<Break>(count);
output.AddRange(results.Select(result => new Break
{
Maximum = Values[result]
}));
// Set latest Maximum to null
output.Last().Maximum = null;
return output;
}
/// <summary>
/// Sets the names for the break categories
/// </summary>
/// <param name="breaks"></param>
protected static void SetBreakNames(IList<Break> breaks)
{
for (int i = 0; i < breaks.Count; i++)
{
Break brk = breaks[i];
if (breaks.Count == 1)
{
brk.Name = "All Values";
}
else if (i == 0)
{
brk.Name = "<= " + brk.Maximum;
}
else if (i == breaks.Count - 1)
{
brk.Name = "> " + breaks[i - 1].Maximum;
}
else
{
brk.Name = breaks[i - 1].Maximum + " - " + brk.Maximum;
}
}
}
private static List<Color> CreateRampColors(int numColors, float minSat, float minLight, int minHue, float maxSat, float maxLight, int maxHue, int hueShift, int minAlpha, int maxAlpha)
{
List<Color> result = new List<Color>(numColors);
double ds = (maxSat - (double)minSat) / numColors;
double dh = (maxHue - (double)minHue) / numColors;
double dl = (maxLight - (double)minLight) / numColors;
double dA = (maxAlpha - (double)minAlpha) / numColors;
for (int i = 0; i < numColors; i++)
{
double h = (minHue + dh * i) + hueShift % 360;
double s = minSat + ds * i;
double l = minLight + dl * i;
float a = (float)(minAlpha + dA * i) / 255f;
result.Add(SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a));
}
return result;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the editor settings that control how this scheme operates.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public EditorSettings EditorSettings
{
get { return _editorSettings; }
set { _editorSettings = value; }
}
/// <summary>
/// This is cached until a GetValues call is made, at which time the statistics will
/// be re-calculated from the values.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Statistics Statistics
{
get
{
return _statistics;
}
protected set
{
_statistics = value;
}
}
/// <summary>
/// Gets or sets the list of breaks for this scheme
/// </summary>
protected List<Break> Breaks
{
get { return _breaks; }
set { _breaks = value; }
}
/// <summary>
/// Gets the current list of values calculated in the case of numeric breaks.
/// This includes only members that are not excluded by the exclude expression,
/// and have a valid numeric value.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<double> Values
{
get { return _values; }
protected set { _values = value; }
}
#endregion
}
}
| |
//
// PublisherIdentityPermissionTest.cs -
// NUnit Test Cases for PublisherIdentityPermission
//
// 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 NUnit.Framework;
using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Cryptography.X509Certificates;
namespace MonoTests.System.Security.Permissions {
[TestFixture]
public class PublisherIdentityPermissionTest : Assertion {
private static string className = "System.Security.Permissions.PublisherIdentityPermission, ";
private static byte[] cert = { 0x30,0x82,0x05,0x0F,0x30,0x82,0x03,0xF7,0xA0,0x03,0x02,0x01,0x02,0x02,0x0A,0x61,0x07,0x11,0x43,0x00,0x00,0x00,0x00,0x00,0x34,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x81,0xA6,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x08,0x13,0x0A,0x57,0x61,0x73,0x68,0x69,0x6E,0x67,0x74,0x6F,0x6E,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x07,0x13,0x07,0x52,0x65,0x64,0x6D,0x6F,0x6E,0x64,0x31,0x1E,0x30,0x1C,0x06,0x03,
0x55,0x04,0x0A,0x13,0x15,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x69,0x6F,0x6E,0x31,0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x0B,0x13,0x22,0x43,0x6F,0x70,0x79,0x72,0x69,0x67,0x68,0x74,0x20,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x30,0x20,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x2E,0x31,0x23,0x30,0x21,0x06,0x03,0x55,0x04,0x03,0x13,0x1A,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x64,0x65,0x20,0x53,0x69,0x67,
0x6E,0x69,0x6E,0x67,0x20,0x50,0x43,0x41,0x30,0x1E,0x17,0x0D,0x30,0x32,0x30,0x35,0x32,0x35,0x30,0x30,0x35,0x35,0x34,0x38,0x5A,0x17,0x0D,0x30,0x33,0x31,0x31,0x32,0x35,0x30,0x31,0x30,0x35,0x34,0x38,0x5A,0x30,0x81,0xA1,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x08,0x13,0x0A,0x57,0x61,0x73,0x68,0x69,0x6E,0x67,0x74,0x6F,0x6E,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x07,0x13,0x07,0x52,0x65,0x64,0x6D,0x6F,0x6E,0x64,0x31,0x1E,0x30,0x1C,0x06,
0x03,0x55,0x04,0x0A,0x13,0x15,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x69,0x6F,0x6E,0x31,0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x0B,0x13,0x22,0x43,0x6F,0x70,0x79,0x72,0x69,0x67,0x68,0x74,0x20,0x28,0x63,0x29,0x20,0x32,0x30,0x30,0x32,0x20,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x2E,0x31,0x1E,0x30,0x1C,0x06,0x03,0x55,0x04,0x03,0x13,0x15,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x6F,0x72,0x61,
0x74,0x69,0x6F,0x6E,0x30,0x82,0x01,0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xAA,0x99,0xBD,0x39,0xA8,0x18,0x27,0xF4,0x2B,0x3D,0x0B,0x4C,0x3F,0x7C,0x77,0x2E,0xA7,0xCB,0xB5,0xD1,0x8C,0x0D,0xC2,0x3A,0x74,0xD7,0x93,0xB5,0xE0,0xA0,0x4B,0x3F,0x59,0x5E,0xCE,0x45,0x4F,0x9A,0x79,0x29,0xF1,0x49,0xCC,0x1A,0x47,0xEE,0x55,0xC2,0x08,0x3E,0x12,0x20,0xF8,0x55,0xF2,0xEE,0x5F,0xD3,0xE0,0xCA,0x96,0xBC,0x30,
0xDE,0xFE,0x58,0xC8,0x27,0x32,0xD0,0x85,0x54,0xE8,0xF0,0x91,0x10,0xBB,0xF3,0x2B,0xBE,0x19,0xE5,0x03,0x9B,0x0B,0x86,0x1D,0xF3,0xB0,0x39,0x8C,0xB8,0xFD,0x0B,0x1D,0x3C,0x73,0x26,0xAC,0x57,0x2B,0xCA,0x29,0xA2,0x15,0x90,0x82,0x15,0xE2,0x77,0xA3,0x40,0x52,0x03,0x8B,0x9D,0xC2,0x70,0xBA,0x1F,0xE9,0x34,0xF6,0xF3,0x35,0x92,0x4E,0x55,0x83,0xF8,0xDA,0x30,0xB6,0x20,0xDE,0x57,0x06,0xB5,0x5A,0x42,0x06,0xDE,0x59,0xCB,0xF2,0xDF,0xA6,0xBD,0x15,0x47,0x71,0x19,0x25,0x23,0xD2,0xCB,0x6F,0x9B,0x19,0x79,0xDF,0x6A,0x5B,
0xF1,0x76,0x05,0x79,0x29,0xFC,0xC3,0x56,0xCA,0x8F,0x44,0x08,0x85,0x55,0x8A,0xCB,0xC8,0x0F,0x46,0x4B,0x55,0xCB,0x8C,0x96,0x77,0x4A,0x87,0xE8,0xA9,0x41,0x06,0xC7,0xFF,0x0D,0xE9,0x68,0x57,0x63,0x72,0xC3,0x69,0x57,0xB4,0x43,0xCF,0x32,0x3A,0x30,0xDC,0x1B,0xE9,0xD5,0x43,0x26,0x2A,0x79,0xFE,0x95,0xDB,0x22,0x67,0x24,0xC9,0x2F,0xD0,0x34,0xE3,0xE6,0xFB,0x51,0x49,0x86,0xB8,0x3C,0xD0,0x25,0x5F,0xD6,0xEC,0x9E,0x03,0x61,0x87,0xA9,0x68,0x40,0xC7,0xF8,0xE2,0x03,0xE6,0xCF,0x05,0x02,0x03,0x01,0x00,0x01,0xA3,0x82,
0x01,0x40,0x30,0x82,0x01,0x3C,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x06,0xC0,0x30,0x13,0x06,0x03,0x55,0x1D,0x25,0x04,0x0C,0x30,0x0A,0x06,0x08,0x2B,0x06,0x01,0x05,0x05,0x07,0x03,0x03,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04,0x16,0x04,0x14,0x6B,0xC8,0xC6,0x51,0x20,0xF0,0xB4,0x2F,0xD3,0xA0,0xB6,0xAE,0x7F,0x5E,0x26,0xB2,0xB8,0x87,0x52,0x29,0x30,0x81,0xA9,0x06,0x03,0x55,0x1D,0x23,0x04,0x81,0xA1,0x30,0x81,0x9E,0x80,0x14,0x29,0x5C,0xB9,0x1B,0xB6,0xCD,0x33,0xEE,0xBB,0x9E,
0x59,0x7D,0xF7,0xE5,0xCA,0x2E,0xC4,0x0D,0x34,0x28,0xA1,0x74,0xA4,0x72,0x30,0x70,0x31,0x2B,0x30,0x29,0x06,0x03,0x55,0x04,0x0B,0x13,0x22,0x43,0x6F,0x70,0x79,0x72,0x69,0x67,0x68,0x74,0x20,0x28,0x63,0x29,0x20,0x31,0x39,0x39,0x37,0x20,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x2E,0x31,0x1E,0x30,0x1C,0x06,0x03,0x55,0x04,0x0B,0x13,0x15,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x43,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x69,0x6F,0x6E,0x31,0x21,0x30,0x1F,0x06,0x03,0x55,
0x04,0x03,0x13,0x18,0x4D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x20,0x52,0x6F,0x6F,0x74,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x82,0x10,0x6A,0x0B,0x99,0x4F,0xC0,0x00,0xDE,0xAA,0x11,0xD4,0xD8,0x40,0x9A,0xA8,0xBE,0xE6,0x30,0x4A,0x06,0x03,0x55,0x1D,0x1F,0x04,0x43,0x30,0x41,0x30,0x3F,0xA0,0x3D,0xA0,0x3B,0x86,0x39,0x68,0x74,0x74,0x70,0x3A,0x2F,0x2F,0x63,0x72,0x6C,0x2E,0x6D,0x69,0x63,0x72,0x6F,0x73,0x6F,0x66,0x74,0x2E,0x63,0x6F,0x6D,0x2F,0x70,0x6B,0x69,0x2F,0x63,0x72,0x6C,0x2F,0x70,0x72,
0x6F,0x64,0x75,0x63,0x74,0x73,0x2F,0x43,0x6F,0x64,0x65,0x53,0x69,0x67,0x6E,0x50,0x43,0x41,0x2E,0x63,0x72,0x6C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x35,0x23,0xFD,0x13,0x54,0xFC,0xE9,0xDC,0xF0,0xDD,0x0C,0x14,0x7A,0xFA,0xA7,0xB3,0xCE,0xFD,0xA7,0x3A,0xC8,0xBA,0xE5,0xE7,0xF6,0x03,0xFB,0x53,0xDB,0xA7,0x99,0xA9,0xA0,0x9B,0x36,0x9C,0x03,0xEB,0x82,0x47,0x1C,0x21,0xBD,0x14,0xCB,0xE7,0x67,0x40,0x09,0xC7,0x16,0x91,0x02,0x55,0xCE,0x43,0x42,0xB4,
0xCD,0x1B,0x5D,0xB0,0xF3,0x32,0x04,0x3D,0x12,0xE5,0x1D,0xA7,0x07,0xA7,0x8F,0xA3,0x7E,0x45,0x55,0x76,0x1B,0x96,0x95,0x91,0x69,0xF0,0xDD,0x38,0xF3,0x48,0x89,0xEF,0x70,0x40,0xB7,0xDB,0xB5,0x55,0x80,0xC0,0x03,0xC4,0x2E,0xB6,0x28,0xDC,0x0A,0x82,0x0E,0xC7,0x43,0xE3,0x7A,0x48,0x5D,0xB8,0x06,0x89,0x92,0x40,0x6C,0x6E,0xC5,0xDC,0xF8,0x9A,0xEF,0x0B,0xBE,0x21,0x0A,0x8C,0x2F,0x3A,0xB5,0xED,0xA7,0xCE,0x71,0x87,0x68,0x23,0xE1,0xB3,0xE4,0x18,0x7D,0xB8,0x47,0x01,0xA5,0x2B,0xC4,0x58,0xCB,0xB2,0x89,0x6C,0x5F,0xFD,
0xD3,0x2C,0xC4,0x6F,0xB8,0x23,0xB2,0x0D,0xFF,0x3C,0xF2,0x11,0x45,0x74,0xF2,0x09,0x06,0x99,0x18,0xDD,0x6F,0xC0,0x86,0x01,0x18,0x12,0x1D,0x2B,0x16,0xAF,0x56,0xEF,0x65,0x33,0xA1,0xEA,0x67,0x4E,0xF4,0x4B,0x82,0xAB,0xE9,0x0F,0xDC,0x01,0xFA,0xDF,0x60,0x7F,0x66,0x47,0x5D,0xCB,0x2C,0x70,0xCC,0x7B,0x4E,0xD9,0x06,0xB8,0x6E,0x8C,0x0C,0xFE,0x62,0x1E,0x42,0xF9,0x93,0x7C,0xA2,0xAB,0x0A,0x9E,0xD0,0x23,0x10,0xAE,0x4D,0x7B,0x27,0x91,0x6F,0x26,0xBE,0x68,0xFA,0xA6,0x3F,0x9F,0x23,0xEB,0xC8,0x9D,0xBB,0x87 };
private static byte[] cert2 = { 0x30,0x82,0x09,0xB9,0x30,0x82,0x09,0x22,0xA0,0x03,0x02,0x01,0x02,0x02,0x10,0x20,0x0B,0x35,0x5E,0xCE,0xC4,0xB0,0x63,0xB7,0xDE,0xC6,0x34,0xB9,0x70,0x34,0x44,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,0x62,0x31,0x11,0x30,0x0F,0x06,0x03,0x55,0x04,0x07,0x13,0x08,0x49,0x6E,0x74,0x65,0x72,0x6E,0x65,0x74,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x34,0x30,0x32,0x06,0x03,0x55,0x04,0x0B,
0x13,0x2B,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x43,0x41,0x20,0x2D,0x20,0x49,0x6E,0x64,0x69,0x76,0x69,0x64,0x75,0x61,0x6C,0x20,0x53,0x75,0x62,0x73,0x63,0x72,0x69,0x62,0x65,0x72,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x38,0x32,0x31,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x39,0x37,0x30,0x38,0x32,0x30,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x82,0x01,0x0A,0x31,0x11,0x30,0x0F,0x06,0x03,0x55,0x04,0x07,0x13,0x08,0x49,0x6E,0x74,0x65,0x72,0x6E,0x65,0x74,
0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x34,0x30,0x32,0x06,0x03,0x55,0x04,0x0B,0x13,0x2B,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x43,0x41,0x20,0x2D,0x20,0x49,0x6E,0x64,0x69,0x76,0x69,0x64,0x75,0x61,0x6C,0x20,0x53,0x75,0x62,0x73,0x63,0x72,0x69,0x62,0x65,0x72,0x31,0x46,0x30,0x44,0x06,0x03,0x55,0x04,0x0B,0x13,0x3D,0x77,0x77,0x77,0x2E,0x76,0x65,0x72,0x69,0x73,0x69,
0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,0x72,0x65,0x70,0x6F,0x73,0x69,0x74,0x6F,0x72,0x79,0x2F,0x43,0x50,0x53,0x20,0x49,0x6E,0x63,0x6F,0x72,0x70,0x2E,0x20,0x62,0x79,0x20,0x52,0x65,0x66,0x2E,0x2C,0x4C,0x49,0x41,0x42,0x2E,0x4C,0x54,0x44,0x28,0x63,0x29,0x39,0x36,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,0x13,0x1D,0x44,0x69,0x67,0x69,0x74,0x61,0x6C,0x20,0x49,0x44,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x2D,0x20,0x4E,0x65,0x74,0x73,0x63,0x61,0x70,0x65,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x03,
0x13,0x0D,0x44,0x61,0x76,0x69,0x64,0x20,0x54,0x2E,0x20,0x47,0x72,0x61,0x79,0x31,0x1E,0x30,0x1C,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x09,0x01,0x16,0x0F,0x64,0x61,0x76,0x69,0x64,0x40,0x66,0x6F,0x72,0x6D,0x61,0x6C,0x2E,0x69,0x65,0x30,0x5C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x4B,0x00,0x30,0x48,0x02,0x41,0x00,0xC5,0x81,0x07,0xA2,0xEB,0x0F,0xB8,0xFF,0xF8,0xF8,0x1C,0xEE,0x32,0xFF,0xBF,0x12,0x35,0x6A,0xF9,0x6B,0xC8,0xBE,0x2F,0xFB,0x3E,0xAF,0x04,0x51,
0x4A,0xAC,0xDD,0x10,0x29,0xA8,0xCD,0x40,0x5B,0x66,0x1E,0x98,0xEF,0xF2,0x4C,0x77,0xFA,0x8F,0x86,0xD1,0x21,0x67,0x92,0x44,0x4A,0xC4,0x89,0xC9,0x83,0xCF,0x88,0x9F,0x6F,0xE2,0x32,0x35,0x02,0x03,0x01,0x00,0x01,0xA3,0x82,0x07,0x08,0x30,0x82,0x07,0x04,0x30,0x09,0x06,0x03,0x55,0x1D,0x13,0x04,0x02,0x30,0x00,0x30,0x82,0x02,0x1F,0x06,0x03,0x55,0x1D,0x03,0x04,0x82,0x02,0x16,0x30,0x82,0x02,0x12,0x30,0x82,0x02,0x0E,0x30,0x82,0x02,0x0A,0x06,0x0B,0x60,0x86,0x48,0x01,0x86,0xF8,0x45,0x01,0x07,0x01,0x01,0x30,0x82,
0x01,0xF9,0x16,0x82,0x01,0xA7,0x54,0x68,0x69,0x73,0x20,0x63,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x69,0x6E,0x63,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x65,0x73,0x20,0x62,0x79,0x20,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x2C,0x20,0x61,0x6E,0x64,0x20,0x69,0x74,0x73,0x20,0x75,0x73,0x65,0x20,0x69,0x73,0x20,0x73,0x74,0x72,0x69,0x63,0x74,0x6C,0x79,0x20,0x73,0x75,0x62,0x6A,0x65,0x63,0x74,0x20,0x74,0x6F,0x2C,0x20,0x74,0x68,0x65,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x43,
0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x50,0x72,0x61,0x63,0x74,0x69,0x63,0x65,0x20,0x53,0x74,0x61,0x74,0x65,0x6D,0x65,0x6E,0x74,0x20,0x28,0x43,0x50,0x53,0x29,0x2C,0x20,0x61,0x76,0x61,0x69,0x6C,0x61,0x62,0x6C,0x65,0x20,0x61,0x74,0x3A,0x20,0x68,0x74,0x74,0x70,0x73,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,0x43,0x50,0x53,0x3B,0x20,0x62,0x79,0x20,0x45,0x2D,0x6D,0x61,0x69,0x6C,0x20,0x61,0x74,0x20,0x43,0x50,0x53,0x2D,
0x72,0x65,0x71,0x75,0x65,0x73,0x74,0x73,0x40,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x3B,0x20,0x6F,0x72,0x20,0x62,0x79,0x20,0x6D,0x61,0x69,0x6C,0x20,0x61,0x74,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x2C,0x20,0x32,0x35,0x39,0x33,0x20,0x43,0x6F,0x61,0x73,0x74,0x20,0x41,0x76,0x65,0x2E,0x2C,0x20,0x4D,0x6F,0x75,0x6E,0x74,0x61,0x69,0x6E,0x20,0x56,0x69,0x65,0x77,0x2C,0x20,0x43,0x41,0x20,0x39,0x34,0x30,0x34,0x33,0x20,0x55,0x53,0x41,0x20,0x54,0x65,
0x6C,0x2E,0x20,0x2B,0x31,0x20,0x28,0x34,0x31,0x35,0x29,0x20,0x39,0x36,0x31,0x2D,0x38,0x38,0x33,0x30,0x20,0x43,0x6F,0x70,0x79,0x72,0x69,0x67,0x68,0x74,0x20,0x28,0x63,0x29,0x20,0x31,0x39,0x39,0x36,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x20,0x41,0x6C,0x6C,0x20,0x52,0x69,0x67,0x68,0x74,0x73,0x20,0x52,0x65,0x73,0x65,0x72,0x76,0x65,0x64,0x2E,0x20,0x43,0x45,0x52,0x54,0x41,0x49,0x4E,0x20,0x57,0x41,0x52,0x52,0x41,0x4E,0x54,0x49,0x45,0x53,0x20,0x44,0x49,0x53,0x43,
0x4C,0x41,0x49,0x4D,0x45,0x44,0x20,0x61,0x6E,0x64,0x20,0x4C,0x49,0x41,0x42,0x49,0x4C,0x49,0x54,0x59,0x20,0x4C,0x49,0x4D,0x49,0x54,0x45,0x44,0x2E,0xA0,0x0E,0x06,0x0C,0x60,0x86,0x48,0x01,0x86,0xF8,0x45,0x01,0x07,0x01,0x01,0x01,0xA1,0x0E,0x06,0x0C,0x60,0x86,0x48,0x01,0x86,0xF8,0x45,0x01,0x07,0x01,0x01,0x02,0x30,0x2C,0x30,0x2A,0x16,0x28,0x68,0x74,0x74,0x70,0x73,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,0x72,0x65,0x70,0x6F,0x73,0x69,0x74,0x6F,
0x72,0x79,0x2F,0x43,0x50,0x53,0x20,0x30,0x11,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x01,0x01,0x04,0x04,0x03,0x02,0x07,0x80,0x30,0x36,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x01,0x08,0x04,0x29,0x16,0x27,0x68,0x74,0x74,0x70,0x73,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x2F,0x72,0x65,0x70,0x6F,0x73,0x69,0x74,0x6F,0x72,0x79,0x2F,0x43,0x50,0x53,0x30,0x82,0x04,0x87,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x42,0x01,0x0D,0x04,0x82,0x04,
0x78,0x16,0x82,0x04,0x74,0x43,0x41,0x55,0x54,0x49,0x4F,0x4E,0x3A,0x20,0x54,0x68,0x65,0x20,0x43,0x6F,0x6D,0x6D,0x6F,0x6E,0x20,0x4E,0x61,0x6D,0x65,0x20,0x69,0x6E,0x20,0x74,0x68,0x69,0x73,0x20,0x43,0x6C,0x61,0x73,0x73,0x20,0x31,0x20,0x44,0x69,0x67,0x69,0x74,0x61,0x6C,0x20,0x0A,0x49,0x44,0x20,0x69,0x73,0x20,0x6E,0x6F,0x74,0x20,0x61,0x75,0x74,0x68,0x65,0x6E,0x74,0x69,0x63,0x61,0x74,0x65,0x64,0x20,0x62,0x79,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2E,0x20,0x49,0x74,0x20,0x6D,0x61,0x79,0x20,0x62,
0x65,0x20,0x74,0x68,0x65,0x0A,0x68,0x6F,0x6C,0x64,0x65,0x72,0x27,0x73,0x20,0x72,0x65,0x61,0x6C,0x20,0x6E,0x61,0x6D,0x65,0x20,0x6F,0x72,0x20,0x61,0x6E,0x20,0x61,0x6C,0x69,0x61,0x73,0x2E,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x64,0x6F,0x65,0x73,0x20,0x61,0x75,0x74,0x68,0x2D,0x0A,0x65,0x6E,0x74,0x69,0x63,0x61,0x74,0x65,0x20,0x74,0x68,0x65,0x20,0x65,0x2D,0x6D,0x61,0x69,0x6C,0x20,0x61,0x64,0x64,0x72,0x65,0x73,0x73,0x20,0x6F,0x66,0x20,0x74,0x68,0x65,0x20,0x68,0x6F,0x6C,0x64,0x65,0x72,0x2E,
0x0A,0x0A,0x54,0x68,0x69,0x73,0x20,0x63,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x65,0x20,0x69,0x6E,0x63,0x6F,0x72,0x70,0x6F,0x72,0x61,0x74,0x65,0x73,0x20,0x62,0x79,0x20,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x2C,0x20,0x61,0x6E,0x64,0x20,0x0A,0x69,0x74,0x73,0x20,0x75,0x73,0x65,0x20,0x69,0x73,0x20,0x73,0x74,0x72,0x69,0x63,0x74,0x6C,0x79,0x20,0x73,0x75,0x62,0x6A,0x65,0x63,0x74,0x20,0x74,0x6F,0x2C,0x20,0x74,0x68,0x65,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x0A,0x43,0x65,0x72,
0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x50,0x72,0x61,0x63,0x74,0x69,0x63,0x65,0x20,0x53,0x74,0x61,0x74,0x65,0x6D,0x65,0x6E,0x74,0x20,0x28,0x43,0x50,0x53,0x29,0x2C,0x20,0x61,0x76,0x61,0x69,0x6C,0x61,0x62,0x6C,0x65,0x0A,0x69,0x6E,0x20,0x74,0x68,0x65,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x72,0x65,0x70,0x6F,0x73,0x69,0x74,0x6F,0x72,0x79,0x20,0x61,0x74,0x3A,0x20,0x0A,0x68,0x74,0x74,0x70,0x73,0x3A,0x2F,0x2F,0x77,0x77,0x77,0x2E,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,
0x63,0x6F,0x6D,0x3B,0x20,0x62,0x79,0x20,0x45,0x2D,0x6D,0x61,0x69,0x6C,0x20,0x61,0x74,0x0A,0x43,0x50,0x53,0x2D,0x72,0x65,0x71,0x75,0x65,0x73,0x74,0x73,0x40,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,0x6F,0x6D,0x3B,0x20,0x6F,0x72,0x20,0x62,0x79,0x20,0x6D,0x61,0x69,0x6C,0x20,0x61,0x74,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x0A,0x49,0x6E,0x63,0x2E,0x2C,0x20,0x32,0x35,0x39,0x33,0x20,0x43,0x6F,0x61,0x73,0x74,0x20,0x41,0x76,0x65,0x2E,0x2C,0x20,0x4D,0x6F,0x75,0x6E,0x74,0x61,0x69,0x6E,
0x20,0x56,0x69,0x65,0x77,0x2C,0x20,0x43,0x41,0x20,0x39,0x34,0x30,0x34,0x33,0x20,0x55,0x53,0x41,0x0A,0x0A,0x43,0x6F,0x70,0x79,0x72,0x69,0x67,0x68,0x74,0x20,0x28,0x63,0x29,0x31,0x39,0x39,0x36,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x20,0x20,0x41,0x6C,0x6C,0x20,0x52,0x69,0x67,0x68,0x74,0x73,0x20,0x0A,0x52,0x65,0x73,0x65,0x72,0x76,0x65,0x64,0x2E,0x20,0x43,0x45,0x52,0x54,0x41,0x49,0x4E,0x20,0x57,0x41,0x52,0x52,0x41,0x4E,0x54,0x49,0x45,0x53,0x20,0x44,0x49,0x53,0x43,
0x4C,0x41,0x49,0x4D,0x45,0x44,0x20,0x41,0x4E,0x44,0x20,0x0A,0x4C,0x49,0x41,0x42,0x49,0x4C,0x49,0x54,0x59,0x20,0x4C,0x49,0x4D,0x49,0x54,0x45,0x44,0x2E,0x0A,0x0A,0x57,0x41,0x52,0x4E,0x49,0x4E,0x47,0x3A,0x20,0x54,0x48,0x45,0x20,0x55,0x53,0x45,0x20,0x4F,0x46,0x20,0x54,0x48,0x49,0x53,0x20,0x43,0x45,0x52,0x54,0x49,0x46,0x49,0x43,0x41,0x54,0x45,0x20,0x49,0x53,0x20,0x53,0x54,0x52,0x49,0x43,0x54,0x4C,0x59,0x0A,0x53,0x55,0x42,0x4A,0x45,0x43,0x54,0x20,0x54,0x4F,0x20,0x54,0x48,0x45,0x20,0x56,0x45,0x52,0x49,
0x53,0x49,0x47,0x4E,0x20,0x43,0x45,0x52,0x54,0x49,0x46,0x49,0x43,0x41,0x54,0x49,0x4F,0x4E,0x20,0x50,0x52,0x41,0x43,0x54,0x49,0x43,0x45,0x0A,0x53,0x54,0x41,0x54,0x45,0x4D,0x45,0x4E,0x54,0x2E,0x20,0x20,0x54,0x48,0x45,0x20,0x49,0x53,0x53,0x55,0x49,0x4E,0x47,0x20,0x41,0x55,0x54,0x48,0x4F,0x52,0x49,0x54,0x59,0x20,0x44,0x49,0x53,0x43,0x4C,0x41,0x49,0x4D,0x53,0x20,0x43,0x45,0x52,0x54,0x41,0x49,0x4E,0x0A,0x49,0x4D,0x50,0x4C,0x49,0x45,0x44,0x20,0x41,0x4E,0x44,0x20,0x45,0x58,0x50,0x52,0x45,0x53,0x53,0x20,
0x57,0x41,0x52,0x52,0x41,0x4E,0x54,0x49,0x45,0x53,0x2C,0x20,0x49,0x4E,0x43,0x4C,0x55,0x44,0x49,0x4E,0x47,0x20,0x57,0x41,0x52,0x52,0x41,0x4E,0x54,0x49,0x45,0x53,0x0A,0x4F,0x46,0x20,0x4D,0x45,0x52,0x43,0x48,0x41,0x4E,0x54,0x41,0x42,0x49,0x4C,0x49,0x54,0x59,0x20,0x4F,0x52,0x20,0x46,0x49,0x54,0x4E,0x45,0x53,0x53,0x20,0x46,0x4F,0x52,0x20,0x41,0x20,0x50,0x41,0x52,0x54,0x49,0x43,0x55,0x4C,0x41,0x52,0x0A,0x50,0x55,0x52,0x50,0x4F,0x53,0x45,0x2C,0x20,0x41,0x4E,0x44,0x20,0x57,0x49,0x4C,0x4C,0x20,0x4E,0x4F,
0x54,0x20,0x42,0x45,0x20,0x4C,0x49,0x41,0x42,0x4C,0x45,0x20,0x46,0x4F,0x52,0x20,0x43,0x4F,0x4E,0x53,0x45,0x51,0x55,0x45,0x4E,0x54,0x49,0x41,0x4C,0x2C,0x0A,0x50,0x55,0x4E,0x49,0x54,0x49,0x56,0x45,0x2C,0x20,0x41,0x4E,0x44,0x20,0x43,0x45,0x52,0x54,0x41,0x49,0x4E,0x20,0x4F,0x54,0x48,0x45,0x52,0x20,0x44,0x41,0x4D,0x41,0x47,0x45,0x53,0x2E,0x20,0x53,0x45,0x45,0x20,0x54,0x48,0x45,0x20,0x43,0x50,0x53,0x0A,0x46,0x4F,0x52,0x20,0x44,0x45,0x54,0x41,0x49,0x4C,0x53,0x2E,0x0A,0x0A,0x43,0x6F,0x6E,0x74,0x65,0x6E,
0x74,0x73,0x20,0x6F,0x66,0x20,0x74,0x68,0x65,0x20,0x56,0x65,0x72,0x69,0x53,0x69,0x67,0x6E,0x20,0x72,0x65,0x67,0x69,0x73,0x74,0x65,0x72,0x65,0x64,0x0A,0x6E,0x6F,0x6E,0x76,0x65,0x72,0x69,0x66,0x69,0x65,0x64,0x53,0x75,0x62,0x6A,0x65,0x63,0x74,0x41,0x74,0x74,0x72,0x69,0x62,0x75,0x74,0x65,0x73,0x20,0x65,0x78,0x74,0x65,0x6E,0x73,0x69,0x6F,0x6E,0x20,0x76,0x61,0x6C,0x75,0x65,0x20,0x73,0x68,0x61,0x6C,0x6C,0x20,0x0A,0x6E,0x6F,0x74,0x20,0x62,0x65,0x20,0x63,0x6F,0x6E,0x73,0x69,0x64,0x65,0x72,0x65,0x64,0x20,
0x61,0x73,0x20,0x61,0x63,0x63,0x75,0x72,0x61,0x74,0x65,0x20,0x69,0x6E,0x66,0x6F,0x72,0x6D,0x61,0x74,0x69,0x6F,0x6E,0x20,0x76,0x61,0x6C,0x69,0x64,0x61,0x74,0x65,0x64,0x20,0x0A,0x62,0x79,0x20,0x74,0x68,0x65,0x20,0x49,0x41,0x2E,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x2B,0x3D,0x44,0xC7,0x32,0x59,0xAE,0xF1,0x5F,0x8F,0x3F,0x87,0xE3,0x3E,0xEB,0x81,0x30,0xF8,0xA9,0x96,0xDB,0x01,0x42,0x0B,0x04,0xEF,0x37,0x02,0x3F,0xD4,0x20,0x61,0x58,0xC4,0x4A,0x3A,
0x39,0xB3,0xFB,0xD9,0xF8,0xA5,0xC4,0x5E,0x33,0x5A,0x0E,0xFA,0x93,0x56,0x2F,0x6F,0xD6,0x61,0xA2,0xAF,0xA5,0x0C,0x1D,0xE2,0x41,0x65,0xF3,0x40,0x75,0x66,0x83,0xD2,0x5A,0xB4,0xB7,0x56,0x0B,0x8E,0x0D,0xA1,0x33,0x13,0x7D,0x49,0xC3,0xB1,0x00,0x68,0x83,0x7F,0xB5,0x66,0xD4,0x32,0x32,0xFE,0x8B,0x9A,0x5A,0xD6,0x01,0x72,0x31,0x5D,0x85,0x91,0xBC,0x93,0x9B,0x65,0x60,0x25,0xC6,0x1F,0xBC,0xDD,0x69,0x44,0x62,0xC2,0xB2,0x6F,0x46,0xAB,0x2F,0x20,0xA5,0x6F,0xDA,0x48,0x6C,0x9C };
private X509Certificate x509;
[SetUp]
public void SetUp ()
{
x509 = new X509Certificate (cert);
}
[Test]
public void PermissionStateNone ()
{
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.None);
AssertNotNull ("PublisherIdentityPermission(PermissionState.None)", p);
PublisherIdentityPermission copy = (PublisherIdentityPermission) p.Copy ();
SecurityElement se = p.ToXml ();
Assert ("ToXml-class", se.Attribute ("class").StartsWith (className));
AssertEquals ("ToXml-version", "1", se.Attribute("version"));
AssertNull ("ToXml-Unrestricted", se.Attribute("Unrestricted"));
AssertNull ("Certificate==null", p.Certificate);
}
#if NET_2_0
[Test]
[Category ("NotWorking")]
public void PermissionStateUnrestricted ()
{
// In 2.0 Unrestricted are permitted for identity permissions
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.Unrestricted);
AssertNotNull ("PublisherIdentityPermission(PermissionState.None)", p);
PublisherIdentityPermission copy = (PublisherIdentityPermission)p.Copy ();
SecurityElement se = p.ToXml ();
Assert ("ToXml-class", se.Attribute ("class").StartsWith (className));
AssertEquals ("ToXml-version", "1", se.Attribute("version"));
AssertEquals ("ToXml-Unrestricted", "true", se.Attribute("Unrestricted"));
AssertNull ("Certificate==null", p.Certificate);
// and they aren't equals to None
Assert (!p.Equals (new PublisherIdentityPermission (PermissionState.None)));
}
#else
[Test]
[ExpectedException (typeof (ArgumentException))]
public void PermissionStateUnrestricted ()
{
// Unrestricted isn't permitted for identity permissions
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.Unrestricted);
}
#endif
[Test]
public void Certificate ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
PublisherIdentityPermission p2 = new PublisherIdentityPermission (PermissionState.None);
p2.Certificate = x509;
AssertEquals ("Certificate", p1.ToXml ().ToString (), p2.ToXml ().ToString ());
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void ConstructorCertificateNull ()
{
PublisherIdentityPermission p = new PublisherIdentityPermission (null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void PropertyCertificateNull ()
{
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.None);
p.Certificate = null;
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void FromXmlNull ()
{
EnvironmentPermission ep = new EnvironmentPermission (PermissionState.None);
ep.FromXml (null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXmlInvalidPermission ()
{
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.None);
SecurityElement se = p.ToXml ();
// can't modify - so we create our own
SecurityElement se2 = new SecurityElement ("IInvalidPermission", se.Text);
se2.AddAttribute ("class", se.Attribute ("class"));
se2.AddAttribute ("version", se.Attribute ("version"));
p.FromXml (se2);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXmlWrongVersion ()
{
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.None);
SecurityElement se = p.ToXml ();
// can't modify - so we create our own
SecurityElement se2 = new SecurityElement (se.Tag, se.Text);
se2.AddAttribute ("class", se.Attribute ("class"));
se2.AddAttribute ("version", "2");
p.FromXml (se2);
}
[Test]
public void FromXml ()
{
PublisherIdentityPermission p = new PublisherIdentityPermission (PermissionState.None);
SecurityElement se = p.ToXml ();
AssertNotNull ("ToXml()", se);
p.FromXml (se);
se.AddAttribute ("X509v3Certificate", x509.GetRawCertDataString ());
p.FromXml (se);
AssertEquals ("CertificateHash", x509.GetCertHashString (), p.Certificate.GetCertHashString ());
}
[Test]
public void UnionWithNull ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
PublisherIdentityPermission p2 = null;
PublisherIdentityPermission p3 = (PublisherIdentityPermission) p1.Union (p2);
AssertEquals ("P1 U null == P1", p1.ToXml ().ToString (), p3.ToXml ().ToString ());
}
[Test]
public void Union ()
{
// with no certificates
PublisherIdentityPermission p1 = new PublisherIdentityPermission (PermissionState.None);
PublisherIdentityPermission p2 = new PublisherIdentityPermission (PermissionState.None);
PublisherIdentityPermission p3 = (PublisherIdentityPermission) p1.Union (p2);
AssertNull ("None U None == null", p3);
// with 1 certificate
p1 = new PublisherIdentityPermission (x509);
p2 = new PublisherIdentityPermission (PermissionState.None);
p3 = (PublisherIdentityPermission) p1.Union (p2);
AssertEquals ("cert U None == cert", p3.ToXml ().ToString (), p1.ToXml ().ToString ());
X509Certificate x2 = new X509Certificate (cert2);
// 2 certificates (same)
x2 = new X509Certificate (cert);
p2 = new PublisherIdentityPermission (x2);
p3 = (PublisherIdentityPermission) p1.Union (p2);
AssertEquals ("cert1 U cert1 == cert1", p3.ToString (), p1.ToString ());
}
[Test]
#if NET_2_0
[Category ("NotWorking")]
#endif
public void Union_DifferentCertificates ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
X509Certificate x2 = new X509Certificate (cert2);
PublisherIdentityPermission p2 = new PublisherIdentityPermission (x2);
IPermission p = p1.Union (p2);
#if NET_2_0
// new XML format is used to contain more than one X.509 certificate
SecurityElement se = p.ToXml ();
AssertEquals ("Childs", 2, se.Children.Count);
AssertEquals ("Cert#1", (se.Children [0] as SecurityElement).Attribute ("X509v3Certificate"), p1.ToXml ().Attribute ("X509v3Certificate"));
AssertEquals ("Cert#2", (se.Children [1] as SecurityElement).Attribute ("X509v3Certificate"), p2.ToXml ().Attribute ("X509v3Certificate"));
// strangely it is still versioned as 'version="1"'.
AssertEquals ("Version", "1", se.Attribute ("version"));
#else
AssertNull ("cert1 U cert2 == null", p);
#endif
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void UnionWithBadPermission ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (PermissionState.None);
EnvironmentPermission ep2 = new EnvironmentPermission (PermissionState.None);
PublisherIdentityPermission p3 = (PublisherIdentityPermission) p1.Union (ep2);
}
[Test]
public void IntersectWithNull ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
PublisherIdentityPermission p2 = null;
PublisherIdentityPermission p3 = (PublisherIdentityPermission) p1.Intersect (p2);
AssertNull ("P1 N null == null", p3);
}
[Test]
public void Intersect ()
{
// intersect None with None
PublisherIdentityPermission p1 = new PublisherIdentityPermission (PermissionState.None);
PublisherIdentityPermission p2 = new PublisherIdentityPermission (PermissionState.None);
PublisherIdentityPermission p3 = (PublisherIdentityPermission) p1.Intersect (p2);
AssertNull ("None N None == null", p3);
// with 1 certificate
p1 = new PublisherIdentityPermission (x509);
p2 = new PublisherIdentityPermission (PermissionState.None);
p3 = (PublisherIdentityPermission) p1.Intersect (p2);
AssertNull ("cert N None == None", p3);
// 2 different certificates
X509Certificate x2 = new X509Certificate (cert2);
p2 = new PublisherIdentityPermission (x2);
p3 = (PublisherIdentityPermission) p1.Intersect (p2);
AssertNull ("cert1 N cert2 == null", p3);
// 2 certificates (same)
x2 = new X509Certificate (cert);
p2 = new PublisherIdentityPermission (x2);
p3 = (PublisherIdentityPermission) p1.Intersect (p2);
AssertEquals ("cert1 N cert1 == cert1", p3.ToString (), p1.ToString ());
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void IntersectWithBadPermission ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
FileDialogPermission fdp2 = new FileDialogPermission (PermissionState.Unrestricted);
PublisherIdentityPermission p3 = (PublisherIdentityPermission) p1.Intersect (fdp2);
}
[Test]
public void IsSubsetOfNull ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
Assert ("IsSubsetOf(null)", !p1.IsSubsetOf (null));
}
[Test]
public void IsSubsetOf ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (PermissionState.None);
PublisherIdentityPermission p2 = new PublisherIdentityPermission (PermissionState.None);
Assert ("None.IsSubsetOf(None)", p1.IsSubsetOf (p2));
PublisherIdentityPermission p3 = new PublisherIdentityPermission (x509);
Assert ("Cert.IsSubsetOf(None)", !p3.IsSubsetOf (p2));
Assert ("None.IsSubsetOf(Cert)", p2.IsSubsetOf (p3));
PublisherIdentityPermission p4 = new PublisherIdentityPermission (x509);
Assert ("Cert.IsSubsetOf(Cert)", p3.IsSubsetOf (p4));
X509Certificate x2 = new X509Certificate (cert2);
PublisherIdentityPermission p5 = new PublisherIdentityPermission (x2);
Assert ("Cert2.IsSubsetOf(Cert)", !p5.IsSubsetOf (p3));
Assert ("Cert.IsSubsetOf(Cert2)", !p3.IsSubsetOf (p5));
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void IsSubsetOfBadPermission ()
{
PublisherIdentityPermission p1 = new PublisherIdentityPermission (x509);
FileDialogPermission fdp2 = new FileDialogPermission (PermissionState.Unrestricted);
Assert ("IsSubsetOf(PublisherIdentityPermission)", p1.IsSubsetOf (fdp2));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TQData.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultData
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// TQData is used to store information about reading and writing the data files in TQ.
/// </summary>
public static class TQData
{
/// <summary>
/// Name of the vault folder
/// </summary>
private static string vaultFolder;
/// <summary>
/// Path to the Immortal Throne game directory.
/// </summary>
private static string immortalThroneGamePath;
/// <summary>
/// Path to the Titan Quest Game directory.
/// </summary>
private static string titanQuestGamePath;
/// <summary>
/// Gets the Immortal Throne Character save folder
/// </summary>
public static string ImmortalThroneSaveFolder
{
get
{
return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games"), "Titan Quest - Immortal Throne");
}
}
/// <summary>
/// Gets the Titan Quest Character save folder.
/// </summary>
public static string TQSaveFolder
{
get
{
return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "My Games"), "Titan Quest");
}
}
/// <summary>
/// Gets the name of the game settings file.
/// </summary>
public static string TQSettingsFile
{
get
{
return Path.Combine(Path.Combine(TQSaveFolder, "Settings"), "options.txt");
}
}
/// <summary>
/// Gets or sets the Titan Quest game path.
/// </summary>
public static string TQPath
{
get
{
// We are either autodetecting or the path has not been set
//
// Detection logic for a GOG install of the anniversary edition ~Malgardian
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string[] path = { "SOFTWARE", "GOG.com", "Games", "1196955511", "PATH" };
titanQuestGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
}
// Detection logic for a Steam install of the anniversary edition ~Malgardian
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string steamTQPath = "\\SteamApps\\common\\Titan Quest Anniversary Edition";
string[] registryPath = { "Software", "Valve", "Steam", "SteamPath" };
string steamPath = ReadRegistryKey(Microsoft.Win32.Registry.CurrentUser, registryPath).Replace("/", "\\");
if (Directory.Exists(steamPath + steamTQPath))
{
titanQuestGamePath = steamPath + steamTQPath;
}
else
{
//further looking for Steam library
//read libraryfolders.vdf
Regex vdfPathRegex = new Regex("\"\\d+\"\t+\"([^\"]+)\""); // "2" "D:\\games\\Steam"
string[] libFile = File.ReadAllLines(steamPath + "\\SteamApps\\libraryfolders.vdf");
foreach (var line in libFile)
{
Match match = vdfPathRegex.Match(line.Trim());
if (match.Success && Directory.Exists(match.Groups[1] + steamTQPath))
{
titanQuestGamePath = match.Groups[1] + steamTQPath;
break;
}
}
}
}
//Disc version detection logic -old
if (string.IsNullOrEmpty(titanQuestGamePath))
{
string[] path = { "SOFTWARE", "Iron Lore", "Titan Quest", "Install Location" };
titanQuestGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
}
if (string.IsNullOrEmpty(titanQuestGamePath) && !string.IsNullOrEmpty(IniProperties.GamePath))
{
titanQuestGamePath = IniProperties.GamePath;
}
if (string.IsNullOrEmpty(titanQuestGamePath))
{
throw new InvalidOperationException("Unable to locate Titan Quest installation directory. Please edit TQVaultAE.ini to contain a valid path in the option 'ForceGamePath'.");
}
return titanQuestGamePath;
}
set
{
titanQuestGamePath = value;
}
}
/// <summary>
/// Gets a value indicating whether Immortal Throne has been installed.
/// </summary>
public static bool IsITInstalled { get; private set; }
/// <summary>
/// Gets a value indicating whether Ragnarok DLC has been installed.
/// </summary>
public static bool IsRagnarokInstalled {
get {
return Directory.Exists(ImmortalThronePath + "\\Resources\\XPack2");
}
}
/// <summary>
/// Gets or sets the Immortal Throne game path.
/// </summary>
public static string ImmortalThronePath
{
get
{
// We are either autodetecting or the path has not been set in configuration UI
// so we attempt to read the value from the registry
//detection logic for a GOG install of the anniversary edition ~Malgardian
if (string.IsNullOrEmpty(immortalThroneGamePath))
{
string[] path = new string[5];
path[0] = "SOFTWARE";
path[1] = "GOG.com";
path[2] = "Games";
path[3] = "1196955511";
path[4] = "PATH";
immortalThroneGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
//System.Windows.Forms.MessageBox.Show(immortalThroneGamePath);
}
// Detection logic for a Steam install of the anniversary edition ~Malgardian
if (string.IsNullOrEmpty(immortalThroneGamePath))
{
string steamTQPath = "\\SteamApps\\common\\Titan Quest Anniversary Edition";
string[] registryPath = new string[] { "Software", "Valve", "Steam", "SteamPath" };
string steamPath = ReadRegistryKey(Microsoft.Win32.Registry.CurrentUser, registryPath).Replace("/", "\\");
if (Directory.Exists(steamPath + steamTQPath))
{
immortalThroneGamePath = steamPath + steamTQPath;
}
else
{
//further looking for Steam library
//read libraryfolders.vdf
Regex vdfPathRegex = new Regex("\"\\d+\"\t+\"([^\"]+)\""); // "2" "D:\\games\\Steam"
string[] libFile = File.ReadAllLines(steamPath + "\\SteamApps\\libraryfolders.vdf");
foreach (var line in libFile)
{
Match match = vdfPathRegex.Match(line.Trim());
if (match.Success && Directory.Exists(match.Groups[1] + steamTQPath))
{
immortalThroneGamePath = match.Groups[1] + steamTQPath;
break;
}
}
}
}
//Disc version detection logic -old
if (string.IsNullOrEmpty(immortalThroneGamePath))
{
string[] path = new string[4];
path[0] = "SOFTWARE";
path[1] = "Iron Lore";
path[2] = "Titan Quest Immortal Throne";
path[3] = "Install Location";
immortalThroneGamePath = ReadRegistryKey(Microsoft.Win32.Registry.LocalMachine, path);
}
if (string.IsNullOrEmpty(immortalThroneGamePath) && !string.IsNullOrEmpty(IniProperties.GamePath))
{
immortalThroneGamePath = IniProperties.GamePath;
}
if (string.IsNullOrEmpty(immortalThroneGamePath))
{
throw new InvalidOperationException("Unable to locate Titan Quest installation directory. Please edit TQVaultAE.ini to contain a valid path in the option 'ForceGamePath'.");
}
// ImmortalThrone is always installed in AE
IsITInstalled = true;
return immortalThroneGamePath;
}
set
{
immortalThroneGamePath = value;
}
}
/// <summary>
/// Gets or sets the name of the custom map.
/// Added to support custom quest characters
/// </summary>
public static string MapName { get; set; }
/// <summary>
/// Gets a value indicating whether a custom map has been specified.
/// </summary>
public static bool IsCustom
{
get
{
return !string.IsNullOrEmpty(MapName) && (MapName.Trim().ToUpperInvariant() != "MAIN");
}
}
/// <summary>
/// Gets a value indicating whether the vault save folder has been changed.
/// Usually done via settings and triggers a reload of the vaults.
/// </summary>
public static bool VaultFolderChanged { get; private set; }
/// <summary>
/// Gets or sets the vault save folder path.
/// </summary>
public static string TQVaultSaveFolder
{
get
{
if (string.IsNullOrEmpty(vaultFolder))
{
string folderPath = Path.Combine(TQSaveFolder, "TQVaultData");
// Lets see if our path exists and create it if it does not
if (!Directory.Exists(folderPath))
{
try
{
Directory.CreateDirectory(folderPath);
}
catch (Exception e)
{
throw new InvalidOperationException(string.Concat("Error creating directory: ", folderPath), e);
}
}
vaultFolder = folderPath;
VaultFolderChanged = true;
}
return vaultFolder;
}
// Added by VillageIdiot
// Used to set vault path by configuration UI.
set
{
if (Directory.Exists(value))
{
vaultFolder = value;
}
}
}
/// <summary>
/// Gets the vault backup folder path.
/// </summary>
public static string TQVaultBackupFolder
{
get
{
string baseFolder = TQVaultSaveFolder;
string folderPath = Path.Combine(baseFolder, "Backups");
// Create the path if it does not yet exist
if (!Directory.Exists(folderPath))
{
try
{
Directory.CreateDirectory(folderPath);
}
catch (Exception e)
{
throw new InvalidOperationException(string.Concat("Error creating directory: ", folderPath), e);
}
}
return folderPath;
}
}
/// <summary>
/// Gets the filename for the character's transfer stash.
/// Stash files for Mods all have their own subdirectory which is the same as the mod's custom map folder
/// </summary>
public static string TransferStashFile
{
get
{
if (IsCustom)
{
return Path.Combine(Path.Combine(Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), "Sys"), MapName), "winsys.dxb");
}
return Path.Combine(Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), "Sys"), "winsys.dxb");
}
}
/// <summary>
/// Validates that the next string is a certain value and throws an exception if it is not.
/// </summary>
/// <param name="value">value to be validated</param>
/// <param name="reader">BinaryReader instance</param>
public static void ValidateNextString(string value, BinaryReader reader)
{
string label = ReadCString(reader);
if (!label.ToUpperInvariant().Equals(value.ToUpperInvariant()))
{
// Turn on debugging so we can log the exception.
if (!TQDebug.DebugEnabled)
{
TQDebug.DebugEnabled = true;
}
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
"Error reading file at position {2}. Expecting '{0}'. Got '{1}'",
value,
label,
reader.BaseStream.Position - label.Length - 4));
throw new ArgumentException(string.Format(
CultureInfo.InvariantCulture,
"Error reading file at position {2}. Expecting '{0}'. Got '{1}'",
value,
label,
reader.BaseStream.Position - label.Length - 4));
}
}
/// <summary>
/// Writes a string along with its length to the file.
/// </summary>
/// <param name="writer">BinaryWriter instance</param>
/// <param name="value">string value to be written.</param>
public static void WriteCString(BinaryWriter writer, string value)
{
// Convert the string to ascii
// Vorbis' fix for extended characters in the database.
Encoding ascii = Encoding.GetEncoding(1252);
byte[] rawstring = ascii.GetBytes(value);
// Write the 4-byte length of the string
writer.Write(rawstring.Length);
// now write the string
writer.Write(rawstring);
}
/// <summary>
/// Normalizes the record path to Upper Case Invariant Culture and replace backslashes with slashes.
/// </summary>
/// <param name="recordId">record path to be normalized</param>
/// <returns>normalized record path</returns>
public static string NormalizeRecordPath(string recordId)
{
// uppercase it
string normalizedRecordId = recordId.ToUpperInvariant();
// replace any '/' with '\\'
normalizedRecordId = normalizedRecordId.Replace('/', '\\');
return normalizedRecordId;
}
/// <summary>
/// Reads a string from the binary stream.
/// Expects an integer length value followed by the actual string of the stated length.
/// </summary>
/// <param name="reader">BinaryReader instance</param>
/// <returns>string of data that was read</returns>
public static string ReadCString(BinaryReader reader)
{
// first 4 bytes is the string length, followed by the string.
int len = reader.ReadInt32();
// Convert the next len bytes into a string
// Vorbis' fix for extended characters in the database.
Encoding ascii = Encoding.GetEncoding(1252);
byte[] rawData = reader.ReadBytes(len);
char[] chars = new char[ascii.GetCharCount(rawData, 0, len)];
ascii.GetChars(rawData, 0, len, chars, 0);
string ans = new string(chars);
return ans;
}
/// <summary>
/// Reads a value from the registry
/// </summary>
/// <param name="key">registry hive to be read</param>
/// <param name="path">path of the value to be read</param>
/// <returns>string value of the key and value that was read or empty string if there was a problem.</returns>
public static string ReadRegistryKey(Microsoft.Win32.RegistryKey key, string[] path)
{
// The last item in the path array is the actual value name.
int valueKey = path.Length - 1;
// All other values in the path are keys which will need to be navigated.
int lastSubKey = path.Length - 2;
for (int i = 0; i <= lastSubKey; ++i)
{
key = key.OpenSubKey(path[i]);
if (key == null)
{
return string.Empty;
}
}
return (string)key.GetValue(path[valueKey]);
}
/// <summary>
/// TQ has an annoying habit of throwing away your char in preference
/// for the Backup folder if it exists if it thinks your char is not valid.
/// We need to move that folder away so TQ won't find it.
/// </summary>
/// <param name="playerFile">Name of the player file to backup</param>
public static void BackupStupidPlayerBackupFolder(string playerFile)
{
string playerFolder = Path.GetDirectoryName(playerFile);
string backupFolder = Path.Combine(playerFolder, "Backup");
if (Directory.Exists(backupFolder))
{
// we need to move it.
string newFolder = Path.Combine(playerFolder, "Backup-moved by TQVault");
if (Directory.Exists(newFolder))
{
try {
// It already exists--we need to remove it
Directory.Delete(newFolder, true);
} catch (Exception e)
{
int fn = 1;
while(Directory.Exists(String.Format("{0}({1})",newFolder,fn)))
{
fn++;
}
newFolder = String.Format("{0}({1})", newFolder, fn);
}
}
Directory.Move(backupFolder, newFolder);
}
}
/// <summary>
/// Gets the base character save folder.
/// Changed to support custom quest characters
/// </summary>
/// <param name="isImmortalThrone">Indicates whether the character is from Immortal Throne.</param>
/// <returns>path of the save folder</returns>
public static string GetBaseCharacterFolder(bool isImmortalThrone)
{
string mapSaveFolder = "Main";
if (IsCustom)
{
mapSaveFolder = "User";
}
if (isImmortalThrone)
{
return Path.Combine(Path.Combine(ImmortalThroneSaveFolder, "SaveData"), mapSaveFolder);
}
return Path.Combine(Path.Combine(TQSaveFolder, "SaveData"), mapSaveFolder);
}
/// <summary>
/// Gets the full path to the player character file.
/// </summary>
/// <param name="characterName">name of the character</param>
/// <param name="isImmortalThrone">Indicates whether the character is from Immortal Throne.</param>
/// <returns>full path to the character file.</returns>
public static string GetPlayerFile(string characterName, bool isImmortalThrone)
{
return Path.Combine(Path.Combine(GetBaseCharacterFolder(isImmortalThrone), string.Concat("_", characterName)), "Player.chr");
}
/// <summary>
/// Gets the full path to the player's stash file.
/// </summary>
/// <param name="characterName">name of the character</param>
/// <param name="isImmortalThrone">Indicates whether the character is from Immortal Throne.</param>
/// <returns>full path to the player stash file</returns>
public static string GetPlayerStashFile(string characterName, bool isImmortalThrone)
{
return Path.Combine(Path.Combine(GetBaseCharacterFolder(isImmortalThrone), string.Concat("_", characterName)), "winsys.dxb");
}
/// <summary>
/// Gets a list of all of the character files in the save folder.
/// Added support for loading custom quest characters
/// </summary>
/// <param name="isImmortalThrone">Indicates whether or not Immortal Throne is installed.</param>
/// <returns>List of character files in a string array</returns>
public static string[] GetCharacterList(bool isImmortalThrone)
{
try
{
// Get all folders that start with a '_'.
string[] folders = Directory.GetDirectories(GetBaseCharacterFolder(isImmortalThrone), "_*");
if (folders == null || folders.Length < 1)
{
return null;
}
List<string> characterList = new List<string>(folders.Length);
// Copy the names over without the '_' and strip out the path information.
foreach (string folder in folders)
{
characterList.Add(Path.GetFileName(folder).Substring(1));
}
// sort alphabetically
characterList.Sort();
return characterList.ToArray();
}
catch (DirectoryNotFoundException)
{
return null;
}
}
/// <summary>
/// Gets a list of all of the custom maps.
/// </summary>
/// <param name="isImmortalThrone">Indicates whether or not Immortal Throne is installed.</param>
/// <returns>List of custom maps in a string array</returns>
public static string[] GetCustomMapList(bool isImmortalThrone)
{
try
{
// Get all folders in the CustomMaps directory.
string saveFolder;
if (isImmortalThrone)
{
saveFolder = ImmortalThroneSaveFolder;
}
else
{
saveFolder = TQSaveFolder;
}
string[] mapFolders = Directory.GetDirectories(Path.Combine(saveFolder, "CustomMaps"), "*");
if (mapFolders == null || mapFolders.Length < 1)
{
return null;
}
List<string> customMapList = new List<string>(mapFolders.Length);
// Strip out the path information
foreach (string mapFolder in mapFolders)
{
customMapList.Add(Path.GetFileName(mapFolder));
}
// sort alphabetically
customMapList.Sort();
return customMapList.ToArray();
}
catch (DirectoryNotFoundException)
{
return null;
}
}
/// <summary>
/// Gets the file name and path for a vault.
/// </summary>
/// <param name="vaultName">The name of the vault file.</param>
/// <returns>The full path along with extension of the vault file.</returns>
public static string GetVaultFile(string vaultName)
{
return string.Concat(Path.Combine(TQVaultSaveFolder, vaultName), ".vault");
}
/// <summary>
/// Gets a list of all of the vault files.
/// </summary>
/// <returns>The list of all of the vault files in the save folder.</returns>
public static string[] GetVaultList()
{
try
{
// Get all files that have a .vault extension.
string[] files = Directory.GetFiles(TQVaultSaveFolder, "*.vault");
if (files == null || files.Length < 1)
{
return null;
}
List<string> vaultList = new List<string>(files.Length);
// Strip out the path information and extension.
foreach (string file in files)
{
vaultList.Add(Path.GetFileNameWithoutExtension(file));
}
// sort alphabetically
vaultList.Sort();
return vaultList.ToArray();
}
catch (DirectoryNotFoundException)
{
return null;
}
}
/// <summary>
/// Converts a file path to a backup file. Adding the current date and time to the name.
/// </summary>
/// <param name="prefix">prefix of the backup file.</param>
/// <param name="filePath">Full path of the file to backup.</param>
/// <returns>Returns the name of the backup file to use for this file. The backup file will have the given prefix.</returns>
public static string ConvertFilePathToBackupPath(string prefix, string filePath)
{
// Get the actual filename without any path information
string filename = Path.GetFileName(filePath);
// Strip the extension off of it.
string extension = Path.GetExtension(filename);
if (!string.IsNullOrEmpty(extension))
{
filename = Path.GetFileNameWithoutExtension(filename);
}
// Now come up with a timestamp string
string timestamp = DateTime.Now.ToString("-yyyyMMdd-HHmmss-fffffff-", CultureInfo.InvariantCulture);
string pathHead = Path.Combine(TQVaultBackupFolder, prefix);
pathHead = string.Concat(pathHead, "-", filename, timestamp);
int uniqueID = 0;
// Now loop and construct the filename and check to see if the name
// is already in use. If it is, increment uniqueID and try again.
while (true)
{
string fullFilePath = string.Concat(pathHead, uniqueID.ToString("000", CultureInfo.InvariantCulture), extension);
if (!File.Exists(fullFilePath))
{
return fullFilePath;
}
// try again
++uniqueID;
}
}
/// <summary>
/// Backs up the file to the backup folder.
/// </summary>
/// <param name="prefix">prefix of the backup file</param>
/// <param name="file">file name to backup</param>
/// <returns>Returns the name of the backup file, or NULL if file does not exist</returns>
public static string BackupFile(string prefix, string file)
{
if (File.Exists(file))
{
// only backup if it exists!
string backupFile = ConvertFilePathToBackupPath(prefix, file);
File.Copy(file, backupFile);
// Added by VillageIdiot
// Backup the file pairs for the player stash files.
if (Path.GetFileName(file).ToUpperInvariant() == "WINSYS.DXB")
{
string dxgfile = Path.ChangeExtension(file, ".dxg");
if (File.Exists(dxgfile))
{
// only backup if it exists!
backupFile = ConvertFilePathToBackupPath(prefix, dxgfile);
File.Copy(dxgfile, backupFile);
}
}
return backupFile;
}
else
{
return 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CeilingDouble()
{
var test = new SimpleUnaryOpTest__CeilingDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__CeilingDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static SimpleUnaryOpTest__CeilingDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__CeilingDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.Ceiling(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.Ceiling(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.Ceiling(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Ceiling), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Ceiling), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.Ceiling), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.Ceiling(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Sse41.Ceiling(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse41.Ceiling(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse41.Ceiling(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__CeilingDouble();
var result = Sse41.Ceiling(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.Ceiling(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Ceiling(firstOp[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(Math.Ceiling(firstOp[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Ceiling)}<Double>(Vector128<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;
using Internal.StackGenerator.Dia;
namespace Internal.StackTraceGenerator
{
public static class StackTraceGenerator
{
//
// Makes reasonable effort to construct one useful line of a stack trace. Returns null if it can't.
//
public static String CreateStackTraceString(IntPtr ip, bool includeFileInfo)
{
try
{
int hr;
int rva;
IDiaSession session = GetDiaSession(ip, out rva);
if (session == null)
return null;
StringBuilder sb = new StringBuilder();
IDiaSymbol symbol;
hr = session.FindSymbolByRVA(rva, SymTagEnum.SymTagFunction, out symbol);
if (hr != S_OK)
return null;
String functionName;
hr = symbol.GetName(out functionName);
if (hr == S_OK)
sb.Append(functionName.Demanglify());
else
sb.Append("<Function Name Not Available>");
sb.Append(CreateParameterListString(session, symbol));
if (includeFileInfo)
{
sb.Append(CreateSourceInfoString(session, rva));
}
return sb.ToString();
}
catch
{
return null;
}
}
//
// Makes reasonable effort to get source info. Returns null sourceFile and 0 lineNumber/columnNumber if it can't.
//
public static void TryGetSourceLineInfo(IntPtr ip, out string fileName, out int lineNumber, out int columnNumber)
{
fileName = null;
lineNumber = 0;
columnNumber = 0;
int rva;
IDiaSession session = GetDiaSession(ip, out rva);
if (session == null)
return;
TryGetSourceLineInfo(session, rva, out fileName, out lineNumber, out columnNumber);
}
//
// Get a IDiaDataSource object
//
private static IDiaDataSource GetDiaDataSource()
{
Guid iid = Guids.IID_IDiaDataSource;
int hr;
foreach (Guid clsId in Guids.DiaSource_CLSIDs)
{
unsafe
{
byte[] _clsid = clsId.ToByteArray();
byte[] _iid = iid.ToByteArray();
fixed (byte* pclsid = _clsid)
{
fixed (byte* piid = _iid)
{
IntPtr _dataSource;
hr = CoCreateInstance(pclsid, (IntPtr)0, CLSCTX_INPROC, piid, out _dataSource);
if (hr == S_OK)
return new IDiaDataSource(_dataSource);
}
}
}
}
return null;
}
//
// Create the method parameter list.
//
private static String CreateParameterListString(IDiaSession session, IDiaSymbol symbol)
{
StringBuilder sb = new StringBuilder("(");
// find the parameters
IDiaEnumSymbols dataSymbols;
int hr = session.FindChildren(symbol, SymTagEnum.SymTagData, null, NameSearchOptions.nsNone, out dataSymbols);
if (hr == S_OK)
{
int count;
hr = dataSymbols.Count(out count);
if (hr == S_OK)
{
for (int i = 0, iParam = 0; i < count; i++)
{
IDiaSymbol dataSym;
hr = dataSymbols.Item(i, out dataSym);
if (hr != S_OK)
continue;
DataKind dataKind;
hr = dataSym.GetDataKind(out dataKind);
if (hr != S_OK || dataKind != DataKind.DataIsParam)
continue;
string paramName;
hr = dataSym.GetName(out paramName);
if (hr != S_OK)
{
continue;
}
//this approximates the way C# displays methods by not including these hidden arguments
if (paramName == "InstParam" || paramName == "this")
{
continue;
}
IDiaSymbol parameterType;
hr = dataSym.GetType(out parameterType);
if (hr != S_OK)
{
continue;
}
if (iParam++ != 0)
sb.Append(", ");
sb.Append(parameterType.ToTypeString(session));
sb.Append(' ');
sb.Append(paramName);
}
}
}
sb.Append(')');
return sb.ToString();
}
//
// Retrieve the source fileName, line number, and column
//
private static void TryGetSourceLineInfo(IDiaSession session, int rva, out string fileName, out int lineNumber, out int columnNumber)
{
fileName = null;
lineNumber = 0;
columnNumber = 0;
IDiaEnumLineNumbers lineNumbers;
int hr = session.FindLinesByRVA(rva, 1, out lineNumbers);
if (hr == S_OK)
{
int numLineNumbers;
hr = lineNumbers.Count(out numLineNumbers);
if (hr == S_OK && numLineNumbers > 0)
{
IDiaLineNumber ln;
hr = lineNumbers.Item(0, out ln);
if (hr == S_OK)
{
IDiaSourceFile sourceFile;
hr = ln.SourceFile(out sourceFile);
if (hr == S_OK)
{
hr = sourceFile.FileName(out fileName);
if (hr == S_OK)
{
hr = ln.LineNumber(out lineNumber);
if (hr == S_OK)
{
hr = ln.ColumnNumber(out columnNumber);
}
}
}
}
}
}
}
//
// Generate the " in <filename>:line <line#>" section.
//
private static String CreateSourceInfoString(IDiaSession session, int rva)
{
StringBuilder sb = new StringBuilder();
string fileName;
int lineNumber, columnNumber;
TryGetSourceLineInfo(session, rva, out fileName, out lineNumber, out columnNumber);
if(!string.IsNullOrEmpty(fileName))
{
sb.Append(" in ").Append(fileName);
if(lineNumber >= 0)
{
sb.Append(":line ").Append(lineNumber);
}
}
return sb.ToString();
}
//
// Clean up all the "$2_" sweetness that ILMerge contributes and
// replace type-name separator "::" by "."
//
private static String Demanglify(this String s)
{
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.Length)
{
sb.Append(s[i++]);
if (i == s.Length)
continue;
if (s[i - 1] == '$' && Char.IsNumber(s[i]))
{
if (i != 1 && (s[i - 2] != ' ' && s[i - 2] != '<'))
continue;
int lookAhead = i + 1;
while (lookAhead < s.Length && Char.IsNumber(s[lookAhead]))
lookAhead++;
if (lookAhead == s.Length || s[lookAhead] != '_')
continue;
sb = sb.Remove(sb.Length - 1, 1);
i = lookAhead + 1;
}
else if (s[i - 1] == ':' && s[i] == ':')
{
sb.Remove(sb.Length - 1, 1);
sb.Append('.');
i++;
}
}
return sb.ToString();
}
private static String ToTypeString(this IDiaSymbol parameterType, IDiaSession session)
{
bool ignore;
return parameterType.ToTypeStringWorker(session, 0, out ignore);
}
private static String ToTypeStringWorker(this IDiaSymbol parameterType, IDiaSession session, int recursionLevel, out bool isValueTypeOrByRef)
{
int hr;
isValueTypeOrByRef = false;
// Block runaway recursions.
if (recursionLevel++ > 10)
return "?";
SymTagEnum symTag;
hr = parameterType.GetSymTag(out symTag);
if (hr != S_OK)
return "?";
if (symTag == SymTagEnum.SymTagPointerType)
{
bool isReference;
hr = parameterType.GetReference(out isReference);
if (hr != S_OK)
return "?";
if (isReference)
{
// An isReference pointer can mean one of two things:
// 1. ELEMENT_TYPE_BYREF
// 2. An indication that the UDT that follows is actually a class, not a struct.
//
isValueTypeOrByRef = true;
IDiaSymbol targetType;
hr = parameterType.GetType(out targetType);
if (hr != S_OK)
return "?";
bool targetIsValueTypeOrByRef;
String targetTypeString = targetType.ToTypeStringWorker(session, recursionLevel, out targetIsValueTypeOrByRef);
if (targetIsValueTypeOrByRef)
return targetTypeString + "&";
else
return targetTypeString;
}
else
{
// A non-isReference pointer means an ELEMENT_TYPE_PTR
IDiaSymbol targetType;
hr = parameterType.GetType(out targetType);
if (hr != S_OK)
return "?";
bool ignore;
return targetType.ToTypeStringWorker(session, recursionLevel, out ignore) + "*";
}
}
else if (symTag == SymTagEnum.SymTagArrayType)
{
// Note: We don't actually hit this case in NUTC-generated PDB's as NUTC emits arrays as if they were UDT's with square brackets in the name.
// But just in case NUTC ever changes its PDB emission, we'll print out the most obvious interpretation and hope we're right.
IDiaSymbol elementType;
hr = parameterType.GetType(out elementType);
if (hr != S_OK)
return "?";
bool ignore;
return elementType.ToTypeStringWorker(session, recursionLevel, out ignore) + "[]";
}
else if (symTag == SymTagEnum.SymTagUDT || symTag == SymTagEnum.SymTagEnum)
{
// Need to figure out whether this is a value type as our recursive caller needs to know whether the "byref pointer" that wrapped this
// is a true managed byref or just the "byref pointer" that wraps all non-valuetypes.
if (symTag == SymTagEnum.SymTagEnum)
{
isValueTypeOrByRef = true;
}
else
{
IDiaEnumSymbols baseClasses;
hr = session.FindChildren(parameterType, SymTagEnum.SymTagBaseClass, null, 0, out baseClasses);
if (hr != S_OK)
return "?";
int count;
hr = baseClasses.Count(out count);
if (hr != S_OK)
return "?";
for (int i = 0; i < count; i++)
{
IDiaSymbol baseClass;
if (S_OK == baseClasses.Item(i, out baseClass))
{
String baseClassName;
if (S_OK == baseClass.GetName(out baseClassName))
{
if (baseClassName == "System::ValueType")
isValueTypeOrByRef = true;
}
}
}
}
String name;
hr = parameterType.GetName(out name);
if (hr != S_OK)
return "?";
return name.RemoveNamespaces().Demanglify();
}
else if (symTag == SymTagEnum.SymTagBaseType)
{
// Certain "primitive" types are encoded specially.
BasicType basicType;
hr = parameterType.GetBaseType(out basicType);
if (hr != S_OK)
return "?";
long length;
hr = parameterType.GetLength(out length);
if (hr != S_OK)
return "?";
return ConvertBasicTypeToTypeString(basicType, length, out isValueTypeOrByRef);
}
else
{
return "?";
}
}
private static String ConvertBasicTypeToTypeString(BasicType basicType, long length, out bool isValueTypeOrByRef)
{
isValueTypeOrByRef = true;
switch (basicType)
{
case BasicType.btNoType:
return "Unknown";
case BasicType.btVoid:
return "Void";
case BasicType.btChar:
return "Byte";
case BasicType.btWChar:
return "Char";
case BasicType.btInt:
if (length != 1L)
{
if (length == 2L)
{
return "Int16";
}
if ((length != 4L) && (length == 8L))
{
return "Int64";
}
return "Int32";
}
return "SByte";
case BasicType.btUInt:
if (length != 1L)
{
if (length == 2L)
{
return "UInt16";
}
if ((length != 4L) && (length == 8L))
{
return "UInt64";
}
return "UInt32";
}
return "Byte";
case BasicType.btFloat:
if (length != 8L)
{
return "Single";
}
return "Double";
case BasicType.btBCD:
return "BCD";
case BasicType.btBool:
return "Boolean";
case BasicType.btLong:
return "Int64";
case BasicType.btULong:
return "UInt64";
case BasicType.btCurrency:
return "Currency";
case BasicType.btDate:
return "Date";
case BasicType.btVariant:
return "Variant";
case BasicType.btComplex:
return "Complex";
case BasicType.btBit:
return "Bit";
case BasicType.btBSTR:
return "BSTR";
case BasicType.btHresult:
return "Hresult";
default:
return "?";
}
}
//
// Attempt to remove namespaces from types. Unfortunately, this isn't straightforward as PDB's present generic instances as "regular types with angle brackets"
// so "s" could be something like "System::Collections::Generics::List$1<System::String>". Worse, the PDB also uses "::" to separate nested types from
// their outer types so these represent collateral damage. And we assume that namespaces (unlike types) have reasonable names (i.e. no names with wierd characters.)
//
// Fortunately, this is just for diagnostic information so we don't need to let perfect be the enemy of good.
//
private static String RemoveNamespaces(this String s)
{
int firstIndexOfColonColon = s.IndexOf("::");
if (firstIndexOfColonColon == -1)
return s;
int lookBack = firstIndexOfColonColon - 1;
for (; ;)
{
if (lookBack < 0)
break;
if (!(Char.IsLetterOrDigit(s[lookBack]) || s[lookBack] == '_'))
break;
lookBack--;
}
s = s.Remove(lookBack + 1, firstIndexOfColonColon - lookBack + 1);
return s.RemoveNamespaces();
}
/// <summary>
/// Locate and lazily load debug info for the native app module overlapping given
/// virtual address.
/// </summary>
/// <param name="ip">Instruction pointer address (code address for the lookup)</param>
/// <param name="rva">Output VA relative to module base</param>
private static IDiaSession GetDiaSession(IntPtr ip, out int rva)
{
if (ip == IntPtr.Zero)
{
rva = -1;
return null;
}
IntPtr moduleBase = RuntimeAugments.GetModuleFromPointer(ip);
if (moduleBase == IntPtr.Zero)
{
rva = -1;
return null;
}
rva = (int)(ip.ToInt64() - moduleBase.ToInt64());
if (s_loadedModules == null)
{
// Lazily create the parallel arrays s_loadedModules and s_perModuleDebugInfo
int moduleCount = RuntimeAugments.GetLoadedModules(null);
s_loadedModules = new IntPtr[moduleCount];
s_perModuleDebugInfo = new IDiaSession[moduleCount];
// Actually read the module addresses into the array
RuntimeAugments.GetLoadedModules(s_loadedModules);
}
// Locate module index based on base address
int moduleIndex = s_loadedModules.Length;
do
{
if (--moduleIndex < 0)
{
return null;
}
}
while(s_loadedModules[moduleIndex] != moduleBase);
IDiaSession diaSession = s_perModuleDebugInfo[moduleIndex];
if (diaSession != null)
{
return diaSession;
}
string modulePath = RuntimeAugments.TryGetFullPathToApplicationModule(moduleBase);
if (modulePath == null)
{
return null;
}
int indexOfLastDot = modulePath.LastIndexOf('.');
if (indexOfLastDot == -1)
{
return null;
}
IDiaDataSource diaDataSource = GetDiaDataSource();
if (diaDataSource == null)
{
return null;
}
// Look for .pdb next to .exe / dll - if it's not there, bail.
String pdbPath = modulePath.Substring(0, indexOfLastDot) + ".pdb";
int hr = diaDataSource.LoadDataFromPdb(pdbPath);
if (hr != S_OK)
{
return null;
}
hr = diaDataSource.OpenSession(out diaSession);
if (hr != S_OK)
{
return null;
}
s_perModuleDebugInfo[moduleIndex] = diaSession;
return diaSession;
}
// CoCreateInstance is not in WindowsApp_Downlevel.lib and ExactSpelling = true is required
// to force MCG to resolve it.
[DllImport("api-ms-win-core-com-l1-1-0.dll", ExactSpelling =true)]
private static extern unsafe int CoCreateInstance(byte* rclsid, IntPtr pUnkOuter, int dwClsContext, byte* riid, out IntPtr ppv);
private const int S_OK = 0;
private const int CLSCTX_INPROC = 0x3;
/// <summary>
/// Loaded binary module addresses.
/// </summary>
[ThreadStatic]
private static IntPtr[] s_loadedModules;
/// <summary>
/// DIA session COM interfaces for the individual native application modules.
/// The array is constructed upon the first call to GetDiaSession but the
/// COM interface instances are created lazily on demand.
/// This array is parallel to s_loadedModules - it has the same number of elements
/// and the corresponding entries have the same indices.
/// </summary>
[ThreadStatic]
private static IDiaSession[] s_perModuleDebugInfo;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ServiceBus.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Definition;
using Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Update;
using Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition;
using Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update;
using Microsoft.Azure.Management.ServiceBus.Fluent.Models;
using System.Collections.Generic;
internal partial class TopicAuthorizationRuleImpl
{
/// <summary>
/// Gets the manager client of this resource type.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasManager<Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusManager>.Manager
{
get
{
return this.Manager;
}
}
/// <summary>
/// Gets the resource ID string.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id
{
get
{
return this.Id;
}
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name;
}
}
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Definition.IWithListen<Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition.IWithCreate>.WithListeningEnabled()
{
return this.WithListeningEnabled();
}
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Update.IWithListen<Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update.IUpdate>.WithListeningEnabled()
{
return this.WithListeningEnabled();
}
/// <return>The primary, secondary keys and connection strings.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationKeys Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationRule<Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule>.GetKeys()
{
return this.GetKeys();
}
/// <summary>
/// Regenerates primary or secondary keys.
/// </summary>
/// <param name="policykey">The key to regenerate.</param>
/// <return>Primary, secondary keys and connection strings.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationKeys Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationRule<Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule>.RegenerateKey(Policykey policykey)
{
return this.RegenerateKey(policykey);
}
/// <summary>
/// Regenerates primary or secondary keys.
/// </summary>
/// <param name="policykey">The key to regenerate.</param>
/// <return>Stream that emits primary, secondary keys and connection strings.</return>
async Task<Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationKeys> Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationRule<Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule>.RegenerateKeyAsync(Policykey policykey, CancellationToken cancellationToken)
{
return await this.RegenerateKeyAsync(policykey, cancellationToken);
}
/// <summary>
/// Gets rights associated with the rule.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.ServiceBus.Fluent.Models.AccessRights> Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationRule<Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule>.Rights
{
get
{
return this.Rights();
}
}
/// <return>Stream that emits primary, secondary keys and connection strings.</return>
async Task<Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationKeys> Microsoft.Azure.Management.ServiceBus.Fluent.IAuthorizationRule<Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule>.GetKeysAsync(CancellationToken cancellationToken)
{
return await this.GetKeysAsync(cancellationToken);
}
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Definition.IWithManage<Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition.IWithCreate>.WithManagementEnabled()
{
return this.WithManagementEnabled();
}
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Update.IWithManage<Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update.IUpdate>.WithManagementEnabled()
{
return this.WithManagementEnabled();
}
/// <summary>
/// Gets the name of the region the resource is in.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.RegionName
{
get
{
return this.RegionName;
}
}
/// <summary>
/// Gets the tags for the resource.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<string, string> Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Tags
{
get
{
return this.Tags;
}
}
/// <summary>
/// Gets the region the resource is in.
/// </summary>
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Region
{
get
{
return this.Region;
}
}
/// <summary>
/// Gets the type of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource.Type
{
get
{
return this.Type;
}
}
/// <summary>
/// Gets the name of the namespace that the parent topic belongs to.
/// </summary>
string Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule.NamespaceName
{
get
{
return this.NamespaceName();
}
}
/// <summary>
/// Gets the name of the parent topic name.
/// </summary>
string Microsoft.Azure.Management.ServiceBus.Fluent.ITopicAuthorizationRule.TopicName
{
get
{
return this.TopicName();
}
}
/// <summary>
/// Gets the name of the resource group.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasResourceGroup.ResourceGroupName
{
get
{
return this.ResourceGroupName;
}
}
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Definition.IWithSend<Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Definition.IWithCreate>.WithSendingEnabled()
{
return this.WithSendingEnabled();
}
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.AuthorizationRule.Update.IWithSend<Microsoft.Azure.Management.ServiceBus.Fluent.TopicAuthorizationRule.Update.IUpdate>.WithSendingEnabled()
{
return this.WithSendingEnabled();
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using CorePhoto.IO;
using CorePhoto.Numerics;
namespace CorePhoto.Tiff
{
public static class TiffIfdReader
{
// Baseline TIFF fields
public static Task<string> ReadArtistAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.Artist, stream, byteOrder);
public static Task<uint[]> ReadBitsPerSampleAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.BitsPerSample);
if (entry == null)
return Task.FromResult(new uint[] { 1 });
else
return entry.Value.ReadIntegerArrayAsync(stream, byteOrder);
}
public static uint? GetCellLength(this TiffIfd ifd, ByteOrder byteOrder) => GetInteger(ifd, TiffTags.CellLength, byteOrder);
public static uint? GetCellWidth(this TiffIfd ifd, ByteOrder byteOrder) => GetInteger(ifd, TiffTags.CellWidth, byteOrder);
public static Task<uint[]> ReadColorMapAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.ColorMap, stream, byteOrder);
public static TiffCompression GetCompression(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.Compression);
return entry == null ? TiffCompression.None : (TiffCompression)entry.Value.GetInteger(byteOrder);
}
public static Task<string> ReadCopyrightAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.Copyright, stream, byteOrder);
public async static Task<DateTimeOffset?> ReadDateTimeAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.DateTime);
if (entry == null)
return null;
else
{
var str = await entry.Value.ReadStringAsync(stream, byteOrder);
return DateTimeOffset.ParseExact(str, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
}
}
public async static Task<TiffExtraSamples[]> ReadExtraSamplesAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.ExtraSamples);
if (entry == null)
return new TiffExtraSamples[0];
else
{
var values = await entry.Value.ReadIntegerArrayAsync(stream, byteOrder);
var result = new TiffExtraSamples[values.Length];
for (int i = 0; i < values.Length; i++)
{
result[i] = (TiffExtraSamples)values[i];
}
return result;
}
}
public static TiffFillOrder GetFillOrder(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.FillOrder);
return entry == null ? TiffFillOrder.MostSignificantBitFirst : (TiffFillOrder)entry.Value.GetInteger(byteOrder);
}
public static Task<uint[]> ReadFreeByteCountsAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.FreeByteCounts, stream, byteOrder);
public static Task<uint[]> ReadFreeOffsetsAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.FreeOffsets, stream, byteOrder);
public static Task<uint[]> ReadGrayResponseCurveAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.GrayResponseCurve, stream, byteOrder);
public static double GetGrayResponseUnit(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.GrayResponseUnit);
if (entry == null)
return 0.01;
else
{
var value = entry.Value.GetInteger(byteOrder);
return Math.Pow(10, -value);
}
}
public static Task<string> ReadHostComputerAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.HostComputer, stream, byteOrder);
public static Task<string> ReadImageDescriptionAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.ImageDescription, stream, byteOrder);
public static uint? GetImageLength(this TiffIfd ifd, ByteOrder byteOrder) => GetInteger(ifd, TiffTags.ImageLength, byteOrder);
public static uint? GetImageWidth(this TiffIfd ifd, ByteOrder byteOrder) => GetInteger(ifd, TiffTags.ImageWidth, byteOrder);
public static Task<string> ReadMakeAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.Make, stream, byteOrder);
public static Task<uint[]> ReadMaxSampleValueAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.MaxSampleValue, stream, byteOrder);
public static Task<uint[]> ReadMinSampleValueAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.MinSampleValue, stream, byteOrder);
public static Task<string> ReadModelAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.Model, stream, byteOrder);
public static TiffNewSubfileType GetNewSubfileType(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.NewSubfileType);
return entry == null ? TiffNewSubfileType.FullImage : (TiffNewSubfileType)entry.Value.GetInteger(byteOrder);
}
public static TiffOrientation GetOrientation(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.Orientation);
return entry == null ? TiffOrientation.TopLeft : (TiffOrientation)entry.Value.GetInteger(byteOrder);
}
public static TiffPhotometricInterpretation? GetPhotometricInterpretation(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.PhotometricInterpretation);
return entry == null ? null : (TiffPhotometricInterpretation?)entry.Value.GetInteger(byteOrder);
}
public static TiffPlanarConfiguration GetPlanarConfiguration(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.PlanarConfiguration);
return entry == null ? TiffPlanarConfiguration.Chunky : (TiffPlanarConfiguration)entry.Value.GetInteger(byteOrder);
}
public static TiffResolutionUnit GetResolutionUnit(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.ResolutionUnit);
return entry == null ? TiffResolutionUnit.Inch : (TiffResolutionUnit)entry.Value.GetInteger(byteOrder);
}
public static uint GetRowsPerStrip(this TiffIfd ifd, ByteOrder byteOrder) => GetInteger(ifd, TiffTags.RowsPerStrip, byteOrder) ?? UInt32.MaxValue;
public static uint GetSamplesPerPixel(this TiffIfd ifd, ByteOrder byteOrder) => GetInteger(ifd, TiffTags.SamplesPerPixel, byteOrder) ?? 1;
public static Task<string> ReadSoftwareAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadStringAsync(ifd, TiffTags.Software, stream, byteOrder);
public static Task<uint[]> ReadStripByteCountsAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.StripByteCounts, stream, byteOrder);
public static Task<uint[]> ReadStripOffsetsAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadIntegerArrayAsync(ifd, TiffTags.StripOffsets, stream, byteOrder);
public static TiffSubfileType? GetSubfileType(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.SubfileType);
return entry == null ? null : (TiffSubfileType?)entry.Value.GetInteger(byteOrder);
}
public static TiffThreshholding GetThreshholding(this TiffIfd ifd, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, TiffTags.Threshholding);
return entry == null ? TiffThreshholding.None : (TiffThreshholding)entry.Value.GetInteger(byteOrder);
}
public static Task<Rational?> ReadXResolutionAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadRationalAsync(ifd, TiffTags.XResolution, stream, byteOrder);
public static Task<Rational?> ReadYResolutionAsync(this TiffIfd ifd, Stream stream, ByteOrder byteOrder) => ReadRationalAsync(ifd, TiffTags.YResolution, stream, byteOrder);
// Helper functions
private static uint? GetInteger(TiffIfd ifd, ushort tag, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, tag);
return entry?.GetInteger(byteOrder);
}
private static Task<uint[]> ReadIntegerArrayAsync(TiffIfd ifd, ushort tag, Stream stream, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, tag);
if (entry == null)
return Task.FromResult<uint[]>(null);
else
return entry.Value.ReadIntegerArrayAsync(stream, byteOrder);
}
private async static Task<Rational?> ReadRationalAsync(TiffIfd ifd, ushort tag, Stream stream, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, tag);
if (entry == null)
return null;
else
return await entry.Value.ReadRationalAsync(stream, byteOrder);
}
private static Task<string> ReadStringAsync(TiffIfd ifd, ushort tag, Stream stream, ByteOrder byteOrder)
{
var entry = TiffReader.GetTiffIfdEntry(ifd, tag);
if (entry == null)
return Task.FromResult<string>(null);
else
return entry.Value.ReadStringAsync(stream, byteOrder);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: money/cards/transactions/get_open_batch_state_response.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 HOLMS.Types.Money.Cards.Transactions {
/// <summary>Holder for reflection information generated from money/cards/transactions/get_open_batch_state_response.proto</summary>
public static partial class GetOpenBatchStateResponseReflection {
#region Descriptor
/// <summary>File descriptor for money/cards/transactions/get_open_batch_state_response.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GetOpenBatchStateResponseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjxtb25leS9jYXJkcy90cmFuc2FjdGlvbnMvZ2V0X29wZW5fYmF0Y2hfc3Rh",
"dGVfcmVzcG9uc2UucHJvdG8SJGhvbG1zLnR5cGVzLm1vbmV5LmNhcmRzLnRy",
"YW5zYWN0aW9ucxo4bW9uZXkvY2FyZHMvdHJhbnNhY3Rpb25zL3BheW1lbnRf",
"Y2FyZF9zYWxlX2NhcHR1cmUucHJvdG8aMm1vbmV5L2NhcmRzL3RyYW5zYWN0",
"aW9ucy9wYXltZW50X2NhcmRfcmVmdW5kLnByb3RvGjBtb25leS9jYXJkcy90",
"cmFuc2FjdGlvbnMvcGF5bWVudF9jYXJkX3NhbGUucHJvdG8i5QIKGUdldE9w",
"ZW5CYXRjaFN0YXRlUmVzcG9uc2USUAoGcmVzdWx0GAEgASgOMkAuaG9sbXMu",
"dHlwZXMubW9uZXkuY2FyZHMudHJhbnNhY3Rpb25zLkdldEN1cnJlbnRCYXRj",
"aFN0YXRlUmVzdWx0ElYKEHBlbmRpbmdfY2FwdHVyZXMYAiADKAsyPC5ob2xt",
"cy50eXBlcy5tb25leS5jYXJkcy50cmFuc2FjdGlvbnMuUGF5bWVudENhcmRT",
"YWxlQ2FwdHVyZRJQCg9wZW5kaW5nX3JlZnVuZHMYAyADKAsyNy5ob2xtcy50",
"eXBlcy5tb25leS5jYXJkcy50cmFuc2FjdGlvbnMuUGF5bWVudENhcmRSZWZ1",
"bmQSTAoNcGF5bWVudF9zYWxlcxgEIAMoCzI1LmhvbG1zLnR5cGVzLm1vbmV5",
"LmNhcmRzLnRyYW5zYWN0aW9ucy5QYXltZW50Q2FyZFNhbGUqwgIKGkdldEN1",
"cnJlbnRCYXRjaFN0YXRlUmVzdWx0EkQKQENBUkRfUFJPQ0VTU0lOR19TVkNf",
"R0VUX0NVUlJFTlRfQkFUQ0hfU1RBVEVfUkVTVUxUX1VOS05PV05fRVJST1IQ",
"ABJUClBDQVJEX1BST0NFU1NJTkdfU1ZDX0dFVF9DVVJSRU5UX0JBVENIX1NU",
"QVRFX1JFU1VMVF9QUk9DRVNTT1JfQ09NTVVOSUNBVElPTl9FUlJPUhABEkUK",
"QUNBUkRfUFJPQ0VTU0lOR19TVkNfR0VUX0NVUlJFTlRfQkFUQ0hfU1RBVEVf",
"UkVTVUxUX0JBVENIX05PVF9PUEVOEAISQQo9Q0FSRF9QUk9DRVNTSU5HX1NW",
"Q19HRVRfQ1VSUkVOVF9CQVRDSF9TVEFURV9SRVNVTFRfQkFUQ0hfT1BFThAD",
"QieqAiRIT0xNUy5UeXBlcy5Nb25leS5DYXJkcy5UcmFuc2FjdGlvbnNiBnBy",
"b3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleCaptureReflection.Descriptor, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefundReflection.Descriptor, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Money.Cards.Transactions.GetCurrentBatchStateResult), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse), global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponse.Parser, new[]{ "Result", "PendingCaptures", "PendingRefunds", "PaymentSales" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum GetCurrentBatchStateResult {
[pbr::OriginalName("CARD_PROCESSING_SVC_GET_CURRENT_BATCH_STATE_RESULT_UNKNOWN_ERROR")] CardProcessingSvcGetCurrentBatchStateResultUnknownError = 0,
[pbr::OriginalName("CARD_PROCESSING_SVC_GET_CURRENT_BATCH_STATE_RESULT_PROCESSOR_COMMUNICATION_ERROR")] CardProcessingSvcGetCurrentBatchStateResultProcessorCommunicationError = 1,
[pbr::OriginalName("CARD_PROCESSING_SVC_GET_CURRENT_BATCH_STATE_RESULT_BATCH_NOT_OPEN")] CardProcessingSvcGetCurrentBatchStateResultBatchNotOpen = 2,
[pbr::OriginalName("CARD_PROCESSING_SVC_GET_CURRENT_BATCH_STATE_RESULT_BATCH_OPEN")] CardProcessingSvcGetCurrentBatchStateResultBatchOpen = 3,
}
#endregion
#region Messages
public sealed partial class GetOpenBatchStateResponse : pb::IMessage<GetOpenBatchStateResponse> {
private static readonly pb::MessageParser<GetOpenBatchStateResponse> _parser = new pb::MessageParser<GetOpenBatchStateResponse>(() => new GetOpenBatchStateResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetOpenBatchStateResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Money.Cards.Transactions.GetOpenBatchStateResponseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetOpenBatchStateResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetOpenBatchStateResponse(GetOpenBatchStateResponse other) : this() {
result_ = other.result_;
pendingCaptures_ = other.pendingCaptures_.Clone();
pendingRefunds_ = other.pendingRefunds_.Clone();
paymentSales_ = other.paymentSales_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetOpenBatchStateResponse Clone() {
return new GetOpenBatchStateResponse(this);
}
/// <summary>Field number for the "result" field.</summary>
public const int ResultFieldNumber = 1;
private global::HOLMS.Types.Money.Cards.Transactions.GetCurrentBatchStateResult result_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.Cards.Transactions.GetCurrentBatchStateResult Result {
get { return result_; }
set {
result_ = value;
}
}
/// <summary>Field number for the "pending_captures" field.</summary>
public const int PendingCapturesFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleCapture> _repeated_pendingCaptures_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleCapture.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleCapture> pendingCaptures_ = new pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleCapture>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleCapture> PendingCaptures {
get { return pendingCaptures_; }
}
/// <summary>Field number for the "pending_refunds" field.</summary>
public const int PendingRefundsFieldNumber = 3;
private static readonly pb::FieldCodec<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund> _repeated_pendingRefunds_codec
= pb::FieldCodec.ForMessage(26, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund> pendingRefunds_ = new pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardRefund> PendingRefunds {
get { return pendingRefunds_; }
}
/// <summary>Field number for the "payment_sales" field.</summary>
public const int PaymentSalesFieldNumber = 4;
private static readonly pb::FieldCodec<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSale> _repeated_paymentSales_codec
= pb::FieldCodec.ForMessage(34, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSale.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSale> paymentSales_ = new pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSale>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSale> PaymentSales {
get { return paymentSales_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetOpenBatchStateResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetOpenBatchStateResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Result != other.Result) return false;
if(!pendingCaptures_.Equals(other.pendingCaptures_)) return false;
if(!pendingRefunds_.Equals(other.pendingRefunds_)) return false;
if(!paymentSales_.Equals(other.paymentSales_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Result != 0) hash ^= Result.GetHashCode();
hash ^= pendingCaptures_.GetHashCode();
hash ^= pendingRefunds_.GetHashCode();
hash ^= paymentSales_.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 (Result != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Result);
}
pendingCaptures_.WriteTo(output, _repeated_pendingCaptures_codec);
pendingRefunds_.WriteTo(output, _repeated_pendingRefunds_codec);
paymentSales_.WriteTo(output, _repeated_paymentSales_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Result != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result);
}
size += pendingCaptures_.CalculateSize(_repeated_pendingCaptures_codec);
size += pendingRefunds_.CalculateSize(_repeated_pendingRefunds_codec);
size += paymentSales_.CalculateSize(_repeated_paymentSales_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetOpenBatchStateResponse other) {
if (other == null) {
return;
}
if (other.Result != 0) {
Result = other.Result;
}
pendingCaptures_.Add(other.pendingCaptures_);
pendingRefunds_.Add(other.pendingRefunds_);
paymentSales_.Add(other.paymentSales_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
result_ = (global::HOLMS.Types.Money.Cards.Transactions.GetCurrentBatchStateResult) input.ReadEnum();
break;
}
case 18: {
pendingCaptures_.AddEntriesFrom(input, _repeated_pendingCaptures_codec);
break;
}
case 26: {
pendingRefunds_.AddEntriesFrom(input, _repeated_pendingRefunds_codec);
break;
}
case 34: {
paymentSales_.AddEntriesFrom(input, _repeated_paymentSales_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Reflection;
using Dg.Deblazer;
using Dg.Deblazer.Validation;
using Dg.Deblazer.CodeAnnotation;
using Dg.Deblazer.Api;
using Dg.Deblazer.Visitors;
using Dg.Deblazer.Cache;
using Dg.Deblazer.SqlGeneration;
using Deblazer.WideWorldImporter.DbLayer.Queries;
using Deblazer.WideWorldImporter.DbLayer.Wrappers;
using Dg.Deblazer.Read;
namespace Deblazer.WideWorldImporter.DbLayer
{
public partial class Purchasing_SupplierCategory : DbEntity, IId
{
private DbValue<System.Int32> _SupplierCategoryID = new DbValue<System.Int32>();
private DbValue<System.String> _SupplierCategoryName = new DbValue<System.String>();
private DbValue<System.Int32> _LastEditedBy = new DbValue<System.Int32>();
private DbValue<System.DateTime> _ValidFrom = new DbValue<System.DateTime>();
private DbValue<System.DateTime> _ValidTo = new DbValue<System.DateTime>();
private IDbEntityRef<Application_People> _Application_People;
private IDbEntitySet<Purchasing_Supplier> _Purchasing_Suppliers;
public int Id => SupplierCategoryID;
long ILongId.Id => SupplierCategoryID;
[Validate]
public System.Int32 SupplierCategoryID
{
get
{
return _SupplierCategoryID.Entity;
}
set
{
_SupplierCategoryID.Entity = value;
}
}
[StringColumn(50, false)]
[Validate]
public System.String SupplierCategoryName
{
get
{
return _SupplierCategoryName.Entity;
}
set
{
_SupplierCategoryName.Entity = value;
}
}
[Validate]
public System.Int32 LastEditedBy
{
get
{
return _LastEditedBy.Entity;
}
set
{
_LastEditedBy.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidFrom
{
get
{
return _ValidFrom.Entity;
}
set
{
_ValidFrom.Entity = value;
}
}
[StringColumn(7, false)]
[Validate]
public System.DateTime ValidTo
{
get
{
return _ValidTo.Entity;
}
set
{
_ValidTo.Entity = value;
}
}
[Validate]
public Application_People Application_People
{
get
{
Action<Application_People> beforeRightsCheckAction = e => e.Purchasing_SupplierCategories.Add(this);
if (_Application_People != null)
{
return _Application_People.GetEntity(beforeRightsCheckAction);
}
_Application_People = GetDbEntityRef(true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, beforeRightsCheckAction);
return (Application_People != null) ? _Application_People.GetEntity(beforeRightsCheckAction) : null;
}
set
{
if (_Application_People == null)
{
_Application_People = new DbEntityRef<Application_People>(_db, true, new[]{"[LastEditedBy]"}, new Func<long ? >[]{() => _LastEditedBy.Entity}, _lazyLoadChildren, _getChildrenFromCache);
}
AssignDbEntity<Application_People, Purchasing_SupplierCategory>(value, value == null ? new long ? [0] : new long ? []{(long ? )value.PersonID}, _Application_People, new long ? []{_LastEditedBy.Entity}, new Action<long ? >[]{x => LastEditedBy = (int ? )x ?? default (int)}, x => x.Purchasing_SupplierCategories, null, LastEditedByChanged);
}
}
void LastEditedByChanged(object sender, EventArgs eventArgs)
{
if (sender is Application_People)
_LastEditedBy.Entity = (int)((Application_People)sender).Id;
}
[Validate]
public IDbEntitySet<Purchasing_Supplier> Purchasing_Suppliers
{
get
{
if (_Purchasing_Suppliers == null)
{
if (_getChildrenFromCache)
{
_Purchasing_Suppliers = new DbEntitySetCached<Purchasing_SupplierCategory, Purchasing_Supplier>(() => _SupplierCategoryID.Entity);
}
}
else
_Purchasing_Suppliers = new DbEntitySet<Purchasing_Supplier>(_db, false, new Func<long ? >[]{() => _SupplierCategoryID.Entity}, new[]{"[SupplierCategoryID]"}, (member, root) => member.Purchasing_SupplierCategory = root as Purchasing_SupplierCategory, this, _lazyLoadChildren, e => e.Purchasing_SupplierCategory = this, e =>
{
var x = e.Purchasing_SupplierCategory;
e.Purchasing_SupplierCategory = null;
new UpdateSetVisitor(true, new[]{"SupplierCategoryID"}, false).Process(x);
}
);
return _Purchasing_Suppliers;
}
}
protected override void ModifyInternalState(FillVisitor visitor)
{
SendIdChanging();
_SupplierCategoryID.Load(visitor.GetInt32());
SendIdChanged();
_SupplierCategoryName.Load(visitor.GetValue<System.String>());
_LastEditedBy.Load(visitor.GetInt32());
_ValidFrom.Load(visitor.GetDateTime());
_ValidTo.Load(visitor.GetDateTime());
this._db = visitor.Db;
isLoaded = true;
}
protected sealed override void CheckProperties(IUpdateVisitor visitor)
{
_SupplierCategoryID.Welcome(visitor, "SupplierCategoryID", "Int NOT NULL", false);
_SupplierCategoryName.Welcome(visitor, "SupplierCategoryName", "NVarChar(50) NOT NULL", false);
_LastEditedBy.Welcome(visitor, "LastEditedBy", "Int NOT NULL", false);
_ValidFrom.Welcome(visitor, "ValidFrom", "DateTime2(7) NOT NULL", false);
_ValidTo.Welcome(visitor, "ValidTo", "DateTime2(7) NOT NULL", false);
}
protected override void HandleChildren(DbEntityVisitorBase visitor)
{
visitor.ProcessAssociation(this, _Application_People);
visitor.ProcessAssociation(this, _Purchasing_Suppliers);
}
}
public static class Db_Purchasing_SupplierCategoryQueryGetterExtensions
{
public static Purchasing_SupplierCategoryTableQuery<Purchasing_SupplierCategory> Purchasing_SupplierCategories(this IDb db)
{
var query = new Purchasing_SupplierCategoryTableQuery<Purchasing_SupplierCategory>(db as IDb);
return query;
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Queries
{
public class Purchasing_SupplierCategoryQuery<K, T> : Query<K, T, Purchasing_SupplierCategory, Purchasing_SupplierCategoryWrapper, Purchasing_SupplierCategoryQuery<K, T>> where K : QueryBase where T : DbEntity, ILongId
{
public Purchasing_SupplierCategoryQuery(IDb db): base (db)
{
}
protected sealed override Purchasing_SupplierCategoryWrapper GetWrapper()
{
return Purchasing_SupplierCategoryWrapper.Instance;
}
public Application_PeopleQuery<Purchasing_SupplierCategoryQuery<K, T>, T> JoinApplication_People(JoinType joinType = JoinType.Inner, bool preloadEntities = false)
{
var joinedQuery = new Application_PeopleQuery<Purchasing_SupplierCategoryQuery<K, T>, T>(Db);
return Join(joinedQuery, string.Concat(joinType.GetJoinString(), " [Application].[People] AS {1} {0} ON", "{2}.[LastEditedBy] = {1}.[PersonID]"), o => ((Purchasing_SupplierCategory)o)?.Application_People, (e, fv, ppe) =>
{
var child = (Application_People)ppe(QueryHelpers.Fill<Application_People>(null, fv));
if (e != null)
{
((Purchasing_SupplierCategory)e).Application_People = child;
}
return child;
}
, typeof (Application_People), preloadEntities);
}
public Purchasing_SupplierQuery<Purchasing_SupplierCategoryQuery<K, T>, T> JoinPurchasing_Suppliers(JoinType joinType = JoinType.Inner, bool attach = false)
{
var joinedQuery = new Purchasing_SupplierQuery<Purchasing_SupplierCategoryQuery<K, T>, T>(Db);
return JoinSet(() => new Purchasing_SupplierTableQuery<Purchasing_Supplier>(Db), joinedQuery, string.Concat(joinType.GetJoinString(), " [Purchasing].[Suppliers] AS {1} {0} ON", "{2}.[SupplierCategoryID] = {1}.[SupplierCategoryID]"), (p, ids) => ((Purchasing_SupplierWrapper)p).Id.In(ids.Select(id => (System.Int32)id)), (o, v) => ((Purchasing_SupplierCategory)o).Purchasing_Suppliers.Attach(v.Cast<Purchasing_Supplier>()), p => (long)((Purchasing_Supplier)p).SupplierCategoryID, attach);
}
}
public class Purchasing_SupplierCategoryTableQuery<T> : Purchasing_SupplierCategoryQuery<Purchasing_SupplierCategoryTableQuery<T>, T> where T : DbEntity, ILongId
{
public Purchasing_SupplierCategoryTableQuery(IDb db): base (db)
{
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Helpers
{
public class Purchasing_SupplierCategoryHelper : QueryHelper<Purchasing_SupplierCategory>, IHelper<Purchasing_SupplierCategory>
{
string[] columnsInSelectStatement = new[]{"{0}.SupplierCategoryID", "{0}.SupplierCategoryName", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInSelectStatement => columnsInSelectStatement;
string[] columnsInInsertStatement = new[]{"{0}.SupplierCategoryID", "{0}.SupplierCategoryName", "{0}.LastEditedBy", "{0}.ValidFrom", "{0}.ValidTo"};
public sealed override string[] ColumnsInInsertStatement => columnsInInsertStatement;
private static readonly string createTempTableCommand = "CREATE TABLE #Purchasing_SupplierCategory ([SupplierCategoryID] Int NOT NULL,[SupplierCategoryName] NVarChar(50) NOT NULL,[LastEditedBy] Int NOT NULL,[ValidFrom] DateTime2(7) NOT NULL,[ValidTo] DateTime2(7) NOT NULL, [RowIndexForSqlBulkCopy] INT NOT NULL)";
public sealed override string CreateTempTableCommand => createTempTableCommand;
public sealed override string FullTableName => "[Purchasing].[SupplierCategories]";
public sealed override bool IsForeignKeyTo(Type other)
{
return other == typeof (Purchasing_Supplier);
}
private const string insertCommand = "INSERT INTO [Purchasing].[SupplierCategories] ([{TableName = \"Purchasing].[SupplierCategories\";}].[SupplierCategoryID], [{TableName = \"Purchasing].[SupplierCategories\";}].[SupplierCategoryName], [{TableName = \"Purchasing].[SupplierCategories\";}].[LastEditedBy], [{TableName = \"Purchasing].[SupplierCategories\";}].[ValidFrom], [{TableName = \"Purchasing].[SupplierCategories\";}].[ValidTo]) VALUES ([@SupplierCategoryID],[@SupplierCategoryName],[@LastEditedBy],[@ValidFrom],[@ValidTo]); SELECT SCOPE_IDENTITY()";
public sealed override void FillInsertCommand(SqlCommand sqlCommand, Purchasing_SupplierCategory _Purchasing_SupplierCategory)
{
sqlCommand.CommandText = insertCommand;
sqlCommand.Parameters.AddWithValue("@SupplierCategoryID", _Purchasing_SupplierCategory.SupplierCategoryID);
sqlCommand.Parameters.AddWithValue("@SupplierCategoryName", _Purchasing_SupplierCategory.SupplierCategoryName ?? (object)DBNull.Value);
sqlCommand.Parameters.AddWithValue("@LastEditedBy", _Purchasing_SupplierCategory.LastEditedBy);
sqlCommand.Parameters.AddWithValue("@ValidFrom", _Purchasing_SupplierCategory.ValidFrom);
sqlCommand.Parameters.AddWithValue("@ValidTo", _Purchasing_SupplierCategory.ValidTo);
}
public sealed override void ExecuteInsertCommand(SqlCommand sqlCommand, Purchasing_SupplierCategory _Purchasing_SupplierCategory)
{
using (var sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
sqlDataReader.Read();
_Purchasing_SupplierCategory.SupplierCategoryID = Convert.ToInt32(sqlDataReader.GetValue(0));
}
}
private static Purchasing_SupplierCategoryWrapper _wrapper = Purchasing_SupplierCategoryWrapper.Instance;
public QueryWrapper Wrapper
{
get
{
return _wrapper;
}
}
}
}
namespace Deblazer.WideWorldImporter.DbLayer.Wrappers
{
public class Purchasing_SupplierCategoryWrapper : QueryWrapper<Purchasing_SupplierCategory>
{
public readonly QueryElMemberId<Application_People> LastEditedBy = new QueryElMemberId<Application_People>("LastEditedBy");
public readonly QueryElMember<System.String> SupplierCategoryName = new QueryElMember<System.String>("SupplierCategoryName");
public readonly QueryElMemberStruct<System.DateTime> ValidFrom = new QueryElMemberStruct<System.DateTime>("ValidFrom");
public readonly QueryElMemberStruct<System.DateTime> ValidTo = new QueryElMemberStruct<System.DateTime>("ValidTo");
public static readonly Purchasing_SupplierCategoryWrapper Instance = new Purchasing_SupplierCategoryWrapper();
private Purchasing_SupplierCategoryWrapper(): base ("[Purchasing].[SupplierCategories]", "Purchasing_SupplierCategory")
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Monitor.Fluent
{
using Microsoft.Azure.Management.Monitor.Fluent.AutoscaleProfile.Definition;
using Microsoft.Azure.Management.Monitor.Fluent.AutoscaleProfile.Update;
using Microsoft.Azure.Management.Monitor.Fluent.AutoscaleProfile.UpdateDefinition;
using Microsoft.Azure.Management.Monitor.Fluent.Models;
using Microsoft.Azure.Management.Monitor.Fluent.ScaleRule.Definition;
using Microsoft.Azure.Management.Monitor.Fluent.ScaleRule.ParentUpdateDefinition;
using Microsoft.Azure.Management.Monitor.Fluent.ScaleRule.Update;
using Microsoft.Azure.Management.Monitor.Fluent.ScaleRule.UpdateDefinition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions;
using System;
internal partial class ScaleRuleImpl
{
/// <summary>
/// Gets the operator that is used to compare the metric data and the threshold. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.
/// </summary>
/// <summary>
/// Gets the operator value.
/// </summary>
Models.ComparisonOperationType Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.Condition
{
get
{
return this.Condition();
}
}
/// <summary>
/// Gets the amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.
/// </summary>
/// <summary>
/// Gets the cooldown value.
/// </summary>
System.TimeSpan Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.CoolDown
{
get
{
return this.CoolDown();
}
}
/// <summary>
/// Gets the range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.
/// </summary>
/// <summary>
/// Gets the timeWindow value.
/// </summary>
System.TimeSpan Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.Duration
{
get
{
return this.Duration();
}
}
/// <summary>
/// Gets the granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.
/// </summary>
/// <summary>
/// Gets the timeGrain value.
/// </summary>
System.TimeSpan Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.Frequency
{
get
{
return this.Frequency();
}
}
/// <summary>
/// Gets the metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.
/// </summary>
/// <summary>
/// Gets the statistic value.
/// </summary>
Models.MetricStatisticType Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.FrequencyStatistic
{
get
{
return this.FrequencyStatistic();
}
}
/// <summary>
/// Gets the name of the metric that defines what the rule monitors.
/// </summary>
/// <summary>
/// Gets the metricName value.
/// </summary>
string Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.MetricName
{
get
{
return this.MetricName();
}
}
/// <summary>
/// Gets the resource identifier of the resource the rule monitors.
/// </summary>
/// <summary>
/// Gets the metricResourceUri value.
/// </summary>
string Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.MetricSource
{
get
{
return this.MetricSource();
}
}
/// <summary>
/// Gets the parent of this child object.
/// </summary>
Microsoft.Azure.Management.Monitor.Fluent.IAutoscaleProfile Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasParent<Microsoft.Azure.Management.Monitor.Fluent.IAutoscaleProfile>.Parent
{
get
{
return this.Parent();
}
}
/// <summary>
/// Gets the scale direction. Whether the scaling action increases or decreases the number of instances. Possible values include: 'None', 'Increase', 'Decrease'.
/// </summary>
/// <summary>
/// Gets the direction value.
/// </summary>
Models.ScaleDirection Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.ScaleDirection
{
get
{
return this.ScaleDirection();
}
}
/// <summary>
/// Gets the number of instances that are involved in the scaling action.
/// </summary>
/// <summary>
/// Gets the value value.
/// </summary>
int Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.ScaleInstanceCount
{
get
{
return this.ScaleInstanceCount();
}
}
/// <summary>
/// Gets the type of action that should occur when the scale rule fires. Possible values include: 'ChangeCount', 'PercentChangeCount', 'ExactCount'.
/// </summary>
/// <summary>
/// Gets the type value.
/// </summary>
Models.ScaleType Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.ScaleType
{
get
{
return this.ScaleType();
}
}
/// <summary>
/// Gets the threshold of the metric that triggers the scale action.
/// </summary>
/// <summary>
/// Gets the threshold value.
/// </summary>
double Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.Threshold
{
get
{
return this.Threshold();
}
}
/// <summary>
/// Gets the time aggregation type. How the data that is collected should be combined over time. The default value is Average. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total', 'Count'.
/// </summary>
/// <summary>
/// Gets the timeAggregation value.
/// </summary>
Models.TimeAggregationType Microsoft.Azure.Management.Monitor.Fluent.IScaleRule.TimeAggregation
{
get
{
return this.TimeAggregation();
}
}
/// <summary>
/// Attaches sclae rule to the new autoscale profile in the autoscale update definition stage.
/// </summary>
/// <return>The next stage of the parent definition.</return>
AutoscaleProfile.UpdateDefinition.IWithScaleRuleOptional ScaleRule.ParentUpdateDefinition.IWithAttach.Attach()
{
return this.Attach();
}
/// <summary>
/// Attaches the child definition to the parent resource update.
/// </summary>
/// <return>The next stage of the parent definition.</return>
AutoscaleProfile.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<AutoscaleProfile.Update.IUpdate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
AutoscaleProfile.Definition.IWithScaleRuleOptional Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<AutoscaleProfile.Definition.IWithScaleRuleOptional>.Attach()
{
return this.Attach();
}
/// <summary>
/// Begins an update for a child resource.
/// This is the beginning of the builder pattern used to update child resources
/// The final method completing the update and continue
/// the actual parent resource update process in Azure is Settable.parent().
/// </summary>
/// <return>The stage of parent resource update.</return>
AutoscaleProfile.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions.ISettable<AutoscaleProfile.Update.IUpdate>.Parent()
{
return this.Parent();
}
/// <summary>
/// Updates the condition to monitor for the current metric alert.
/// </summary>
/// <param name="condition">The operator that is used to compare the metric data and the threshold. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param>
/// <param name="timeAggregation">The time aggregation type. How the data that is collected should be combined over time. The default value is Average. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total', 'Count'.</param>
/// <param name="threshold">The threshold of the metric that triggers the scale action.</param>
/// <return>The next stage of the scale rule update.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithCondition(TimeAggregationType timeAggregation, ComparisonOperationType condition, double threshold)
{
return this.WithCondition(timeAggregation, condition, threshold);
}
/// <summary>
/// Sets the condition to monitor for the current metric alert.
/// </summary>
/// <param name="condition">The operator that is used to compare the metric data and the threshold. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param>
/// <param name="timeAggregation">The time aggregation type. How the data that is collected should be combined over time. The default value is Average. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total', 'Count'.</param>
/// <param name="threshold">The threshold of the metric that triggers the scale action.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithScaleAction ScaleRule.ParentUpdateDefinition.IWithCondition.WithCondition(TimeAggregationType timeAggregation, ComparisonOperationType condition, double threshold)
{
return this.WithCondition(timeAggregation, condition, threshold);
}
/// <summary>
/// Sets the condition to monitor for the current metric alert.
/// </summary>
/// <param name="condition">The operator that is used to compare the metric data and the threshold. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param>
/// <param name="timeAggregation">The time aggregation type. How the data that is collected should be combined over time. The default value is Average. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total', 'Count'.</param>
/// <param name="threshold">The threshold of the metric that triggers the scale action.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithScaleAction ScaleRule.UpdateDefinition.IWithCondition.WithCondition(TimeAggregationType timeAggregation, ComparisonOperationType condition, double threshold)
{
return this.WithCondition(timeAggregation, condition, threshold);
}
/// <summary>
/// Sets the condition to monitor for the current metric alert.
/// </summary>
/// <param name="condition">The operator that is used to compare the metric data and the threshold. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual'.</param>
/// <param name="timeAggregation">The time aggregation type. How the data that is collected should be combined over time. The default value is Average. Possible values include: 'Average', 'Minimum', 'Maximum', 'Total', 'Count'.</param>
/// <param name="threshold">The threshold of the metric that triggers the scale action.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithScaleAction ScaleRule.Definition.IWithCondition.WithCondition(TimeAggregationType timeAggregation, ComparisonOperationType condition, double threshold)
{
return this.WithCondition(timeAggregation, condition, threshold);
}
/// <summary>
/// The name of the metric that defines what the rule monitors.
/// </summary>
/// <param name="metricName">MetricName name of the metric.</param>
/// <return>The next stage of the scale rule update.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithMetricName(string metricName)
{
return this.WithMetricName(metricName);
}
/// <summary>
/// Sets the name of the metric that defines what the rule monitors.
/// </summary>
/// <param name="metricName">Name of the metric.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithStatistic ScaleRule.ParentUpdateDefinition.IWithMetricName.WithMetricName(string metricName)
{
return this.WithMetricName(metricName);
}
/// <summary>
/// Sets the name of the metric that defines what the rule monitors.
/// </summary>
/// <param name="metricName">Name of the metric.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithStatistic ScaleRule.UpdateDefinition.IWithMetricName.WithMetricName(string metricName)
{
return this.WithMetricName(metricName);
}
/// <summary>
/// Sets the name of the metric that defines what the rule monitors.
/// </summary>
/// <param name="metricName">Name of the metric.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithStatistic ScaleRule.Definition.IWithMetricName.WithMetricName(string metricName)
{
return this.WithMetricName(metricName);
}
/// <summary>
/// Updates the resource identifier of the resource the rule monitors.
/// </summary>
/// <param name="metricSourceResourceId">ResourceId of the resource.</param>
/// <return>The next stage of the scale rule update.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithMetricSource(string metricSourceResourceId)
{
return this.WithMetricSource(metricSourceResourceId);
}
/// <summary>
/// Sets the resource identifier of the resource the rule monitors.
/// </summary>
/// <param name="metricSourceResourceId">ResourceId of the resource.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithMetricName ScaleRule.ParentUpdateDefinition.IBlank.WithMetricSource(string metricSourceResourceId)
{
return this.WithMetricSource(metricSourceResourceId);
}
/// <summary>
/// Sets the resource identifier of the resource the rule monitors.
/// </summary>
/// <param name="metricSourceResourceId">ResourceId of the resource.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithMetricName ScaleRule.UpdateDefinition.IBlank.WithMetricSource(string metricSourceResourceId)
{
return this.WithMetricSource(metricSourceResourceId);
}
/// <summary>
/// Sets the resource identifier of the resource the rule monitors.
/// </summary>
/// <param name="metricSourceResourceId">ResourceId of the resource.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithMetricName ScaleRule.Definition.IBlank.WithMetricSource(string metricSourceResourceId)
{
return this.WithMetricSource(metricSourceResourceId);
}
/// <summary>
/// Updates the action to be performed when the scale rule will be active.
/// </summary>
/// <param name="direction">The scale direction. Whether the scaling action increases or decreases the number of instances. Possible values include: 'None', 'Increase', 'Decrease'.</param>
/// <param name="type">The type of action that should occur when the scale rule fires. Possible values include: 'ChangeCount', 'PercentChangeCount', 'ExactCount'.</param>
/// <param name="instanceCountChange">The number of instances that are involved in the scaling action.</param>
/// <param name="cooldown">The amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.</param>
/// <return>The next stage of the scale rule update.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithScaleAction(ScaleDirection direction, ScaleType type, int instanceCountChange, TimeSpan cooldown)
{
return this.WithScaleAction(direction, type, instanceCountChange, cooldown);
}
/// <summary>
/// Sets the action to be performed when the scale rule will be active.
/// </summary>
/// <param name="direction">The scale direction. Whether the scaling action increases or decreases the number of instances. Possible values include: 'None', 'Increase', 'Decrease'.</param>
/// <param name="type">The type of action that should occur when the scale rule fires. Possible values include: 'ChangeCount', 'PercentChangeCount', 'ExactCount'.</param>
/// <param name="instanceCountChange">The number of instances that are involved in the scaling action.</param>
/// <param name="cooldown">The amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithAttach ScaleRule.ParentUpdateDefinition.IWithScaleAction.WithScaleAction(ScaleDirection direction, ScaleType type, int instanceCountChange, TimeSpan cooldown)
{
return this.WithScaleAction(direction, type, instanceCountChange, cooldown);
}
/// <summary>
/// Sets the action to be performed when the scale rule will be active.
/// </summary>
/// <param name="direction">The scale direction. Whether the scaling action increases or decreases the number of instances. Possible values include: 'None', 'Increase', 'Decrease'.</param>
/// <param name="type">The type of action that should occur when the scale rule fires. Possible values include: 'ChangeCount', 'PercentChangeCount', 'ExactCount'.</param>
/// <param name="instanceCountChange">The number of instances that are involved in the scaling action.</param>
/// <param name="cooldown">The amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithAttach ScaleRule.UpdateDefinition.IWithScaleAction.WithScaleAction(ScaleDirection direction, ScaleType type, int instanceCountChange, TimeSpan cooldown)
{
return this.WithScaleAction(direction, type, instanceCountChange, cooldown);
}
/// <summary>
/// Sets the action to be performed when the scale rule will be active.
/// </summary>
/// <param name="direction">The scale direction. Whether the scaling action increases or decreases the number of instances. Possible values include: 'None', 'Increase', 'Decrease'.</param>
/// <param name="type">The type of action that should occur when the scale rule fires. Possible values include: 'ChangeCount', 'PercentChangeCount', 'ExactCount'.</param>
/// <param name="instanceCountChange">The number of instances that are involved in the scaling action.</param>
/// <param name="cooldown">The amount of time to wait since the last scaling action before this action occurs. It must be between 1 week and 1 minute in ISO 8601 format.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithAttach ScaleRule.Definition.IWithScaleAction.WithScaleAction(ScaleDirection direction, ScaleType type, int instanceCountChange, TimeSpan cooldown)
{
return this.WithScaleAction(direction, type, instanceCountChange, cooldown);
}
/// <summary>
/// Updates the statistics for autoscale trigger action.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="frequency">The granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the scale rule update.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithStatistic(TimeSpan duration, TimeSpan frequency, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, frequency, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 10 minutes for duration, 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <return>The next stage of the definition.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithStatistic()
{
return this.WithStatistic();
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithStatistic(TimeSpan duration)
{
return this.WithStatistic(duration);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain).
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Update.IUpdate ScaleRule.Update.IUpdate.WithStatistic(TimeSpan duration, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="frequency">The granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithCondition ScaleRule.ParentUpdateDefinition.IWithStatistic.WithStatistic(TimeSpan duration, TimeSpan frequency, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, frequency, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 10 minutes for duration, 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithCondition ScaleRule.ParentUpdateDefinition.IWithStatistic.WithStatistic()
{
return this.WithStatistic();
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithCondition ScaleRule.ParentUpdateDefinition.IWithStatistic.WithStatistic(TimeSpan duration)
{
return this.WithStatistic(duration);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain).
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.ParentUpdateDefinition.IWithCondition ScaleRule.ParentUpdateDefinition.IWithStatistic.WithStatistic(TimeSpan duration, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="frequency">The granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithCondition ScaleRule.UpdateDefinition.IWithStatistic.WithStatistic(TimeSpan duration, TimeSpan frequency, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, frequency, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 10 minutes for duration, 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithCondition ScaleRule.UpdateDefinition.IWithStatistic.WithStatistic()
{
return this.WithStatistic();
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithCondition ScaleRule.UpdateDefinition.IWithStatistic.WithStatistic(TimeSpan duration)
{
return this.WithStatistic(duration);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain).
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.UpdateDefinition.IWithCondition ScaleRule.UpdateDefinition.IWithStatistic.WithStatistic(TimeSpan duration, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="frequency">The granularity of metrics the rule monitors. Must be one of the predefined values returned from metric definitions for the metric. Must be between 12 hours and 1 minute.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithCondition ScaleRule.Definition.IWithStatistic.WithStatistic(TimeSpan duration, TimeSpan frequency, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, frequency, statisticType);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 10 minutes for duration, 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithCondition ScaleRule.Definition.IWithStatistic.WithStatistic()
{
return this.WithStatistic();
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain) and 'Average' for statistic type.
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithCondition ScaleRule.Definition.IWithStatistic.WithStatistic(TimeSpan duration)
{
return this.WithStatistic(duration);
}
/// <summary>
/// Sets statistics for autoscale trigger action with default values of 1 minute for frequency(time grain).
/// </summary>
/// <param name="duration">The range of time in which instance data is collected. This value must be greater than the delay in metric collection, which can vary from resource-to-resource. Must be between 12 hours and 5 minutes.</param>
/// <param name="statisticType">The metric statistic type. How the metrics from multiple instances are combined. Possible values include: 'Average', 'Min', 'Max', 'Sum'.</param>
/// <return>The next stage of the definition.</return>
ScaleRule.Definition.IWithCondition ScaleRule.Definition.IWithStatistic.WithStatistic(TimeSpan duration, MetricStatisticType statisticType)
{
return this.WithStatistic(duration, statisticType);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.