context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace System.Resources
{
public sealed class ResourceReader : IDisposable
{
private const int ResSetVersion = 2;
private const int ResourceTypeCodeString = 1;
private const int ResourceManagerMagicNumber = unchecked((int)0xBEEFCACE);
private const int ResourceManagerHeaderVersionNumber = 1;
private Stream _stream; // backing store we're reading from.
private long _nameSectionOffset; // Offset to name section of file.
private long _dataSectionOffset; // Offset to Data section of file.
private long _resourceStreamStart; // beginning of the resource stream, which could be part of a longer file stream
private int[] _namePositions; // relative locations of names
private int _stringTypeIndex;
private int _numOfTypes;
private int _numResources; // Num of resources files, in case arrays aren't allocated.
private int _version;
// "System.String, mscorlib" representation in resources stream
private readonly static byte[] s_SystemStringName = EncodeStringName();
public ResourceReader(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
if (!stream.CanSeek)
throw new ArgumentException(SR.Argument_StreamNotSeekable);
_stream = stream;
ReadResources();
}
public void Dispose()
{
Dispose(true);
}
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe void Dispose(bool disposing)
{
if (_stream != null) {
if (disposing) {
Stream stream = _stream;
_stream = null;
if (stream != null) {
stream.Dispose();
}
_namePositions = null;
}
}
}
private void SkipString()
{
int stringLength;
if (!_stream.TryReadInt327BitEncoded(out stringLength) || stringLength < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
_stream.Seek(stringLength, SeekOrigin.Current);
}
private unsafe int GetNamePosition(int index)
{
Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index);
int r;
r = _namePositions[index];
if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesNameInvalidOffset + ":" + r);
}
return r;
}
public IDictionaryEnumerator GetEnumerator()
{
if (_stream == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return new ResourceEnumerator(this);
}
private void SuccessElseEosException(bool condition)
{
if (!condition) {
throw new EndOfStreamException();
}
}
private string GetKeyForNameIndex(int index)
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_stream.Seek(_resourceStreamStart + nameVA + _nameSectionOffset, SeekOrigin.Begin);
var result = _stream.ReadString(utf16: true);
int dataOffset;
SuccessElseEosException(_stream.TryReadInt32(out dataOffset));
if (dataOffset < 0 || dataOffset >= _stream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + " offset :" + dataOffset);
}
return result;
}
}
private string GetValueForNameIndex(int index)
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_stream.Seek(_resourceStreamStart + nameVA + _nameSectionOffset, SeekOrigin.Begin);
SkipString();
int dataPos;
SuccessElseEosException(_stream.TryReadInt32(out dataPos));
if (dataPos < 0 || dataPos >= _stream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + dataPos);
}
try
{
return ReadStringElseNull(dataPos);
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
catch (ArgumentOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
}
//returns null if the resource is not a string
private string ReadStringElseNull(int pos)
{
_stream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex;
if(!_stream.TryReadInt327BitEncoded(out typeIndex)) {
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
}
if (_version == 1) {
if (typeIndex == -1 || !IsString(typeIndex)) {
return null;
}
}
else
{
if (ResourceTypeCodeString != typeIndex) {
return null;
}
}
return _stream.ReadString(utf16 : false);
}
private void ReadResources()
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _ReadResources and wrap here.
_ReadResources();
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof);
}
catch (IndexOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e);
}
}
private void _ReadResources()
{
_resourceStreamStart = _stream.Position;
// Read out the ResourceManager header
// Read out magic number
int magicNum;
SuccessElseEosException(_stream.TryReadInt32(out magicNum));
if (magicNum != ResourceManagerMagicNumber)
throw new ArgumentException(SR.Resources_StreamNotValid);
// Assuming this is ResourceManager header V1 or greater, hopefully
// after the version number there is a number of bytes to skip
// to bypass the rest of the ResMgr header. For V2 or greater, we
// use this to skip to the end of the header
int resMgrHeaderVersion;
SuccessElseEosException(_stream.TryReadInt32(out resMgrHeaderVersion));
//number of bytes to skip over to get past ResMgr header
int numBytesToSkip;
SuccessElseEosException(_stream.TryReadInt32(out numBytesToSkip));
if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
if (resMgrHeaderVersion > 1) {
_stream.Seek(numBytesToSkip, SeekOrigin.Current);
}
else {
// We don't care about numBytesToSkip; read the rest of the header
//Due to legacy : this field is always a variant of System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
//So we Skip the type name for resourcereader unlike Desktop
SkipString();
// Skip over type name for a suitable ResourceSet
SkipString();
}
// Read RuntimeResourceSet header
// Do file version check
SuccessElseEosException(_stream.TryReadInt32(out _version));
if (_version != ResSetVersion && _version != 1) {
throw new ArgumentException(SR.Arg_ResourceFileUnsupportedVersion + "Expected:" + ResSetVersion + "but got:" + _version);
}
// number of resources
SuccessElseEosException(_stream.TryReadInt32(out _numResources));
if (_numResources < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
SuccessElseEosException(_stream.TryReadInt32(out _numOfTypes));
if (_numOfTypes < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// find index of System.String
for (int i = 0; i < _numOfTypes; i++)
{
if(_stream.StartsWith(s_SystemStringName, advance : true)){
_stringTypeIndex = i;
}
}
// Prepare to read in the array of name hashes
// Note that the name hashes array is aligned to 8 bytes so
// we can use pointers into it on 64 bit machines. (4 bytes
// may be sufficient, but let's plan for the future)
// Skip over alignment stuff. All public .resources files
// should be aligned No need to verify the byte values.
long pos = _stream.Position;
int alignBytes = ((int)pos) & 7;
if (alignBytes != 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
{
_stream.ReadByte();
}
}
//Skip over the array of name hashes
for (int i = 0; i < _numResources; i++)
{
int hash;
SuccessElseEosException(_stream.TryReadInt32(out hash));
}
// Read in the array of relative positions for all the names.
_namePositions = new int[_numResources];
for (int i = 0; i < _numResources; i++)
{
int namePosition;
SuccessElseEosException(_stream.TryReadInt32(out namePosition));
if (namePosition < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_namePositions[i] = namePosition;
}
// Read location of data section.
int dataSectionOffset;
SuccessElseEosException(_stream.TryReadInt32(out dataSectionOffset));
if (dataSectionOffset < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_dataSectionOffset = dataSectionOffset;
// Store current location as start of name section
_nameSectionOffset = _stream.Position - _resourceStreamStart;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
if (_dataSectionOffset < _nameSectionOffset)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
}
private bool IsString(int typeIndex)
{
if (typeIndex < 0 || typeIndex >= _numOfTypes)
{
throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
return typeIndex == _stringTypeIndex;
}
private static byte[] EncodeStringName()
{
var type = typeof(string);
var name = type.AssemblyQualifiedName;
int length = name.IndexOf(", Version=");
var buffer = new byte[length + 1];
var encoded = Encoding.UTF8.GetBytes(name, 0, length, buffer, 1);
// all characters should be single byte encoded and the type name shorter than 128 bytes
// this restriction is needed to encode without multiple allocations of the buffer
if (encoded > 127 || encoded != length)
{
throw new NotSupportedException();
}
checked { buffer[0] = (byte)encoded; }
return buffer;
}
internal sealed class ResourceEnumerator : IDictionaryEnumerator
{
private const int ENUM_DONE = int.MinValue;
private const int ENUM_NOT_STARTED = -1;
private ResourceReader _reader;
private bool _currentIsValid;
private int _currentName;
internal ResourceEnumerator(ResourceReader reader)
{
_currentName = ENUM_NOT_STARTED;
_reader = reader;
}
public bool MoveNext()
{
if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE)
{
_currentIsValid = false;
_currentName = ENUM_DONE;
return false;
}
_currentIsValid = true;
_currentName++;
return true;
}
public Object Key
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetKeyForNameIndex(_currentName);
}
}
public Object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
string key = _reader.GetKeyForNameIndex(_currentName);
string value = _reader.GetValueForNameIndex(_currentName);
return new DictionaryEntry(key, value);
}
}
public Object Value
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetValueForNameIndex(_currentName);
}
}
public void Reset()
{
if (_reader._stream == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
_currentIsValid = false;
_currentName = ENUM_NOT_STARTED;
}
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
////////////////////////////////////////////////////////////////
// TestCase TCXML ReadState
//
////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract class TCReadState : TCXMLReaderBaseGeneral
{
public override int Init(object objParam)
{
int ret = base.Init(objParam);
CreateTestFile(EREADER_TYPE.JUNK);
return ret;
}
public override int Terminate(object objParam)
{
// just in case it failed without closing
DataReader.Close();
DeleteTestFile(EREADER_TYPE.JUNK);
return base.Terminate(objParam);
}
[Variation("XmlReader ReadState", Pri = 0)]
public int ReadState1()
{
ReloadSource(EREADER_TYPE.JUNK);
try
{
DataReader.Read();
}
catch (XmlException)
{
CError.WriteLine(DataReader.ReadState);
CError.Compare(DataReader.ReadState, ReadState.Error, "ReadState should be Error");
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, "wrong exception");
}
}
/////////////////////////////////////////////////////////////////////////
// TestCase ReadInnerXml
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract class TCReadInnerXml : TCXMLReaderBaseGeneral
{
public const String ST_ENT_TEXT = "xxx>xxxBxxxDxxx&e1;xxx";
private void VerifyNextNode(XmlNodeType nt, string name, string value)
{
while (DataReader.NodeType == XmlNodeType.Whitespace ||
DataReader.NodeType == XmlNodeType.SignificantWhitespace)
{
// skip all whitespace nodes
// if EOF is reached NodeType=None
DataReader.Read();
}
CError.Compare(DataReader.VerifyNode(nt, name, value), "VerifyNextNode");
}
////////////////////////////////////////////////////////////////
// Variations
////////////////////////////////////////////////////////////////
[Variation("ReadInnerXml on Empty Tag", Pri = 0)]
public int TestReadInnerXml1()
{
bool bPassed = false;
String strExpected = String.Empty;
ReloadSource();
DataReader.PositionOnElement("EMPTY1");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "EMPTY2", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on non Empty Tag", Pri = 0)]
public int TestReadInnerXml2()
{
bool bPassed = false;
String strExpected = String.Empty;
ReloadSource();
DataReader.PositionOnElement("EMPTY2");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "EMPTY3", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on non Empty Tag with text content", Pri = 0)]
public int TestReadInnerXml3()
{
bool bPassed = false;
String strExpected = "ABCDE";
ReloadSource();
DataReader.PositionOnElement("NONEMPTY1");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "NONEMPTY2", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on non Empty Tag with Attribute", Pri = 0)]
public int TestReadInnerXml4()
{
bool bPassed = false;
String strExpected = "1234";
ReloadSource();
DataReader.PositionOnElement("NONEMPTY2");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "ACT2", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on non Empty Tag with text and markup content (mixed content)")]
public int TestReadInnerXml5()
{
bool bPassed = false;
String strExpected;
strExpected = "xxx<MARKUP />yyy";
ReloadSource();
DataReader.PositionOnElement("CHARS2");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "CHARS_ELEM1", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml with multiple Level of elements")]
public int TestReadInnerXml6()
{
bool bPassed = false;
String strExpected;
strExpected = "<ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 />";
ReloadSource();
DataReader.PositionOnElement("SKIP3");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "AFTERSKIP3", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml with multiple Level of elements, text and attributes", Pri = 0)]
public int TestReadInnerXml7()
{
bool bPassed = false;
String strExpected = "<e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1>";
strExpected = strExpected.Replace('\'', '"');
ReloadSource();
DataReader.PositionOnElement("CONTENT");
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "TITLE", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml with with entity references, EntityHandling = ExpandEntities")]
public int TestReadInnerXml8()
{
bool bPassed = false;
String strExpected = ST_EXPAND_ENTITIES3;
if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = ST_EXPAND_ENTITIES2;
ReloadSource();
DataReader.PositionOnElement(ST_ENTTEST_NAME);
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Element, "ENTITY2", String.Empty);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on attribute node", Pri = 0)]
public int TestReadInnerXml9()
{
bool bPassed = false;
String strExpected = "a1value";
ReloadSource();
DataReader.PositionOnElement("ATTRIBUTE2");
bPassed = DataReader.MoveToFirstAttribute();
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Attribute, "a1", strExpected);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on attribute node with entity reference in value", Pri = 0)]
public int TestReadInnerXml10()
{
bool bPassed = false;
string strExpected;
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader())
{
strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES4;
}
else if (IsXmlNodeReader())
{
strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES2;
}
else
{
strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES2;
}
string strExpectedAttValue = ST_ENT1_ATT_EXPAND_ENTITIES;
if (IsXmlTextReader())
strExpectedAttValue = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES;
ReloadSource();
DataReader.PositionOnElement(ST_ENTTEST_NAME);
bPassed = DataReader.MoveToFirstAttribute();
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
VerifyNextNode(XmlNodeType.Attribute, "att1", strExpectedAttValue);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on Text", Pri = 0)]
public int TestReadInnerXml11()
{
XmlNodeType nt;
string name;
string value;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.Text);
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
// save status and compare with Read
nt = DataReader.NodeType;
name = DataReader.Name;
value = DataReader.Value;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.Text);
DataReader.Read();
CError.Compare(DataReader.VerifyNode(nt, name, value), "vn");
return TEST_PASS;
}
[Variation("ReadInnerXml on CDATA")]
public int TestReadInnerXml12()
{
if (IsXsltReader() || IsXPathNavigatorReader())
{
while (FindNodeType(XmlNodeType.CDATA) == TEST_PASS)
return TEST_FAIL;
return TEST_PASS;
}
ReloadSource();
if (FindNodeType(XmlNodeType.CDATA) == TEST_PASS)
{
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadInnerXml on ProcessingInstruction")]
public int TestReadInnerXml13()
{
ReloadSource();
if (FindNodeType(XmlNodeType.ProcessingInstruction) == TEST_PASS)
{
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadInnerXml on Comment")]
public int TestReadInnerXml14()
{
ReloadSource();
if (FindNodeType(XmlNodeType.Comment) == TEST_PASS)
{
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadInnerXml on EndElement")]
public int TestReadInnerXml16()
{
ReloadSource();
if (FindNodeType(XmlNodeType.EndElement) == TEST_PASS)
{
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("ReadInnerXml on XmlDeclaration")]
public int TestReadInnerXml17()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
if (FindNodeType(XmlNodeType.XmlDeclaration) == TEST_PASS)
{
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
return TEST_FAIL;
}
[Variation("Current node after ReadInnerXml on element", Pri = 0)]
public int TestReadInnerXml18()
{
ReloadSource();
DataReader.PositionOnElement("SKIP2");
DataReader.ReadInnerXml();
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "AFTERSKIP2", String.Empty), true, "VN");
return TEST_PASS;
}
[Variation("Current node after ReadInnerXml on element")]
public int TestReadInnerXml19()
{
ReloadSource();
DataReader.PositionOnElement("MARKUP");
CError.Compare(DataReader.ReadInnerXml(), String.Empty, "RIX");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Text, String.Empty, "yyy"), true, "VN");
return TEST_PASS;
}
[Variation("ReadInnerXml with with entity references, EntityHandling = ExpandCharEntites")]
public int TestTextReadInnerXml2()
{
bool bPassed = false;
String strExpected;
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = ST_EXPAND_ENTITIES2;
else
{
if (IsXmlNodeReader())
{
strExpected = ST_EXPAND_ENTITIES3;
}
else
{
strExpected = ST_EXPAND_ENTITIES3;
}
}
ReloadSource();
DataReader.PositionOnElement(ST_ENTTEST_NAME);
bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc);
return BoolToLTMResult(bPassed);
}
[Variation("ReadInnerXml on EntityReference")]
public int TestTextReadInnerXml4()
{
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.EntityReference);
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
[Variation("ReadInnerXml on EndEntity")]
public int TestTextReadInnerXml5()
{
if (IsXmlTextReader() || IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.EntityReference);
CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc);
return TEST_PASS;
}
[Variation("ReadInnerXml on XmlDeclaration attributes")]
public int TestTextReadInnerXml16()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
if (IsBinaryReader())
{
CError.Compare(DataReader.ReadInnerXml(), "utf-8", "inner");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "utf-8"), true, "vn");
}
else
{
CError.Compare(DataReader.ReadInnerXml(), "UTF-8", "inner");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "UTF-8"), true, "vn");
}
return TEST_PASS;
}
[Variation("One large element")]
public int TestTextReadInnerXml18()
{
String strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + "</Name>";
ReloadSourceStr(strxml);
DataReader.Read();
CError.Compare(DataReader.ReadInnerXml(), strp, "rix");
return TEST_PASS;
}
}
/////////////////////////////////////////////////////////////////////////
// TestCase MoveToContent
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCMoveToContent : TCXMLReaderBaseGeneral
{
public const String ST_TEST_NAME1 = "GOTOCONTENT";
public const String ST_TEST_NAME2 = "SKIPCONTENT";
public const String ST_TEST_NAME3 = "MIXCONTENT";
public const String ST_TEST_TEXT = "some text";
public const String ST_TEST_CDATA = "cdata info";
////////////////////////////////////////////////////////////////
// Variations
////////////////////////////////////////////////////////////////
[Variation("MoveToContent on Skip XmlDeclaration", Pri = 0)]
public int TestMoveToContent1()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.XmlDeclaration);
CError.Compare(DataReader.MoveToContent(), XmlNodeType.Element, CurVariation.Desc);
CError.Compare(DataReader.Name, "PLAY", CurVariation.Desc);
return TEST_PASS;
}
[Variation("MoveToContent on Read through All invalid Content Node(PI, Comment and whitespace)", Pri = 0)]
public int TestMoveToContent3()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME2);
CError.Compare(DataReader.MoveToContent(), XmlNodeType.Element, CurVariation.Desc);
CError.Compare(DataReader.Name, ST_TEST_NAME2, "Element name");
DataReader.Read();
CError.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement");
CError.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value");
return TEST_PASS;
}
[Variation("MoveToContent on Attribute", Pri = 0)]
public int TestMoveToContent5()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_NAME1);
PositionOnNodeType(XmlNodeType.Attribute);
CError.Compare(DataReader.MoveToContent(), XmlNodeType.Element, "Move to EndElement");
CError.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value");
return TEST_PASS;
}
public const String ST_ENT1_ELEM_ALL_ENTITIES_TYPE = "xxxBxxxDxxxe1fooxxx";
public const String ST_ATT1_NAME = "att1";
public const String ST_GEN_ENT_NAME = "e1";
public const String ST_GEN_ENT_VALUE = "e1foo";
}
/////////////////////////////////////////////////////////////////////////
// TestCase IsStartElement
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCIsStartElement : TCXMLReaderBaseGeneral
{
private const String ST_TEST_ELEM = "DOCNAMESPACE";
private const String ST_TEST_EMPTY_ELEM = "NOSPACE";
private const String ST_TEST_ELEM_NS = "NAMESPACE1";
private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
[Variation("IsStartElement on Regular Element, no namespace", Pri = 0)]
public int TestIsStartElement1()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
CError.Compare(DataReader.IsStartElement(ST_TEST_ELEM), true, "IsStartElement(n)");
CError.Compare(DataReader.IsStartElement(ST_TEST_ELEM, String.Empty), true, "IsStartElement(n,ns)");
return TEST_PASS;
}
[Variation("IsStartElement on Empty Element, no namespace", Pri = 0)]
public int TestIsStartElement2()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM);
CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM), true, "IsStartElement(n)");
CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM, String.Empty), true, "IsStartElement(n,ns)");
return TEST_PASS;
}
[Variation("IsStartElement on regular Element, with namespace", Pri = 0)]
public int TestIsStartElement3()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
CError.Compare(DataReader.IsStartElement("check", "1"), true, "IsStartElement(n,ns)");
CError.Compare(DataReader.IsStartElement("check", String.Empty), false, "IsStartElement(n)");
CError.Compare(DataReader.IsStartElement("check"), false, "IsStartElement2(n)");
CError.Compare(DataReader.IsStartElement("bar:check"), true, "IsStartElement(qname)");
CError.Compare(DataReader.IsStartElement("bar1:check"), false, "IsStartElement(invalid_qname)");
return TEST_PASS;
}
[Variation("IsStartElement on Empty Tag, with default namespace", Pri = 0)]
public int TestIsStartElement4()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, "14"), true, "IsStartElement(n,ns)");
CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty), false, "IsStartElement(n)");
CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS), true, "IsStartElement2(n)");
return TEST_PASS;
}
[Variation("IsStartElement with Name=String.Empty")]
public int TestIsStartElement5()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
CError.Compare(DataReader.IsStartElement(String.Empty), false, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on Empty Element with Name and Namespace=String.Empty")]
public int TestIsStartElement6()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM);
CError.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on CDATA")]
public int TestIsStartElement7()
{
//XSLT doesn't deal with CDATA
if (IsXsltReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.CDATA);
CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on EndElement, no namespace")]
public int TestIsStartElement8()
{
ReloadSource();
DataReader.PositionOnElement("NONAMESPACE");
PositionOnNodeType(XmlNodeType.EndElement);
CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
CError.Compare(DataReader.IsStartElement("NONAMESPACE"), false, "IsStartElement(n)");
CError.Compare(DataReader.IsStartElement("NONAMESPACE", String.Empty), false, "IsStartElement(n,ns)");
return TEST_PASS;
}
[Variation("IsStartElement on EndElement, with namespace")]
public int TestIsStartElement9()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
PositionOnNodeType(XmlNodeType.EndElement);
CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
CError.Compare(DataReader.IsStartElement("check", "1"), false, "IsStartElement(n,ns)");
CError.Compare(DataReader.IsStartElement("bar:check"), false, "IsStartElement(qname)");
return TEST_PASS;
}
[Variation("IsStartElement on Attribute")]
public int TestIsStartElement10()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.Attribute);
CError.Compare(DataReader.IsStartElement(), true, CurVariation.Desc);
CError.Compare(DataReader.NodeType, XmlNodeType.Element, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on Text")]
public int TestIsStartElement11()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.Text);
CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on ProcessingInstruction")]
public int TestIsStartElement12()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.ProcessingInstruction);
CError.Compare(DataReader.IsStartElement(), IsSubtreeReader() ? false : true, CurVariation.Desc);
CError.Compare(DataReader.NodeType, IsSubtreeReader() ? XmlNodeType.Text : XmlNodeType.Element, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on Comment")]
public int TestIsStartElement13()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.Comment);
CError.Compare(DataReader.IsStartElement(), IsSubtreeReader() ? false : true, CurVariation.Desc);
CError.Compare(DataReader.NodeType, IsSubtreeReader() ? XmlNodeType.Text : XmlNodeType.Element, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on XmlDeclaration")]
public int TestIsStartElement15()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.XmlDeclaration);
CError.Compare(DataReader.IsStartElement(), true, CurVariation.Desc);
CError.Compare(DataReader.NodeType, XmlNodeType.Element, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on EntityReference")]
public int TestTextIsStartElement1()
{
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.EntityReference);
CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc);
return TEST_PASS;
}
[Variation("IsStartElement on EndEntity")]
public int TestTextIsStartElement2()
{
if (IsXsltReader() || IsXmlTextReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.EndEntity);
CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc);
return TEST_PASS;
}
}
/////////////////////////////////////////////////////////////////////////
// TestCase ReadStartElement
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadStartElement : TCXMLReaderBaseGeneral
{
private const String ST_TEST_ELEM = "DOCNAMESPACE";
private const String ST_TEST_EMPTY_ELEM = "NOSPACE";
private const String ST_TEST_ELEM_NS = "NAMESPACE1";
private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
[Variation("ReadStartElement on Regular Element, no namespace", Pri = 0)]
public int TestReadStartElement1()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
DataReader.ReadStartElement();
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
DataReader.ReadStartElement(ST_TEST_ELEM);
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
DataReader.ReadStartElement(ST_TEST_ELEM, String.Empty);
return TEST_PASS;
}
[Variation("ReadStartElement on Empty Element, no namespace", Pri = 0)]
public int TestReadStartElement2()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement();
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM);
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM, String.Empty);
return TEST_PASS;
}
[Variation("ReadStartElement on regular Element, with namespace", Pri = 0)]
public int TestReadStartElement3()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
DataReader.ReadStartElement();
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
DataReader.ReadStartElement("check", "1");
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
DataReader.ReadStartElement("bar:check");
return TEST_PASS;
}
[Variation("Passing ns=String.EmptyErrorCase: ReadStartElement on regular Element, with namespace", Pri = 0)]
public int TestReadStartElement4()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
try
{
DataReader.ReadStartElement("check", String.Empty);
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("Passing no ns: ReadStartElement on regular Element, with namespace", Pri = 0)]
public int TestReadStartElement5()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
try
{
DataReader.ReadStartElement("check");
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement on Empty Tag, with namespace")]
public int TestReadStartElement6()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement();
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, "14");
return TEST_PASS;
}
[Variation("ErrorCase: ReadStartElement on Empty Tag, with namespace, passing ns=String.Empty")]
public int TestReadStartElement7()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty);
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement on Empty Tag, with namespace, passing no ns")]
public int TestReadStartElement8()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS);
return TEST_PASS;
}
[Variation("ReadStartElement with Name=String.Empty")]
public int TestReadStartElement9()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
try
{
DataReader.ReadStartElement(String.Empty);
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement on Empty Element with Name and Namespace=String.Empty")]
public int TestReadStartElement10()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadStartElement(String.Empty, String.Empty);
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement on CDATA")]
public int TestReadStartElement11()
{
//XSLT doesn't deal with CDATA
if (IsXsltReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.CDATA);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement() on EndElement, no namespace")]
public int TestReadStartElement12()
{
ReloadSource();
DataReader.PositionOnElement("NONAMESPACE");
PositionOnNodeType(XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement(n) on EndElement, no namespace")]
public int TestReadStartElement13()
{
ReloadSource();
DataReader.PositionOnElement("NONAMESPACE");
PositionOnNodeType(XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("NONAMESPACE");
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement(n, String.Empty) on EndElement, no namespace")]
public int TestReadStartElement14()
{
ReloadSource();
DataReader.PositionOnElement("NONAMESPACE");
PositionOnNodeType(XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("NONAMESPACE", String.Empty);
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement() on EndElement, with namespace")]
public int TestReadStartElement15()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
PositionOnNodeType(XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadStartElement(n,ns) on EndElement, with namespace")]
public int TestReadStartElement16()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
PositionOnNodeType(XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("check", "1");
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
}
/////////////////////////////////////////////////////////////////////////
// TestCase ReadEndElement
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadEndElement : TCXMLReaderBaseGeneral
{
private const String ST_TEST_ELEM = "DOCNAMESPACE";
private const String ST_TEST_EMPTY_ELEM = "NOSPACE";
private const String ST_TEST_ELEM_NS = "NAMESPACE1";
private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
[Variation("ReadEndElement() on EndElement, no namespace", Pri = 0)]
public int TestReadEndElement1()
{
ReloadSource();
DataReader.PositionOnElement("NONAMESPACE");
PositionOnNodeType(XmlNodeType.EndElement);
DataReader.ReadEndElement();
DataReader.VerifyNode(XmlNodeType.EndElement, "NONAMESPACE", String.Empty);
return TEST_PASS;
}
[Variation("ReadEndElement() on EndElement, with namespace", Pri = 0)]
public int TestReadEndElement2()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
PositionOnNodeType(XmlNodeType.EndElement);
DataReader.ReadEndElement();
DataReader.VerifyNode(XmlNodeType.EndElement, "bar:check", String.Empty);
return TEST_PASS;
}
[Variation("ReadEndElement on Start Element, no namespace")]
public int TestReadEndElement3()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on Empty Element, no namespace", Pri = 0)]
public int TestReadEndElement4()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on regular Element, with namespace", Pri = 0)]
public int TestReadEndElement5()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_ELEM_NS);
DataReader.PositionOnElement("bar:check");
CError.WriteLine(DataReader.NamespaceURI);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on Empty Tag, with namespace", Pri = 0)]
public int TestReadEndElement6()
{
ReloadSource();
DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on CDATA")]
public int TestReadEndElement7()
{
//XSLT doesn't deal with CDATA
if (IsXsltReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.CDATA);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on Text")]
public int TestReadEndElement9()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.Text);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on ProcessingInstruction")]
public int TestReadEndElement10()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.ProcessingInstruction);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on Comment")]
public int TestReadEndElement11()
{
ReloadSource();
PositionOnNodeType(XmlNodeType.Comment);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on XmlDeclaration")]
public int TestReadEndElement13()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.XmlDeclaration);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on EntityReference")]
public int TestTextReadEndElement1()
{
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.EntityReference);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
[Variation("ReadEndElement on EndEntity")]
public int TestTextReadEndElement2()
{
if (IsXsltReader() || IsXmlTextReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
ReloadSource();
PositionOnNodeType(XmlNodeType.EndEntity);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return TEST_PASS;
}
throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION);
}
}
////////////////////////////////////////////////////////////////
// TestCase TCXML MoveToElement
//
////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCMoveToElement : TCXMLReaderBaseGeneral
{
[Variation("Attribute node")]
public int v1()
{
ReloadSource();
DataReader.PositionOnElement("elem2");
DataReader.MoveToAttribute(1);
CError.Compare(DataReader.MoveToElement(), "MTE on elem2 failed");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node");
return TEST_PASS;
}
[Variation("Element node")]
public int v2()
{
ReloadSource();
DataReader.PositionOnElement("elem2");
CError.Compare(!DataReader.MoveToElement(), "MTE on elem2 failed");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node");
return TEST_PASS;
}
[Variation("XmlDeclaration node")]
public int v3()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration);
CError.Compare(!DataReader.MoveToElement(), "MTE on xmldecl failed");
CError.Compare(DataReader.NodeType, XmlNodeType.XmlDeclaration, "xmldecl");
CError.Compare(DataReader.Name, "xml", "Name");
if (IsBinaryReader())
CError.Compare(DataReader.Value, "version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"", "Value");
else
CError.Compare(DataReader.Value, "version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"", "Value");
return TEST_PASS;
}
[Variation("Comment node")]
public int v5()
{
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.Comment);
CError.Compare(!DataReader.MoveToElement(), "MTE on comment failed");
CError.Compare(DataReader.NodeType, XmlNodeType.Comment, "comment");
return TEST_PASS;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="RelationshipDetailsRow.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Xml;
using System.Data.Common;
using System.Globalization;
using System.Data;
using System.Data.Entity.Design.Common;
namespace System.Data.Entity.Design.SsdlGenerator
{
/// <summary>
/// Strongly typed RelationshipDetail row
/// </summary>
internal sealed class RelationshipDetailsRow : System.Data.DataRow
{
private RelationshipDetailsCollection _tableRelationshipDetails;
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
internal RelationshipDetailsRow(System.Data.DataRowBuilder rb)
: base(rb)
{
this._tableRelationshipDetails = ((RelationshipDetailsCollection)(base.Table));
}
/// <summary>
/// Gets a strongly typed table
/// </summary>
public new RelationshipDetailsCollection Table
{
get
{
return _tableRelationshipDetails;
}
}
/// <summary>
/// Gets the PkCatalog column value
/// </summary>
public string PKCatalog
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.PKCatalogColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.PKCatalogColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.PKCatalogColumn] = value;
}
}
/// <summary>
/// Gets the PkSchema column value
/// </summary>
public string PKSchema
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.PKSchemaColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.PKSchemaColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.PKSchemaColumn] = value;
}
}
/// <summary>
/// Gets the PkTable column value
/// </summary>
public string PKTable
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.PKTableColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.PKTableColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.PKTableColumn] = value;
}
}
/// <summary>
/// Gets the PkColumn column value
/// </summary>
public string PKColumn
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.PKColumnColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.PKColumnColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.PKColumnColumn] = value;
}
}
/// <summary>
/// Gets the FkCatalog column value
/// </summary>
public string FKCatalog
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.FKCatalogColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.FKCatalogColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.FKCatalogColumn] = value;
}
}
/// <summary>
/// Gets the FkSchema column value
/// </summary>
public string FKSchema
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.FKSchemaColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.FKSchemaColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.FKSchemaColumn] = value;
}
}
/// <summary>
/// Gets the FkTable column value
/// </summary>
public string FKTable
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.FKTableColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.FKTableColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.FKTableColumn] = value;
}
}
/// <summary>
/// Gets the FkColumn column value
/// </summary>
public string FKColumn
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.FKColumnColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.FKColumnColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.FKColumnColumn] = value;
}
}
/// <summary>
/// Gets the Ordinal column value
/// </summary>
public int Ordinal
{
get
{
try
{
return ((int)(this[this._tableRelationshipDetails.OrdinalColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.OrdinalColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.OrdinalColumn] = value;
}
}
/// <summary>
/// Gets the RelationshipName column value
/// </summary>
public string RelationshipName
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.RelationshipNameColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.RelationshipNameColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.RelationshipNameColumn] = value;
}
}
/// <summary>
/// Gets the RelationshipName column value
/// </summary>
public string RelationshipId
{
get
{
try
{
return ((string)(this[this._tableRelationshipDetails.RelationshipIdColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.RelationshipIdColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.RelationshipIdColumn] = value;
}
}
/// <summary>
/// Gets the IsCascadeDelete column value
/// </summary>
public bool RelationshipIsCascadeDelete
{
get
{
try
{
return ((bool)(this[this._tableRelationshipDetails.RelationshipIsCascadeDeleteColumn]));
}
catch (System.InvalidCastException e)
{
throw EDesignUtil.StonglyTypedAccessToNullValue(_tableRelationshipDetails.RelationshipIsCascadeDeleteColumn.ColumnName, _tableRelationshipDetails.TableName, e);
}
}
set
{
this[this._tableRelationshipDetails.RelationshipIsCascadeDeleteColumn] = value;
}
}
/// <summary>
/// Determines if the PkCatalog column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsPKCatalogNull()
{
return this.IsNull(this._tableRelationshipDetails.PKCatalogColumn);
}
/// <summary>
/// Determines if the PkSchema column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsPKSchemaNull()
{
return this.IsNull(this._tableRelationshipDetails.PKSchemaColumn);
}
/// <summary>
/// Determines if the PkTable column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsPKTableNull()
{
return this.IsNull(this._tableRelationshipDetails.PKTableColumn);
}
/// <summary>
/// Determines if the PkColumn column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsPKColumnNull()
{
return this.IsNull(this._tableRelationshipDetails.PKColumnColumn);
}
/// <summary>
/// Determines if the FkCatalog column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsFKCatalogNull()
{
return this.IsNull(this._tableRelationshipDetails.FKCatalogColumn);
}
/// <summary>
/// Determines if the FkSchema column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsFKSchemaNull()
{
return this.IsNull(this._tableRelationshipDetails.FKSchemaColumn);
}
/// <summary>
/// Determines if the FkTable column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsFKTableNull()
{
return this.IsNull(this._tableRelationshipDetails.FKTableColumn);
}
/// <summary>
/// Determines if the FkColumn column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsFKColumnNull()
{
return this.IsNull(this._tableRelationshipDetails.FKColumnColumn);
}
/// <summary>
/// Determines if the Ordinal column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsOrdinalNull()
{
return this.IsNull(this._tableRelationshipDetails.OrdinalColumn);
}
/// <summary>
/// Determines if the RelationshipName column value is null
/// </summary>
/// <returns>true if the value is null, otherwise false.</returns>
public bool IsRelationshipNameNull()
{
return this.IsNull(this._tableRelationshipDetails.RelationshipNameColumn);
}
}
}
| |
using NUnit.Framework;
using SJP.Schematic.Core;
namespace SJP.Schematic.DataAccess.Tests
{
[TestFixture]
internal static class CamelCaseNameTranslatorTests
{
[Test]
public static void SchemaToNamespace_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.SchemaToNamespace(null), Throws.ArgumentNullException);
}
[Test]
public static void SchemaToNamespace_GivenNullSchema_ReturnsNull()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("test");
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.Null);
}
[Test]
public static void SchemaToNamespace_GivenSpaceSeparatedSchemaName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first second", "test");
const string expected = "firstsecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void SchemaToNamespace_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first_second", "test");
const string expected = "firstSecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void SchemaToNamespace_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("FirstSecond", "test");
const string expected = "firstSecond";
var result = nameTranslator.SchemaToNamespace(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.TableToClassName(null), Throws.ArgumentNullException);
}
[Test]
public static void TableToClassName_GivenSpaceSeparatedLocalName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first second");
const string expected = "firstsecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first_second");
const string expected = "firstSecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void TableToClassName_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("FirstSecond");
const string expected = "firstSecond";
var result = nameTranslator.TableToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenNullName_ThrowsArgumentNullException()
{
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ViewToClassName(null), Throws.ArgumentNullException);
}
[Test]
public static void ViewToClassName_GivenSpaceSeparatedLocalName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first second");
const string expected = "firstsecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("first_second");
const string expected = "firstSecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ViewToClassName_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
var testName = new Identifier("FirstSecond");
const string expected = "firstSecond";
var result = nameTranslator.ViewToClassName(testName);
Assert.That(result, Is.EqualTo(expected));
}
[TestCase((string)null)]
[TestCase("")]
[TestCase(" ")]
public static void ColumnToPropertyName_GivenNullOrWhiteSpaceClassName_ThrowsArgumentNullException(string className)
{
const string columnName = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, columnName), Throws.ArgumentNullException);
}
[TestCase((string)null)]
[TestCase("")]
[TestCase(" ")]
public static void ColumnToPropertyName_GivenNullOrWhiteSpaceColumnName_ThrowsArgumentNullException(string columnName)
{
const string className = "test";
var nameTranslator = new CamelCaseNameTranslator();
Assert.That(() => nameTranslator.ColumnToPropertyName(className, columnName), Throws.ArgumentNullException);
}
[Test]
public static void ColumnToPropertyName_GivenSpaceSeparatedSchemaName_ReturnsSpaceRemovedText()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "test";
const string testName = "first second";
const string expected = "firstsecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenUnderscoreSeparatedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "test";
const string testName = "first_second";
const string expected = "firstSecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenPascalCasedSchemaName_ReturnsCamelCasedText()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "test";
const string testName = "FirstSecond";
const string expected = "firstSecond";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public static void ColumnToPropertyName_GivenTransformedNameMatchingClassName_ReturnsUnderscoreAppendedColumnName()
{
var nameTranslator = new CamelCaseNameTranslator();
const string className = "firstSecond";
const string testName = "FirstSecond";
const string expected = "firstSecond_";
var result = nameTranslator.ColumnToPropertyName(className, testName);
Assert.That(result, Is.EqualTo(expected));
}
}
}
| |
using System;
using System.Collections;
using System.Web;
using NHibernate;
using Castle.Services.Transaction;
using Castle.Facilities.NHibernateIntegration;
using Cuyahoga.Core;
using Cuyahoga.Core.Domain;
using Cuyahoga.Core.Service;
using Cuyahoga.Core.Service.Files;
using Cuyahoga.Modules.Downloads.Domain;
namespace Cuyahoga.Modules.Downloads
{
/// <summary>
/// The Downloads Module provides file downloads for users.
/// </summary>
[Transactional]
public class DownloadsModule : ModuleBase, INHibernateModule
{
private string _physicalDir;
private bool _showPublisher;
private bool _showDateModified;
private bool _showNumberOfDownloads;
private int _currentFileId;
private DownloadsModuleActions _currentAction;
private ISessionManager _sessionManager;
private IFileService _fileService;
#region properties
/// <summary>
/// The physical directory where the files are located.
/// </summary>
/// <remarks>
/// If there is no setting for the physical directory, the default of
/// Application_Root/files is used.
/// </remarks>
public string FileDir
{
get
{
if (this._physicalDir == null)
{
this._physicalDir = HttpContext.Current.Server.MapPath("~/files");
CheckPhysicalDirectory(this._physicalDir);
}
return this._physicalDir;
}
set
{
this._physicalDir = value;
CheckPhysicalDirectory(this._physicalDir);
}
}
/// <summary>
/// The Id of the file that is to be downloaded.
/// </summary>
public int CurrentFileId
{
get { return this._currentFileId; }
}
/// <summary>
/// A specific action that has to be done by the module.
/// </summary>
public DownloadsModuleActions CurrentAction
{
get { return this._currentAction; }
}
/// <summary>
/// Show the name of the user who published the file?
/// </summary>
public bool ShowPublisher
{
get { return this._showPublisher; }
}
/// <summary>
/// Show the date and time when the file was last updated?
/// </summary>
public bool ShowDateModified
{
get { return this._showDateModified; }
}
/// <summary>
/// Show the number of downloads?
/// </summary>
public bool ShowNumberOfDownloads
{
get { return this._showNumberOfDownloads; }
}
#endregion
/// <summary>
/// DownloadsModule constructor.
/// </summary>
/// <param name="fileService">FileService dependency.</param>
/// <param name="sessionManager">NHibernate session manager dependency.</param>
public DownloadsModule(IFileService fileService, ISessionManager sessionManager)
{
this._sessionManager = sessionManager;
this._fileService = fileService;
}
public override void ReadSectionSettings()
{
base.ReadSectionSettings();
// Set dynamic module settings
string physicalDir = Convert.ToString(base.Section.Settings["PHYSICAL_DIR"]);
if (physicalDir != String.Empty)
{
this._physicalDir = physicalDir;
}
this._showPublisher = Convert.ToBoolean(base.Section.Settings["SHOW_PUBLISHER"]);
this._showDateModified = Convert.ToBoolean(base.Section.Settings["SHOW_DATE"]);
this._showNumberOfDownloads = Convert.ToBoolean(base.Section.Settings["SHOW_NUMBER_OF_DOWNLOADS"]);
}
/// <summary>
/// Validate module settings.
/// </summary>
public override void ValidateSectionSettings()
{
// Check if the virtual directory exists.
// We need to do this based on the section setting because it might be possible that the related section
// isn't saved yet.
if (base.Section != null)
{
string physicalDir = Convert.ToString(base.Section.Settings["PHYSICAL_DIR"]);
if (!String.IsNullOrEmpty(physicalDir))
{
CheckPhysicalDirectory(physicalDir);
}
}
base.ValidateSectionSettings();
}
/// <summary>
/// Get the a file as stream.
/// </summary>
/// <returns></returns>
public System.IO.Stream GetFileAsStream(File file)
{
if (file.IsDownloadAllowed(HttpContext.Current.User.Identity))
{
string physicalFilePath = System.IO.Path.Combine(this.FileDir, file.FilePath);
if (System.IO.File.Exists(physicalFilePath))
{
return this._fileService.ReadFile(physicalFilePath);
}
else
{
throw new System.IO.FileNotFoundException("File not found", physicalFilePath);
}
}
else
{
throw new AccessForbiddenException("The current user has no permission to download the file.");
}
}
/// <summary>
/// Retrieve the meta-information of all files that belong to this module.
/// </summary>
/// <returns></returns>
public IList GetAllFiles()
{
ISession session = this._sessionManager.OpenSession();
string hql = "from File f where f.Section.Id = :sectionId order by f.DatePublished desc";
IQuery q = session.CreateQuery(hql);
q.SetInt32("sectionId", base.Section.Id);
try
{
return q.List();
}
catch (Exception ex)
{
throw new Exception("Unable to get Files for section: " + base.Section.Title, ex);
}
}
/// <summary>
/// Get the meta-information of a single file.
/// </summary>
/// <param name="fileId"></param>
/// <returns></returns>
public File GetFileById(int fileId)
{
ISession session = this._sessionManager.OpenSession();
try
{
return (File)session.Load(typeof(File), fileId);
}
catch (Exception ex)
{
throw new Exception("Unable to get File with identifier: " + fileId.ToString(), ex);
}
}
/// <summary>
/// Insert or update the meta-information of a file and update the file contents at the
/// same time in one transaction.
/// </summary>
/// <param name="file"></param>
/// <param name="fileContents"></param>
[Transaction(TransactionMode.RequiresNew)]
public virtual void SaveFile(File file, System.IO.Stream fileContents)
{
// Save physical file.
string physicalFilePath = System.IO.Path.Combine(this.FileDir, file.FilePath);
this._fileService.WriteFile(physicalFilePath, fileContents);
// Save meta-information.
SaveFileInfo(file);
}
/// <summary>
/// Insert or update the meta-information of a file.
/// </summary>
[Transaction(TransactionMode.Requires)]
public virtual void SaveFileInfo(File file)
{
// Obtain current NHibernate session.
ISession session = this._sessionManager.OpenSession();
// Save meta-information
session.SaveOrUpdate(file);
}
/// <summary>
/// Delete a file
/// </summary>
[Transaction(TransactionMode.RequiresNew)]
public virtual void DeleteFile(File file)
{
// Delete physical file.
string physicalFilePath = System.IO.Path.Combine(this.FileDir, file.FilePath);
this._fileService.DeleteFile(physicalFilePath);
// Delete meta information.
ISession session = this._sessionManager.OpenSession();
session.Delete(file);
}
/// <summary>
/// Increase the number of downloads for the given file.
/// </summary>
/// <param name="file"></param>
public virtual void IncreaseNrOfDownloads(File file)
{
ISession session = this._sessionManager.OpenSession();
// First refresh the file to prevent stale updates because downloads can take a little while.
session.Refresh(file);
file.NrOfDownloads++;
SaveFileInfo(file);
}
/// <summary>
/// Parse the pathinfo.
/// </summary>
protected override void ParsePathInfo()
{
base.ParsePathInfo();
if (base.ModuleParams != null)
{
if (base.ModuleParams.Length == 2)
{
// First argument is the module action and the second is the Id of the file.
try
{
this._currentAction = (DownloadsModuleActions)Enum.Parse(typeof(DownloadsModuleActions)
, base.ModuleParams[0], true);
this._currentFileId = Int32.Parse(base.ModuleParams[1]);
}
catch (ArgumentException ex)
{
throw new Exception("Error when parsing module action: " + base.ModuleParams[0], ex);
}
catch (Exception ex)
{
throw new Exception("Error when parsing module parameters: " + base.ModulePathInfo, ex);
}
}
}
}
private void CheckPhysicalDirectory(string physicalDir)
{
// Check existence
if (!System.IO.Directory.Exists(physicalDir))
{
throw new Exception(String.Format("The Downloads module didn't find the physical directory {0} on the server.", physicalDir));
}
// Check if the diretory is writable
if (!this._fileService.CheckIfDirectoryIsWritable(physicalDir))
{
throw new Exception(String.Format("The physical directory {0} is not writable.", physicalDir));
}
}
}
public enum DownloadsModuleActions
{
Download
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Xml.Serialization;
using Rainbow.Framework.Settings.Cache;
// using System.Diagnostics;
namespace Rainbow.Framework.Design
{
/// <summary>
/// The ThemeManager class encapsulates all data logic necessary to
/// use differents themes across the entire portal.
/// Manages the Load and Save of the Themes.
/// Encapsulates a Theme object that contains all the settings
/// of the current Theme.
/// </summary>
public class ThemeManager
{
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
public Theme CurrentTheme = new Theme();
/// <summary>
///
/// </summary>
private string _portalPath;
/// <summary>
/// Initializes a new instance of the <see cref="T:ThemeManager"/> class.
/// </summary>
/// <param name="portalPath">The portal path.</param>
/// <returns>
/// A void value...
/// </returns>
public ThemeManager(string portalPath)
{
_portalPath = portalPath;
}
/// <summary>
/// Clears the cache list.
/// </summary>
public void ClearCacheList()
{
//Clear cache
CurrentCache.Remove(Key.ThemeList(Path));
CurrentCache.Remove(Key.ThemeList(PortalThemePath));
}
/// <summary>
/// Read the Path dir and returns an ArrayList with all the Themes found.
/// Static because the list is Always the same.
/// </summary>
/// <returns></returns>
public static ArrayList GetPublicThemes()
{
ArrayList baseThemeList;
if (!CurrentCache.Exists(Key.ThemeList(Path)))
{
//Initialize array
baseThemeList = new ArrayList();
string[] themes;
// Try to read directories from public theme path
if (Directory.Exists(Path))
{
themes = Directory.GetDirectories(Path);
}
else
{
themes = new string[0];
}
for (int i = 0; i < themes.Length; i++)
{
ThemeItem t = new ThemeItem();
t.Name = themes[i].Substring(Path.Length + 1);
if (t.Name != "CVS" && t.Name != "_svn") //Ignore CVS and _svn folders
baseThemeList.Add(t);
}
CurrentCache.Insert(Key.ThemeList(Path), baseThemeList, new CacheDependency(Path));
}
else
{
baseThemeList = (ArrayList) CurrentCache.Get(Key.ThemeList(Path));
}
return baseThemeList;
}
/// <summary>
/// Read the Path dir and returns
/// an ArrayList with all the Themes found, public and privates
/// </summary>
/// <returns></returns>
public ArrayList GetPrivateThemes()
{
ArrayList privateThemeList;
if (!CurrentCache.Exists(Key.ThemeList(PortalThemePath)))
{
privateThemeList = new ArrayList();
string[] themes;
// Try to read directories from private theme path
if (Directory.Exists(PortalThemePath))
{
themes = Directory.GetDirectories(PortalThemePath);
}
else
{
themes = new string[0];
}
for (int i = 0; i <= themes.GetUpperBound(0); i++)
{
ThemeItem t = new ThemeItem();
t.Name = themes[i].Substring(PortalThemePath.Length + 1);
if (t.Name != "CVS" && t.Name != "_svn") //Ignore CVS
privateThemeList.Add(t);
}
CurrentCache.Insert(Key.ThemeList(PortalThemePath), privateThemeList,
new CacheDependency(PortalThemePath));
//Debug.WriteLine("Storing privateThemeList in Cache: item count is " + privateThemeList.Count.ToString());
}
else
{
privateThemeList = (ArrayList) CurrentCache.Get(Key.ThemeList(PortalThemePath));
//Debug.WriteLine("Retrieving privateThemeList from Cache: item count is " + privateThemeList.Count.ToString());
}
return privateThemeList;
}
/// <summary>
/// Read the Path dir and returns
/// an ArrayList with all the Themes found, public and privates
/// </summary>
/// <returns></returns>
public ArrayList GetThemes()
{
ArrayList themeList;
ArrayList themeListPrivate;
themeList = (ArrayList) GetPublicThemes().Clone();
themeListPrivate = GetPrivateThemes();
themeList.AddRange(themeListPrivate);
return themeList;
}
/// <summary>
/// Loads the specified theme name.
/// </summary>
/// <param name="ThemeName">Name of the theme.</param>
public void Load(string ThemeName)
{
CurrentTheme = new Theme();
CurrentTheme.Name = ThemeName;
//Try loading private theme first
if (LoadTheme(Settings.Path.WebPathCombine(PortalWebPath, ThemeName)))
return;
//Try loading public theme
if (LoadTheme(Settings.Path.WebPathCombine(WebPath, ThemeName)))
return;
//Try default
CurrentTheme.Name = "default";
if (LoadTheme(Settings.Path.WebPathCombine(WebPath, "default")))
return;
string errormsg = General.GetString("LOAD_THEME_ERROR");
throw new FileNotFoundException(errormsg.Replace("%1%", "'" + ThemeName + "'"), WebPath + "/" + ThemeName);
}
/// <summary>
/// Called when [remove].
/// </summary>
/// <param name="key">The key.</param>
/// <param name="cacheItem">The cache item.</param>
/// <param name="reason">The reason.</param>
public static void OnRemove(string key, object cacheItem, CacheItemRemovedReason reason)
{
ErrorHandler.Publish(LogLevel.Info,
"The cached value with key '" + key + "' was removed from the cache. Reason: " +
reason.ToString());
}
/// <summary>
/// Saves the specified theme name.
/// </summary>
/// <param name="ThemeName">Name of the theme.</param>
public void Save(string ThemeName)
{
CurrentTheme.Name = ThemeName;
CurrentTheme.WebPath = Settings.Path.WebPathCombine(WebPath, ThemeName);
XmlSerializer serializer = new XmlSerializer(typeof (Theme));
// Create an XmlTextWriter using a FileStream.
using (Stream fs = new FileStream(CurrentTheme.ThemeFileName, FileMode.Create))
{
XmlWriter writer = new XmlTextWriter(fs, new UTF8Encoding());
// Serialize using the XmlTextWriter.
serializer.Serialize(writer, CurrentTheme);
writer.Close();
//Release the file
writer = null;
}
}
/// <summary>
/// Loads the theme.
/// </summary>
/// <param name="CurrentWebPath">The current web path.</param>
/// <returns>A bool value...</returns>
private bool LoadTheme(string CurrentWebPath)
{
CurrentTheme.WebPath = CurrentWebPath;
//if (!Rainbow.Framework.Settings.Cache.CurrentCache.Exists (Rainbow.Framework.Settings.Cache.Key.CurrentTheme(CurrentWebPath)))
if (!CurrentCache.Exists(Key.CurrentTheme(CurrentTheme.Path)))
{
if (File.Exists(CurrentTheme.ThemeFileName))
{
if (LoadXml(CurrentTheme.ThemeFileName))
{
//Rainbow.Framework.Settings.Cache.CurrentCache.Insert(Rainbow.Framework.Settings.Cache.Key.CurrentTheme(CurrentWebPath), CurrentTheme, new CacheDependency(CurrentTheme.ThemeFileName));
CurrentCache.Insert(Key.CurrentTheme(CurrentTheme.Path), CurrentTheme,
new CacheDependency(CurrentTheme.Path));
}
else
{
// failed
return false;
}
}
else
{
//Return fail
return false;
}
}
else
{
//CurrentTheme = (Theme) Rainbow.Framework.Settings.Cache.CurrentCache.Get (Rainbow.Framework.Settings.Cache.Key.CurrentTheme(CurrentWebPath));
CurrentTheme = (Theme) CurrentCache.Get(Key.CurrentTheme(CurrentTheme.Path));
}
CurrentTheme.WebPath = CurrentWebPath;
return true;
}
/// <summary>
/// Loads the XML.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>A bool value...</returns>
private bool LoadXml(string filename)
{
XmlTextReader _xtr = null;
NameTable _nt = new NameTable();
XmlNamespaceManager _nsm = new XmlNamespaceManager(_nt);
_nsm.AddNamespace(string.Empty, "http://www.w3.org/1999/xhtml");
XmlParserContext _context = new XmlParserContext(_nt, _nsm, string.Empty, XmlSpace.None);
bool returnValue = false;
try
{
// Create an XmlTextReader using a FileStream.
using (Stream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
try
{
_xtr = new XmlTextReader(fs, XmlNodeType.Document, _context);
_xtr.WhitespaceHandling = WhitespaceHandling.None;
ThemeImage _myImage;
ThemePart _myPart = new ThemePart();
while (!_xtr.EOF)
{
if (_xtr.MoveToContent() == XmlNodeType.Element)
{
switch (_xtr.LocalName)
{
case "Name":
CurrentTheme.Name = _xtr.ReadString();
break;
case "Type":
CurrentTheme.Type = _xtr.ReadString();
break;
case "Css":
CurrentTheme.Css = _xtr.ReadString();
break;
case "MinimizeColor":
CurrentTheme.MinimizeColor = _xtr.ReadString();
break;
case "ThemeImage":
_myImage = new ThemeImage();
while (_xtr.MoveToNextAttribute())
{
switch (_xtr.LocalName)
{
case "Name":
_myImage.Name = _xtr.Value;
break;
case "ImageUrl":
_myImage.ImageUrl = _xtr.Value;
break;
case "Width":
_myImage.Width = double.Parse(_xtr.Value);
break;
case "Height":
_myImage.Height = double.Parse(_xtr.Value);
break;
default:
break;
}
}
CurrentTheme.ThemeImages.Add(_myImage.Name, _myImage);
_xtr.MoveToElement();
break;
case "ThemePart":
_myPart = new ThemePart();
while (_xtr.MoveToNextAttribute())
{
switch (_xtr.LocalName)
{
case "Name":
_myPart.Name = _xtr.Value;
break;
default:
break;
}
}
_xtr.MoveToElement();
break;
case "HTML":
if (_myPart.Name.Length != 0)
_myPart.Html = _xtr.ReadString();
//Moved here on load instead on retrival.
//by Manu
string w = string.Concat(CurrentTheme.WebPath, "/");
_myPart.Html = _myPart.Html.Replace("src='", string.Concat("src='", w));
_myPart.Html = _myPart.Html.Replace("src=\"", string.Concat("src=\"", w));
_myPart.Html =
_myPart.Html.Replace("background='", string.Concat("background='", w));
_myPart.Html =
_myPart.Html.Replace("background=\"", string.Concat("background=\"", w));
CurrentTheme.ThemeParts.Add(_myPart.Name, _myPart);
break;
default:
//Debug.WriteLine(" - unwanted");
break;
}
}
_xtr.Read();
}
returnValue = true;
}
catch (Exception ex)
{
ErrorHandler.Publish(LogLevel.Error,
"Failed to Load XML Theme : " + filename + " Message was: " + ex.Message);
}
finally
{
fs.Close();
}
}
}
catch (Exception ex)
{
ErrorHandler.Publish(LogLevel.Error,
"Failed to open XML Theme : " + filename + " Message was: " + ex.Message);
}
return returnValue;
}
/// <summary>
/// The path of the Theme dir (Phisical path)
/// used ot load Themes
/// </summary>
/// <value>The path.</value>
public static string Path
{
get { return (HttpContext.Current.Server.MapPath(WebPath)); }
}
/// <summary>
/// The path of the current portal Theme dir (Phisical path)
/// used to load Themes
/// </summary>
/// <value>The portal theme path.</value>
public string PortalThemePath
{
get { return (HttpContext.Current.Server.MapPath(PortalWebPath)); }
}
/// <summary>
/// The path of the current portal Theme dir (Web side)
/// used to reference images
/// </summary>
/// <value>The portal web path.</value>
public string PortalWebPath
{
get
{
string myPortalWebPath =
Settings.Path.WebPathCombine(Settings.Path.ApplicationRoot, _portalPath, "/Themes");
return myPortalWebPath;
}
}
/// <summary>
/// The path of the Theme dir (Web side)
/// used to reference images
/// </summary>
/// <value>The web path.</value>
public static string WebPath
{
get { return Settings.Path.WebPathCombine(Settings.Path.ApplicationRoot, "/Design/Themes"); }
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.TestingHost;
using TestExtensions;
using TestGrainInterfaces;
using Tests.GeoClusterTests;
using Xunit;
using Xunit.Abstractions;
using Orleans.Hosting;
namespace UnitTests.GeoClusterTests
{
[TestCategory("GeoCluster")]
public class MultiClusterRegistrationTests : TestingClusterHost
{
private string[] ClusterNames;
private ClientWrapper[][] Clients;
private IEnumerable<KeyValuePair<string, ClientWrapper>> EnumerateClients()
{
for (int i = 0; i < ClusterNames.Length; i++)
foreach (var c in Clients[i])
yield return new KeyValuePair<string, ClientWrapper>(ClusterNames[i], c);
}
public MultiClusterRegistrationTests(ITestOutputHelper output) : base(output)
{
}
[SkippableFact]
public async Task TwoClusterBattery()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2));
var testtasks = new List<Task>();
testtasks.Add(RunWithTimeout("Deact", 20000, Deact));
testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls));
testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls));
testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls));
testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification));
testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification));
foreach (var t in testtasks)
await t;
}
[SkippableFact(), TestCategory("Functional")]
public async Task ThreeClusterBattery()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2, 2));
var testtasks = new List<Task>();
testtasks.Add(RunWithTimeout("Deact", 20000, Deact));
testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls));
testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls));
testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls));
testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification));
testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification));
foreach (var t in testtasks)
await t;
}
[SkippableFact]
public async Task FourClusterBattery()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2, 1, 1));
var testtasks = new List<Task>();
for (int i = 0; i < 20; i++)
{
testtasks.Add(RunWithTimeout("Deact", 20000, Deact));
testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls));
testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls));
testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls));
testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification));
testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification));
}
foreach (var t in testtasks)
await t;
}
private Task StartClustersAndClients(params short[] silos)
{
return StartClustersAndClients(null, null, silos);
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddSimpleMessageStreamProvider("SMSProvider");
}
}
private Task StartClustersAndClients(Action<ClusterConfiguration> config_customizer, Action<ClientConfiguration> clientconfig_customizer, params short[] silos)
{
WriteLog("Creating clusters and clients...");
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
random = new Random();
System.Threading.ThreadPool.SetMaxThreads(8, 8);
// configuration for cluster
Action<ClusterConfiguration> addtracing = (ClusterConfiguration c) =>
{
config_customizer?.Invoke(c);
};
// Create clusters and clients
ClusterNames = new string[silos.Length];
Clients = new ClientWrapper[silos.Length][];
for (int i = 0; i < silos.Length; i++)
{
var numsilos = silos[i];
var clustername = ClusterNames[i] = ((char)('A' + i)).ToString();
var c = Clients[i] = new ClientWrapper[numsilos];
NewGeoCluster<SiloConfigurator>(globalserviceid, clustername, silos[i], addtracing);
// create one client per silo
Parallel.For(0, numsilos, paralleloptions, (j) => c[j] = this.NewClient(clustername, j, ClientWrapper.Factory, null, clientBuilder => clientBuilder.AddSimpleMessageStreamProvider("SMSProvider")));
}
WriteLog("Clusters and clients are ready (elapsed = {0})", stopwatch.Elapsed);
// wait for configuration to stabilize
WaitForLivenessToStabilizeAsync().WaitWithThrow(TimeSpan.FromMinutes(1));
Clients[0][0].InjectClusterConfiguration(ClusterNames);
WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
stopwatch.Stop();
WriteLog("Multicluster is ready (elapsed = {0}).", stopwatch.Elapsed);
return Task.CompletedTask;
}
Random random;
public class ClientWrapper : ClientWrapperBase
{
public static readonly Func<string, int, string, Action<ClientConfiguration>, Action<IClientBuilder>, ClientWrapper> Factory =
(name, gwPort, clusterId, configUpdater, clientConfigurator) => new ClientWrapper(name, gwPort, clusterId, configUpdater, clientConfigurator);
public ClientWrapper(string name, int gatewayport, string clusterId, Action<ClientConfiguration> configCustomizer, Action<IClientBuilder> clientConfigurator) : base(name, gatewayport, clusterId, configCustomizer, clientConfigurator)
{
this.systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
public int CallGrain(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Client.Logger().Info("Call Grain {0}", grainRef);
Task<int> toWait = grainRef.SayHelloAsync();
toWait.Wait();
return toWait.GetResult();
}
public string GetRuntimeId(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Client.Logger().Info("GetRuntimeId {0}", grainRef);
Task<string> toWait = grainRef.GetRuntimeId();
toWait.Wait();
return toWait.GetResult();
}
public void Deactivate(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Client.Logger().Info("Deactivate {0}", grainRef);
Task toWait = grainRef.Deactivate();
toWait.GetResult();
}
public void EnableStreamNotifications(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Client.Logger().Info("EnableStreamNotifications {0}", grainRef);
Task toWait = grainRef.EnableStreamNotifications();
toWait.GetResult();
}
// observer-based notification
public void Subscribe(int i, IClusterTestListener listener)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Client.Logger().Info("Create Listener object {0}", grainRef);
listeners.Add(listener);
var obj = this.GrainFactory.CreateObjectReference<IClusterTestListener>(listener).Result;
listeners.Add(obj);
this.Client.Logger().Info("Subscribe {0}", grainRef);
Task toWait = grainRef.Subscribe(obj);
toWait.GetResult();
}
List<IClusterTestListener> listeners = new List<IClusterTestListener>(); // keep them from being GCed
// stream-based notification
public void SubscribeStream(int i, IAsyncObserver<int> listener)
{
IStreamProvider streamProvider = this.Client.GetStreamProvider("SMSProvider");
Guid guid = new Guid(i, 0, 0, new byte[8]);
IAsyncStream<int> stream = streamProvider.GetStream<int>(guid, "notificationtest");
handle = stream.SubscribeAsync(listener).GetResult();
}
StreamSubscriptionHandle<int> handle;
public void InjectClusterConfiguration(string[] clusters, string comment = "", bool checkForLaggingSilos = true)
{
systemManagement.InjectMultiClusterConfiguration(clusters, comment, checkForLaggingSilos).Wait();
}
IManagementGrain systemManagement;
public string GetGrainRef(int i)
{
return this.GrainFactory.GetGrain<IClusterTestGrain>(i).ToString();
}
}
public class ClusterTestListener : MarshalByRefObject, IClusterTestListener, IAsyncObserver<int>
{
public ClusterTestListener(Action<int> oncall)
{
this.oncall = oncall;
}
private Action<int> oncall;
public void GotHello(int number)
{
count++;
oncall(number);
}
public Task OnNextAsync(int item, StreamSequenceToken token = null)
{
GotHello(item);
return Task.CompletedTask;
}
public Task OnCompletedAsync()
{
throw new NotImplementedException();
}
public Task OnErrorAsync(Exception ex)
{
throw new NotImplementedException();
}
public int count;
}
private int Next()
{
lock (random)
return random.Next();
}
private int[] Next(int count)
{
var result = new int[count];
lock (random)
for (int i = 0; i < count; i++)
result[i] = random.Next();
return result;
}
private async Task SequentialCalls()
{
await Task.Yield();
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
var list = EnumerateClients().ToList();
// one call to each silo, in parallel
foreach (var c in list) c.Value.CallGrain(x);
// total number of increments should match
AssertEqual(list.Count() + 1, Clients[0][0].CallGrain(x), gref);
}
private async Task ParallelCalls()
{
await Task.Yield();
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
var list = EnumerateClients().ToList();
// one call to each silo, in parallel
Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x));
// total number of increments should match
AssertEqual(list.Count + 1, Clients[0][0].CallGrain(x), gref);
}
private async Task ManyParallelCalls()
{
await Task.Yield();
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// pick just one client per cluster, use it multiple times
var clients = Clients.Select(a => a[0]).ToList();
// concurrently increment (numupdates) times, distributed over the clients
Parallel.For(0, 20, paralleloptions, i => clients[i % clients.Count].CallGrain(x));
// total number of increments should match
AssertEqual(21, Clients[0][0].CallGrain(x), gref);
}
private async Task Deact()
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// put into cluster A
var id = Clients[0][0].GetRuntimeId(x);
WriteLog("Grain {0} at {1}", gref, id);
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id);
// ensure presence in all caches
var list = EnumerateClients().ToList();
Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x));
Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x));
AssertEqual(2* list.Count() + 1, Clients[0][0].CallGrain(x), gref);
WriteLog("Grain {0} deactivating.", gref);
//deactivate
Clients[0][0].Deactivate(x);
// wait for deactivation to complete
await Task.Delay(5000);
WriteLog("Grain {0} reactivating.", gref);
// activate anew in cluster B
var val = Clients[1][0].CallGrain(x);
AssertEqual(1, val, gref);
var newid = Clients[1][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]);
Assert.Contains(Clusters[ClusterNames[1]].Silos, silo => silo.SiloAddress.ToString() == newid);
WriteLog("Grain {0} Check that other clusters find new activation.", gref);
for (int i = 2; i < Clusters.Count; i++)
{
var idd = Clients[i][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, idd, ClusterNames[i]);
AssertEqual(newid, idd, gref);
}
}
private async Task ObserverBasedClientNotification()
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
Clients[0][0].GetRuntimeId(x);
WriteLog("{0} created grain", gref);
var promises = new List<Task<int>>();
// create an observer on each client
Parallel.For(0, Clients.Length, paralleloptions, i =>
{
for (int jj = 0; jj < Clients[i].Length; jj++)
{
int j = jj;
var promise = new TaskCompletionSource<int>();
var listener = new ClusterTestListener((num) =>
{
WriteLog("{3} observedcall {2} on Client[{0}][{1}]", i, j, num, gref);
promise.TrySetResult(num);
});
lock(promises)
promises.Add(promise.Task);
Clients[i][j].Subscribe(x, listener);
WriteLog("{2} subscribed to Client[{0}][{1}]", i, j, gref);
}
});
// call the grain
Clients[0][0].CallGrain(x);
await Task.WhenAll(promises);
var sortedresults = promises.Select(p => p.Result).OrderBy(num => num).ToArray();
// each client should get its own notification
for (int i = 0; i < sortedresults.Length; i++)
AssertEqual(sortedresults[i], i, gref);
}
private async Task StreamBasedClientNotification()
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
Clients[0][0].EnableStreamNotifications(x);
WriteLog("{0} created grain", gref);
var promises = new List<Task<int>>();
// create an observer on each client
Parallel.For(0, Clients.Length, paralleloptions, i =>
{
for (int jj = 0; jj < Clients[i].Length; jj++)
{
int j = jj;
var promise = new TaskCompletionSource<int>();
var listener = new ClusterTestListener((num) =>
{
WriteLog("{3} observedcall {2} on Client[{0}][{1}]", i, j, num, gref);
promise.TrySetResult(num);
});
lock (promises)
promises.Add(promise.Task);
Clients[i][j].SubscribeStream(x, listener);
WriteLog("{2} subscribed to Client[{0}][{1}]", i, j, gref);
}
});
// call the grain
Clients[0][0].CallGrain(x);
await Task.WhenAll(promises);
// each client should get same value
foreach (var p in promises)
AssertEqual(1, p.Result, gref);
}
[SkippableFact, TestCategory("Functional")]
public async Task BlockedDeact()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () =>
{
Action<ClusterConfiguration> c =
(cc) => { cc.Globals.DirectoryLazyDeregistrationDelay = TimeSpan.FromSeconds(5); };
return StartClustersAndClients(c, null, 2, 2);
});
await RunWithTimeout("BlockedDeact", 10 * 1000, async () =>
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// put into cluster A and access from cluster B
var id = Clients[0][0].GetRuntimeId(x);
WriteLog("Grain {0} at {1}", gref, id);
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id);
var id2 = Clients[1][0].GetRuntimeId(x);
AssertEqual(id2, id, gref);
// deactivate grain in cluster A, but block deactivation message to cluster B
WriteLog("Grain {0} deactivating.", gref);
BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]);
Clients[0][0].Deactivate(x);
await Task.Delay(5000);
UnblockAllClusterCommunication(ClusterNames[0]);
// reactivate in cluster B. This should cause unregistration to be sent
WriteLog("Grain {0} reactivating.", gref);
// activate anew in cluster B
var val = Clients[1][0].CallGrain(x);
AssertEqual(1, val, gref);
var newid = Clients[1][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]);
Assert.Contains(newid, Clusters[ClusterNames[1]].Silos.Select(s => s.SiloAddress.ToString()));
// connect from cluster A
val = Clients[0][0].CallGrain(x);
AssertEqual(2, val, gref);
});
}
[SkippableFact, TestCategory("Functional")]
public async Task CacheCleanup()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () =>
{
Action<ClusterConfiguration> c =
(cc) => {
};
return StartClustersAndClients(c, null, 1, 1);
});
await RunWithTimeout("CacheCleanup", 1000000, async () =>
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// put grain into cluster A
var id = Clients[0][0].GetRuntimeId(x);
WriteLog("Grain {0} at {1}", gref, id);
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id);
// access the grain from B, causing
// causing entry to be installed in B's directory and/or B's directory caches
var id2 = Clients[1][0].GetRuntimeId(x);
AssertEqual(id2, id, gref);
// block communication from A to B
BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]);
// change multi-cluster configuration to be only { B }, i.e. exclude A
WriteLog($"Removing A from multi-cluster");
Clients[1][0].InjectClusterConfiguration(new string[] { ClusterNames[1] }, "exclude A", false);
WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
// give the cache cleanup process time to remove all cached references in B
await Task.Delay(40000);
// now try to access the grain from cluster B
// if everything works correctly this should succeed, creating a new instances on B locally
// (if invalid caches were not removed this times out)
WriteLog("Grain {0} doubly-activating.", gref);
var val = Clients[1][0].CallGrain(x);
AssertEqual(1, val, gref);
var newid = Clients[1][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]);
Assert.Contains(newid, Clusters[ClusterNames[1]].Silos.Select(s => s.SiloAddress.ToString()));
});
}
[SkippableFact, TestCategory("Functional")]
public async Task CacheCleanupMultiple()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () =>
{
Action<ClusterConfiguration> c =
(cc) => {
};
return StartClustersAndClients(c, null, 3, 3);
});
await RunWithTimeout("CacheCleanupMultiple", 1000000, async () =>
{
int count = 100;
var grains = Next(count);
var grefs = grains.Select((x) => Clients[0][0].GetGrainRef(x)).ToList();
// put grains into cluster A
var ids = grains.Select((x,i) => Clients[0][i % 3].GetRuntimeId(x)).ToList();
WriteLog($"{count} Grains activated on A");
for (int i = 0; i < count; i++ )
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == ids[i]);
// access all the grains living in A from all the clients of B
// causing entries to be installed in B's directory and in B's directory caches
for (int j = 0; j < 3; j++)
{
var ids2 = grains.Select((x) => Clients[1][j].GetRuntimeId(x)).ToList();
for (int i = 0; i < count; i++)
AssertEqual(ids2[i], ids[i], grefs[i]);
}
WriteLog($"{count} Grain references cached in B");
// block communication from A to B
BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]);
// change multi-cluster configuration to be only { B }, i.e. exclude A
WriteLog($"Removing A from multi-cluster");
Clients[1][0].InjectClusterConfiguration(new string[] { ClusterNames[1] }, "exclude A", false);
WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
// give the cache cleanup process time to remove all cached references in B
await Task.Delay(50000);
// call the grains from random clients of B
// if everything works correctly this should succeed, creating new instances on B locally
// (if invalid caches were not removed this times out)
var vals = grains.Select((x) => Clients[1][Math.Abs(x) % 3].CallGrain(x)).ToList();
for (int i = 0; i < count; i++)
AssertEqual(1, vals[i], grefs[i]);
// check the placement of the new grains, from client 0
var newids = grains.Select((x) => Clients[1][0].GetRuntimeId(x)).ToList();
for (int i = 0; i < count; i++)
Assert.Contains(newids[i], Clusters[ClusterNames[1]].Silos.Select(s => s.SiloAddress.ToString()));
// check the placement of these same grains, from other clients
for (int j = 1; j < 3; j++)
{
var ids2 = grains.Select((x) => Clients[1][j].GetRuntimeId(x)).ToList();
for (int i = 0; i < count; i++)
AssertEqual(ids2[i], newids[i], grefs[i]);
}
});
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Basic point graph.
* \ingroup graphs
* The point graph is the most basic graph structure, it consists of a number of interconnected points in space called nodes or waypoints.\n
* The point graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node.
* If #recursive is enabled, it will also search the child objects of the children recursively.
* It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large (#maxDistance)
* and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named #limits,
* is useful because usually an AI cannot climb very high, but linking nodes far away from each other,
* but on the same Y level should still be possible. #limits and #maxDistance are treated as being set to infinity if they are set to 0 (zero). \n
* Lastly it will check if there are any obstructions between the nodes using
* <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.\n
* One thing to think about when using raycasting is to either place the nodes a small
* distance above the ground in your scene or to make sure that the ground is not in the raycast \a mask to avoid the raycast from hitting the ground.\n
*
* Alternatively, a tag can be used to search for nodes.
* \see http://docs.unity3d.com/Manual/Tags.html
*
* For larger graphs, it can take quite some time to scan the graph with the default settings.
* If you have the pro version you can enable 'optimizeForSparseGraph' which will in most cases reduce the calculation times
* drastically.
*
* \note Does not support linecast because of obvious reasons.
*
* \shadowimage{pointgraph_graph.png}
* \shadowimage{pointgraph_inspector.png}
*
*/
[JsonOptIn]
public class PointGraph : NavGraph {
/** Childs of this transform are treated as nodes */
[JsonMember]
public Transform root;
/** If no #root is set, all nodes with the tag is used as nodes */
[JsonMember]
public string searchTag;
/** Max distance for a connection to be valid.
* The value 0 (zero) will be read as infinity and thus all nodes not restricted by
* other constraints will be added as connections.
*
* A negative value will disable any neighbours to be added.
* It will completely stop the connection processing to be done, so it can save you processing
* power if you don't these connections.
*/
[JsonMember]
public float maxDistance;
/** Max distance along the axis for a connection to be valid. 0 = infinity */
[JsonMember]
public Vector3 limits;
/** Use raycasts to check connections */
[JsonMember]
public bool raycast = true;
/** Use the 2D Physics API */
[JsonMember]
public bool use2DPhysics;
/** Use thick raycast */
[JsonMember]
public bool thickRaycast;
/** Thick raycast radius */
[JsonMember]
public float thickRaycastRadius = 1;
/** Recursively search for child nodes to the #root */
[JsonMember]
public bool recursive = true;
/** Layer mask to use for raycast */
[JsonMember]
public LayerMask mask;
/** All nodes in this graph.
* Note that only the first #nodeCount will be non-null.
*
* You can also use the GetNodes method to get all nodes.
*/
public PointNode[] nodes;
/** Number of nodes in this graph */
public int nodeCount { get; private set; }
public override int CountNodes () {
return nodeCount;
}
public override void GetNodes (System.Action<GraphNode> action) {
if (nodes == null) return;
var count = nodeCount;
for (int i = 0; i < count; i++) action(nodes[i]);
}
public override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearestForce(position, null);
}
public override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint) {
if (nodes == null) return new NNInfoInternal();
float maxDistSqr = constraint == null || constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
var nnInfo = new NNInfoInternal(null);
float minDist = float.PositiveInfinity;
float minConstDist = float.PositiveInfinity;
for (int i = 0; i < nodeCount; i++) {
PointNode node = nodes[i];
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
nnInfo.node = node;
}
if (dist < minConstDist && dist < maxDistSqr && (constraint == null || constraint.Suitable(node))) {
minConstDist = dist;
nnInfo.constrainedNode = node;
}
}
nnInfo.UpdateInfo();
return nnInfo;
}
/** Add a node to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \note This needs to be called when it is safe to update nodes, which is
* - when scanning
* - during a graph update
* - inside a callback registered using AstarPath.RegisterSafeUpdate
*/
public PointNode AddNode (Int3 position) {
return AddNode(new PointNode(active), position);
}
/** Add a node with the specified type to the graph at the specified position.
*
* \param node This must be a node created using T(AstarPath.active) right before the call to this method.
* The node parameter is only there because there is no new(AstarPath) constraint on
* generic type parameters.
* \param position The node will be set to this position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \note This needs to be called when it is safe to update nodes, which is
* - when scanning
* - during a graph update
* - inside a callback registered using AstarPath.RegisterSafeUpdate
*
* \see AstarPath.RegisterSafeUpdate
*/
public T AddNode<T>(T node, Int3 position) where T : PointNode {
if (nodes == null || nodeCount == nodes.Length) {
var newNodes = new PointNode[nodes != null ? System.Math.Max(nodes.Length+4, nodes.Length*2) : 4];
for (int i = 0; i < nodeCount; i++) newNodes[i] = nodes[i];
nodes = newNodes;
}
node.SetPosition(position);
node.GraphIndex = graphIndex;
node.Walkable = true;
nodes[nodeCount] = node;
nodeCount++;
AddToLookup(node);
return node;
}
/** Recursively counds children of a transform */
protected static int CountChildren (Transform tr) {
int c = 0;
foreach (Transform child in tr) {
c++;
c += CountChildren(child);
}
return c;
}
/** Recursively adds childrens of a transform as nodes */
protected void AddChildren (ref int c, Transform tr) {
foreach (Transform child in tr) {
nodes[c].SetPosition((Int3)child.position);
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
AddChildren(ref c, child);
}
}
/** Rebuilds the lookup structure for nodes.
*
* This is used when #optimizeForSparseGraph is enabled.
*
* You should call this method every time you move a node in the graph manually and
* you are using #optimizeForSparseGraph, otherwise pathfinding might not work correctly.
*
* \astarpro
*/
public void RebuildNodeLookup () {
// A* Pathfinding Project Pro Only
}
void AddToLookup (PointNode node) {
// A* Pathfinding Project Pro Only
}
public override IEnumerable<Progress> ScanInternal () {
yield return new Progress(0, "Searching for GameObjects");
if (root == null) {
//If there is no root object, try to find nodes with the specified tag instead
GameObject[] gos = searchTag != null ? GameObject.FindGameObjectsWithTag(searchTag) : null;
if (gos == null) {
nodes = new PointNode[0];
nodeCount = 0;
yield break;
}
yield return new Progress(0.1f, "Creating nodes");
//Create and set up the found nodes
nodes = new PointNode[gos.Length];
nodeCount = nodes.Length;
for (int i = 0; i < nodes.Length; i++) nodes[i] = new PointNode(active);
for (int i = 0; i < gos.Length; i++) {
nodes[i].SetPosition((Int3)gos[i].transform.position);
nodes[i].Walkable = true;
nodes[i].gameObject = gos[i].gameObject;
}
} else {
//Search the root for children and create nodes for them
if (!recursive) {
nodes = new PointNode[root.childCount];
nodeCount = nodes.Length;
for (int i = 0; i < nodes.Length; i++) nodes[i] = new PointNode(active);
int c = 0;
foreach (Transform child in root) {
nodes[c].SetPosition((Int3)child.position);
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
}
} else {
nodes = new PointNode[CountChildren(root)];
nodeCount = nodes.Length;
for (int i = 0; i < nodes.Length; i++) nodes[i] = new PointNode(active);
int startID = 0;
AddChildren(ref startID, root);
}
}
if (maxDistance >= 0) {
// To avoid too many allocations, these lists are reused for each node
var connections = new List<Connection>();
// Max possible squared length of a connection between two nodes
// This is used to speed up the calculations by skipping a lot of nodes that do not need to be checked
long maxPossibleSqrRange;
if (maxDistance == 0 && (limits.x == 0 || limits.y == 0 || limits.z == 0)) {
maxPossibleSqrRange = long.MaxValue;
} else {
maxPossibleSqrRange = (long)(Mathf.Max(limits.x, Mathf.Max(limits.y, Mathf.Max(limits.z, maxDistance))) * Int3.Precision) + 1;
maxPossibleSqrRange *= maxPossibleSqrRange;
}
// Report progress every N nodes
const int YieldEveryNNodes = 512;
// Loop through all nodes and add connections to other nodes
for (int i = 0; i < nodes.Length; i++) {
if (i % YieldEveryNNodes == 0) {
yield return new Progress(Mathf.Lerp(0.15f, 1, i/(float) nodes.Length), "Connecting nodes");
}
connections.Clear();
PointNode node = nodes[i];
// Only brute force is available in the free version
for (int j = 0; j < nodes.Length; j++) {
if (i == j) continue;
PointNode other = nodes[j];
float dist;
if (IsValidConnection(node, other, out dist)) {
connections.Add(new Connection {
node = other,
/** \todo Is this equal to .costMagnitude */
cost = (uint)Mathf.RoundToInt(dist*Int3.FloatPrecision)
});
}
}
node.connections = connections.ToArray();
}
}
}
/** Returns if the connection between \a a and \a b is valid.
* Checks for obstructions using raycasts (if enabled) and checks for height differences.\n
* As a bonus, it outputs the distance between the nodes too if the connection is valid.
*
* \note This is not the same as checking if node a is connected to node b.
* That should be done using a.ContainsConnection(b)
*/
public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) {
dist = 0;
if (!a.Walkable || !b.Walkable) return false;
var dir = (Vector3)(b.position-a.position);
if (
(!Mathf.Approximately(limits.x, 0) && Mathf.Abs(dir.x) > limits.x) ||
(!Mathf.Approximately(limits.y, 0) && Mathf.Abs(dir.y) > limits.y) ||
(!Mathf.Approximately(limits.z, 0) && Mathf.Abs(dir.z) > limits.z)) {
return false;
}
dist = dir.magnitude;
if (maxDistance == 0 || dist < maxDistance) {
if (raycast) {
var ray = new Ray((Vector3)a.position, dir);
var invertRay = new Ray((Vector3)b.position, -dir);
if (use2DPhysics) {
if (thickRaycast) {
return !Physics2D.CircleCast(ray.origin, thickRaycastRadius, ray.direction, dist, mask) && !Physics2D.CircleCast(invertRay.origin, thickRaycastRadius, invertRay.direction, dist, mask);
} else {
return !Physics2D.Linecast((Vector2)(Vector3)a.position, (Vector2)(Vector3)b.position, mask) && !Physics2D.Linecast((Vector2)(Vector3)b.position, (Vector2)(Vector3)a.position, mask);
}
} else {
if (thickRaycast) {
return !Physics.SphereCast(ray, thickRaycastRadius, dist, mask) && !Physics.SphereCast(invertRay, thickRaycastRadius, dist, mask);
} else {
return !Physics.Linecast((Vector3)a.position, (Vector3)b.position, mask) && !Physics.Linecast((Vector3)b.position, (Vector3)a.position, mask);
}
}
} else {
return true;
}
}
return false;
}
#if UNITY_EDITOR
public override void OnDrawGizmos (Pathfinding.Util.RetainedGizmos gizmos, bool drawNodes) {
base.OnDrawGizmos(gizmos, drawNodes);
if (!drawNodes) return;
Gizmos.color = new Color(0.161f, 0.341f, 1f, 0.5f);
if (root != null) {
DrawChildren(this, root);
} else if (!string.IsNullOrEmpty(searchTag)) {
GameObject[] gos = GameObject.FindGameObjectsWithTag(searchTag);
for (int i = 0; i < gos.Length; i++) {
Gizmos.DrawCube(gos[i].transform.position, Vector3.one*UnityEditor.HandleUtility.GetHandleSize(gos[i].transform.position)*0.1F);
}
}
}
static void DrawChildren (PointGraph graph, Transform tr) {
foreach (Transform child in tr) {
Gizmos.DrawCube(child.position, Vector3.one*UnityEditor.HandleUtility.GetHandleSize(child.position)*0.1F);
if (graph.recursive) DrawChildren(graph, child);
}
}
#endif
public override void PostDeserialization () {
RebuildNodeLookup();
}
public override void RelocateNodes (Matrix4x4 deltaMatrix) {
base.RelocateNodes(deltaMatrix);
RebuildNodeLookup();
}
public override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) {
base.DeserializeSettingsCompatibility(ctx);
root = ctx.DeserializeUnityObject() as Transform;
searchTag = ctx.reader.ReadString();
maxDistance = ctx.reader.ReadSingle();
limits = ctx.DeserializeVector3();
raycast = ctx.reader.ReadBoolean();
use2DPhysics = ctx.reader.ReadBoolean();
thickRaycast = ctx.reader.ReadBoolean();
thickRaycastRadius = ctx.reader.ReadSingle();
recursive = ctx.reader.ReadBoolean();
ctx.reader.ReadBoolean(); // Deprecated field
mask = (LayerMask)ctx.reader.ReadInt32();
}
public override void SerializeExtraInfo (GraphSerializationContext ctx) {
// Serialize node data
if (nodes == null) ctx.writer.Write(-1);
// Length prefixed array of nodes
ctx.writer.Write(nodeCount);
for (int i = 0; i < nodeCount; i++) {
// -1 indicates a null field
if (nodes[i] == null) ctx.writer.Write(-1);
else {
ctx.writer.Write(0);
nodes[i].SerializeNode(ctx);
}
}
}
public override void DeserializeExtraInfo (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
nodes = null;
return;
}
nodes = new PointNode[count];
nodeCount = count;
for (int i = 0; i < nodes.Length; i++) {
if (ctx.reader.ReadInt32() == -1) continue;
nodes[i] = new PointNode(active);
nodes[i].DeserializeNode(ctx);
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedAdapter
{
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Protocols.TestSuites.Common;
/// <summary>
/// A class is used to construct the body of the request message.
/// </summary>
public class RequestMessageBodyWriter : BodyWriter
{
/// <summary>
/// Specify the request of envelop body which will be send to the server.
/// </summary>
private EnvelopeBody requestEnvelope;
/// <summary>
/// Initializes a new instance of the RequestMessageBodyWriter class with the specified version and minor version type number.
/// </summary>
/// <param name="version">Specify the version type number.</param>
/// <param name="minorVersion">Specify the minor version type number.</param>
public RequestMessageBodyWriter(ushort? version, ushort? minorVersion)
: base(true)
{
this.CreateEnvelopeBody(version, minorVersion);
}
/// <summary>
/// Gets the message body XML.
/// </summary>
public XmlElement MessageBodyXml
{
get
{
MemoryStream ms = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(EnvelopeBody));
serializer.Serialize(ms, this.requestEnvelope);
XmlDocument doc = new XmlDocument();
doc.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray(), 0, ms.ToArray().Length));
ms.Dispose();
return doc.DocumentElement;
}
}
/// <summary>
/// This method is used to add a request to the request collection in the request envelope body.
/// </summary>
/// <param name="url">Specify the URL of the file to edit.</param>
/// <param name="subRequests">Specify the sub request array.</param>
/// <param name="requestToken">Specify the token which uniquely identify the request.</param>
/// <param name="interval">Specify a nonnegative integer in seconds, which the protocol client will repeat this request.</param>
/// <param name="metaData">Specify a 32-bit value that specifies information about the scenario and urgency of the request.</param>
/// <param name="lastModifiedTime">Specify the last modified time, which is expressed as a tick count.</param>
/// <param name="parentFolderResourceID">If UseResourceID is true, this parameter tells the host to create a file in the given folder ResourceID, regardless of the request URL value.</param>
/// <param name="shouldReturnDisambiguatedFileName">If an upload request fails with a coherency failure, this flag specifies whether the host should return a suggested/available file name that the client can try instead</param>
/// <param name="resourceID">Specify the invariant ResourceID for a file that uniquely identifies the file whose response is being generated</param>
/// <param name="useResourceID">Specify if the protocol server MAY perform ResourceID specific behavior for the file whose contents or metadata contents are requested for uploading to the server or downloading from the server. </param>
public void AddRequest(string url, SubRequestType[] subRequests, string requestToken, uint? interval, int? metaData,
string lastModifiedTime = null,
string parentFolderResourceID = null,
bool? shouldReturnDisambiguatedFileName = null,
string resourceID = null,
bool? useResourceID = null)
{
Request request = new Request();
request.RequestToken = requestToken;
request.Url = url;
request.Interval = interval == null ? null : interval.Value.ToString();
request.MetaData = metaData == null ? null : metaData.Value.ToString();
request.ParentFolderResourceID = parentFolderResourceID;
request.ResourceID = resourceID;
if (shouldReturnDisambiguatedFileName != null)
{
request.ShouldReturnDisambiguatedFileName = (bool)shouldReturnDisambiguatedFileName;
request.ShouldReturnDisambiguatedFileNameSpecified = true;
}
if (useResourceID != null)
{
request.UseResourceID = useResourceID.ToString();
}
int index = 0;
if (subRequests != null)
{
request.SubRequest = new SubRequestElementGenericType[subRequests.Length];
foreach (SubRequestType item in subRequests)
{
if (item != null)
{
int temp = index;
request.SubRequest[temp] = FsshttpConverter.ConvertSubRequestToGenericType<SubRequestElementGenericType>(item);
if (!string.IsNullOrEmpty(lastModifiedTime))
{
if (request.SubRequest[temp].SubRequestData == null)
{
request.SubRequest[temp].SubRequestData = new SubRequestDataGenericType();
}
request.SubRequest[temp].SubRequestData.LastModifiedTime = lastModifiedTime;
}
index++;
}
}
}
else
{
throw new System.ArgumentException("subRequests parameter in FSSHTTPMessageBodyWriter::AddRequest cannot be null.");
}
List<Request> requestList = this.requestEnvelope.RequestCollection.Request == null ? new List<Request>(1) : new List<Request>(this.requestEnvelope.RequestCollection.Request);
requestList.Add(request);
this.requestEnvelope.RequestCollection.Request = requestList.ToArray();
}
/// <summary>
/// Override the method to write the content to the XML dictionary writer.
/// </summary>
/// <param name="writer">Specify the output destination of the content.</param>
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
MemoryStream ms = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(typeof(EnvelopeBody));
serializer.Serialize(ms, this.requestEnvelope);
XmlDocument doc = new XmlDocument();
doc.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray(), 0, ms.ToArray().Length));
ms.Dispose();
foreach (XmlNode node in doc.LastChild.ChildNodes)
{
if (node.Name == "RequestVersion")
{
writer.WriteRaw(node.OuterXml);
}
else if (node.Name == "RequestCollection")
{
this.WriteNode(node, writer);
}
else
{
throw new InvalidOperationException(string.Format("this element [{0}] is not expected element", node.Name));
}
}
}
/// <summary>
/// This method is used to write a XML node to a XML writer.
/// </summary>
/// <param name="node">Specify the XML node.</param>
/// <param name="writer">Specify the XML writer.</param>
private void WriteNode(XmlNode node, XmlDictionaryWriter writer)
{
writer.WriteStartElement(node.Name);
foreach (XmlAttribute xmlAttribute in node.Attributes)
{
writer.WriteAttributeString(xmlAttribute.Name, xmlAttribute.Value);
if (!string.IsNullOrEmpty(xmlAttribute.Prefix))
{
writer.WriteXmlnsAttribute(xmlAttribute.Prefix, xmlAttribute.NamespaceURI);
}
}
if (node.Name == "SubRequestData")
{
string base64 = node.InnerText;
byte[] bytes = Convert.FromBase64String(base64);
writer.WriteBase64(bytes, 0, bytes.Length);
}
else
{
foreach (XmlNode childNode in node.ChildNodes)
{
this.WriteNode(childNode, writer);
}
}
writer.WriteEndElement();
}
/// <summary>
/// This method is used to create request envelope message body, but not include the RequestCollection.
/// </summary>
/// <param name="versionTypeNumber">Specify the version type number.</param>
/// <param name="minorVersionTypeNumber">Specify the minor version type number.</param>
private void CreateEnvelopeBody(ushort? versionTypeNumber, ushort? minorVersionTypeNumber)
{
this.requestEnvelope = new EnvelopeBody();
this.requestEnvelope.RequestVersion = this.CreateRequestVersion(versionTypeNumber, minorVersionTypeNumber);
this.requestEnvelope.RequestCollection = new RequestCollection();
this.requestEnvelope.RequestCollection.CorrelationId = Guid.NewGuid().ToString();
}
/// <summary>
/// This method is used to create the VersionType instance using the specified version type number and minor version type number
/// </summary>
/// <param name="versionTypeNumber">Specify the version type number, which can only be 2.</param>
/// <param name="minorVersionTypeNumber">Specify the minor version type number, which could be 0 or 2.</param>
/// <returns>Returns the VersionType instance.</returns>
private VersionType CreateRequestVersion(ushort? versionTypeNumber, ushort? minorVersionTypeNumber)
{
if (versionTypeNumber == null || minorVersionTypeNumber == null)
{
return null;
}
else
{
VersionType versionType = new VersionType();
// The version number type can only be 2.
versionType.Version = versionTypeNumber.Value;
// The minor version type number can 0 or 2.
versionType.MinorVersion = minorVersionTypeNumber.Value;
return versionType;
}
}
}
}
| |
using System;
using System.Windows.Input;
using Xunit;
using Prism.Commands;
using System.Threading.Tasks;
using Prism.Tests.Mocks.Commands;
using Prism.Mvvm;
using System.Threading;
using Xunit.Sdk;
namespace Prism.Tests.Mvvm
{
/// <summary>
/// Summary description for DelegateCommandFixture
/// </summary>
public class DelegateCommandFixture : BindableBase
{
[Fact]
public void WhenConstructedWithGenericTypeOfObject_InitializesValues()
{
// Prepare
// Act
var actual = new DelegateCommand<object>(param => { });
// verify
Assert.NotNull(actual);
}
[Fact]
public void WhenConstructedWithGenericTypeOfNullable_InitializesValues()
{
// Prepare
// Act
var actual = new DelegateCommand<int?>(param => { });
// verify
Assert.NotNull(actual);
}
[Fact]
public void WhenConstructedWithGenericTypeIsNonNullableValueType_Throws()
{
Assert.Throws<InvalidCastException>(() =>
{
var actual = new DelegateCommand<int>(param => { });
});
}
[Fact]
public async Task ExecuteCallsPassedInExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
object parameter = new object();
await command.Execute(parameter);
Assert.Same(parameter, handlers.ExecuteParameter);
}
[Fact]
public void CanExecuteCallsPassedInCanExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute, handlers.CanExecute);
object parameter = new object();
handlers.CanExecuteReturnValue = true;
bool retVal = command.CanExecute(parameter);
Assert.Same(parameter, handlers.CanExecuteParameter);
Assert.Equal(handlers.CanExecuteReturnValue, retVal);
}
[Fact]
public void CanExecuteReturnsTrueWithouthCanExecuteDelegate()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
bool retVal = command.CanExecute(null);
Assert.Equal(true, retVal);
}
[Fact]
public void RaiseCanExecuteChangedRaisesCanExecuteChanged()
{
var handlers = new DelegateHandlers();
var command = new DelegateCommand<object>(handlers.Execute);
bool canExecuteChangedRaised = false;
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
command.RaiseCanExecuteChanged();
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void CanRemoveCanExecuteChangedHandler()
{
var command = new DelegateCommand<object>((o) => { });
bool canExecuteChangedRaised = false;
EventHandler handler = (s, e) => canExecuteChangedRaised = true;
command.CanExecuteChanged += handler;
command.CanExecuteChanged -= handler;
command.RaiseCanExecuteChanged();
Assert.False(canExecuteChangedRaised);
}
[Fact]
public void ShouldPassParameterInstanceOnExecute()
{
bool executeCalled = false;
MyClass testClass = new MyClass();
ICommand command = new DelegateCommand<MyClass>(delegate (MyClass parameter)
{
Assert.Same(testClass, parameter);
executeCalled = true;
});
command.Execute(testClass);
Assert.True(executeCalled);
}
[Fact]
public void ShouldPassParameterInstanceOnCanExecute()
{
bool canExecuteCalled = false;
MyClass testClass = new MyClass();
ICommand command = new DelegateCommand<MyClass>((p) => { }, delegate (MyClass parameter)
{
Assert.Same(testClass, parameter);
canExecuteCalled = true;
return true;
});
command.CanExecute(testClass);
Assert.True(canExecuteCalled);
}
[Fact]
public void ShouldThrowIfAllDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>(null, null);
});
}
[Fact]
public void ShouldThrowIfExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>(null);
});
}
[Fact]
public void ShouldThrowIfCanExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand<object>((o) => { }, null);
});
}
[Fact]
public void DelegateCommandBaseShouldThrowIfAllDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommandMock(null, null);
});
}
[Fact]
public void DelegateCommandBaseShouldThrowIfExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommandMock(null);
});
}
[Fact]
public void DelegateCommandBaseShouldThrowIfCanExecuteMethodDelegateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommandMock((o) => { }, null);
});
}
//TODO: BBL: This test fails intermittently. The cause is unknown, but we think it may be a race condition issue.
//In order to reduce the friction of our automated build processes, we are commenting out this test.
//[Fact]
//public void NonGenericDelegateCommandShouldInvokeExplicitExecuteFunc()
//{
// bool executed = false;
// ICommand command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { executed = true; }));
// command.Execute(null);
// Assert.True(executed);
//}
[Fact]
public void IsActivePropertyIsFalseByDeafult()
{
var command = new DelegateCommand<object>(DoNothing);
Assert.False(command.IsActive);
}
[Fact]
public void IsActivePropertyChangeFiresEvent()
{
bool fired = false;
var command = new DelegateCommand<object>(DoNothing);
command.IsActiveChanged += delegate { fired = true; };
command.IsActive = true;
Assert.True(fired);
}
[Fact]
public async Task NonGenericDelegateCommandExecuteShouldInvokeExecuteAction()
{
bool executed = false;
var command = new DelegateCommand(() => { executed = true; });
await command.Execute();
Assert.True(executed);
}
[Fact]
public void NonGenericDelegateCommandCanExecuteShouldInvokeCanExecuteFunc()
{
bool invoked = false;
var command = new DelegateCommand(() => { }, () => { invoked = true; return true; });
bool canExecute = command.CanExecute();
Assert.True(invoked);
Assert.True(canExecute);
}
[Fact]
public void NonGenericDelegateCommandShouldDefaultCanExecuteToTrue()
{
var command = new DelegateCommand(() => { });
Assert.True(command.CanExecute());
}
[Fact]
public void NonGenericDelegateThrowsIfDelegatesAreNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null, null);
});
}
[Fact]
public void NonGenericDelegateCommandThrowsIfExecuteDelegateIsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(null);
});
}
[Fact]
public void NonGenericDelegateCommandThrowsIfCanExecuteDelegateIsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = new DelegateCommand(() => { }, null);
});
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }));
Assert.NotNull(command);
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithExecuteAndCanExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }), (o) => true);
Assert.NotNull(command);
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerCanExecuteShouldBeTrueByDefault()
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }));
var canExecute = command.CanExecute(null);
Assert.True(canExecute);
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithNullExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand<object>.FromAsyncHandler(null);
});
}
[Fact]
public void GenericDelegateCommandFromAsyncHandlerWithNullCanExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }), null);
});
}
[Fact]
public void DelegateCommandBaseWithNullExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommandMock.FromAsyncHandler(null);
});
}
[Fact]
public void DelegateCommandBaseWithNullCanExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => { }), null);
});
}
[Fact]
public async Task GenericDelegateCommandFromAsyncHandlerExecuteShouldInvokeExecuteFunc()
{
bool executed = false;
var command = DelegateCommand<object>.FromAsyncHandler(async (o) => await Task.Run(() => executed = true));
await command.Execute(null);
Assert.True(executed);
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }));
Assert.NotNull(command);
}
[Fact]
public void DelegateCommandFromAsyncHandlerCanExecuteShouldBeTrueByDefault()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }));
var canExecute = command.CanExecute();
Assert.True(canExecute);
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithNullExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand.FromAsyncHandler(null);
});
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithExecuteAndCanExecuteFuncShouldNotBeNull()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }), () => true);
Assert.NotNull(command);
}
[Fact]
public void DelegateCommandFromAsyncHandlerWithNullCanExecuteFuncShouldThrow()
{
Assert.Throws<ArgumentNullException>(() =>
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }), null);
});
}
[Fact]
public async Task DelegateCommandFromAsyncHandlerExecuteShouldInvokeExecuteFunc()
{
bool executed = false;
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => executed = true));
await command.Execute();
Assert.True(executed);
}
[Fact]
public void DelegateCommandFromAsyncHandlerCanExecuteShouldInvokeCanExecuteFunc()
{
var command = DelegateCommand.FromAsyncHandler(async () => await Task.Run(() => { }), () => true);
var canExecute = command.CanExecute();
Assert.True(canExecute);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute((o) => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void NonGenericDelegateCommandShouldObserveCanExecuteAndObserveOtherProperties()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute((o) => BoolProperty).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
canExecuteChangedRaised = false;
Assert.False(canExecuteChangedRaised);
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void NonGenericDelegateCommandShouldNotObserveDuplicateCanExecute()
{
Assert.Throws<ArgumentException>(() =>
{
ICommand command = new DelegateCommand(() => { }).ObservesCanExecute((o) => BoolProperty).ObservesCanExecute((o) => BoolProperty);
});
}
[Fact]
public void NonGenericDelegateCommandShouldObserveOneProperty()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldObserveMultipleProperties()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void NonGenericDelegateCommandShouldNotObserveDuplicateProperties()
{
Assert.Throws<ArgumentException>(() =>
{
DelegateCommand command = new DelegateCommand(() => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => IntProperty);
});
}
[Fact]
public void GenericDelegateCommandShouldObserveCanExecute()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<object>((o) => { }).ObservesCanExecute((o) => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandShouldObserveCanExecuteAndObserveOtherProperties()
{
bool canExecuteChangedRaised = false;
ICommand command = new DelegateCommand<object>((o) => { }).ObservesCanExecute((o) => BoolProperty).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
Assert.False(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
Assert.False(command.CanExecute(null));
canExecuteChangedRaised = false;
Assert.False(canExecuteChangedRaised);
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
Assert.True(command.CanExecute(null));
}
[Fact]
public void GenericDelegateCommandShouldNotObserveDuplicateCanExecute()
{
Assert.Throws<ArgumentException>(() =>
{
ICommand command =
new DelegateCommand<object>((o) => { }).ObservesCanExecute((o) => BoolProperty)
.ObservesCanExecute((o) => BoolProperty);
});
}
[Fact]
public void GenericDelegateCommandShouldObserveOneProperty()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldObserveMultipleProperties()
{
bool canExecuteChangedRaised = false;
var command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => BoolProperty);
command.CanExecuteChanged += delegate { canExecuteChangedRaised = true; };
IntProperty = 10;
Assert.True(canExecuteChangedRaised);
canExecuteChangedRaised = false;
BoolProperty = true;
Assert.True(canExecuteChangedRaised);
}
[Fact]
public void GenericDelegateCommandShouldNotObserveDuplicateProperties()
{
Assert.Throws<ArgumentException>(() =>
{
DelegateCommand<object> command = new DelegateCommand<object>((o) => { }).ObservesProperty(() => IntProperty).ObservesProperty(() => IntProperty);
});
}
private bool _boolProperty;
public bool BoolProperty
{
get { return _boolProperty; }
set { SetProperty(ref _boolProperty, value); }
}
private int _intProperty;
public int IntProperty
{
get { return _intProperty; }
set { SetProperty(ref _intProperty, value); }
}
class CanExecutChangeHandler
{
public bool CanExeucteChangedHandlerCalled;
public void CanExecuteChangeHandler(object sender, EventArgs e)
{
CanExeucteChangedHandlerCalled = true;
}
}
public void DoNothing(object param)
{ }
class DelegateHandlers
{
public bool CanExecuteReturnValue = true;
public object CanExecuteParameter;
public object ExecuteParameter;
public bool CanExecute(object parameter)
{
CanExecuteParameter = parameter;
return CanExecuteReturnValue;
}
public void Execute(object parameter)
{
ExecuteParameter = parameter;
}
}
}
internal class MyClass
{
}
}
| |
// 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 BuildIt.CognitiveServices
{
/// <summary>
/// Use this API to create reviews in Content Moderator. Before you can
/// create reviews you will need a moderation Team. If you don't already
/// have one Sign Up here:
/// https://contentmoderator.cognitive.microsoft.com
///
/// You will need to use your Content Moderator review team credentials to
/// generate Authentication Tokens that need to be passed in the
/// Authorization header in addition to your Content Moderator
/// subscription key.
///
/// To use the Test Console you must include the following header:
///
/// Header name: authorization
/// Header value: Bearer -Your access token-
///
/// </summary>
public partial interface IContentModeratorReview : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Returns review details for the review Id passed.
/// </summary>
/// <param name='teamName'>
/// </param>
/// <param name='reviewId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ReviewGetWithHttpMessagesAsync(string teamName, string reviewId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get the Job Details for a Job Id.
/// </summary>
/// <param name='teamName'>
/// </param>
/// <param name='jobId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> JobGetWithHttpMessagesAsync(string teamName, string jobId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// The reviews created would show up for Reviewers on your team. As
/// Reviewers complete reviewing, results of the Review would be
/// POSTED (i.e. HTTP POST) on the specified CallBackEndpoint.
///
/// <h3>CallBack Schemas </h3>
/// <h4>Review Completion CallBack Sample</h4>
/// <p>
/// {<br/>
/// "ReviewId": "<Review Id>",<br/>
/// "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
/// "ModifiedBy": "<Name of the Reviewer>",<br/>
/// "CallBackType": "Review",<br/>
/// "ContentId": "<The ContentId that was specified
/// input>",<br/>
/// "Metadata": {<br/>
/// "adultscore": "0.xxx",<br/>
/// "a": "False",<br/>
/// "racyscore": "0.xxx",<br/>
/// "r": "True"<br/>
/// },<br/>
/// "ReviewerResultTags": {<br/>
/// "a": "False",<br/>
/// "r": "True"<br/>
/// }<br/>
/// }<br/>
///
/// </p>
/// </summary>
/// <param name='teamName'>
/// Your Team Name
/// </param>
/// <param name='subTeam'>
/// Optional paramter used to specify the Sub Team for this review
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ReviewCreateWithHttpMessagesAsync(string teamName, string subTeam = default(string), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A job Id will be returned for the Image content posted on this
/// endpoint.
///
/// Once the content is evaluated against the Workflow provided the
/// review will be created or ignored based on the workflow
/// expression.
///
/// <h3>CallBack Schemas </h3>
///
/// <p>
/// <h4>Job Completion CallBack Sample</h4><br/>
///
/// {<br/>
/// "JobId": "<Job Id>,<br/>
/// "ReviewId": "<Review Id, if the Job resulted in a Review to
/// be created>",<br/>
/// "WorkFlowId": "default",<br/>
/// "Status": "<This will be one of Complete, InProgress,
/// Error>",<br/>
/// "ContentType": "Image",<br/>
/// "ContentId": "<This is the ContentId that was specified on
/// input>",<br/>
/// "CallBackType": "Job",<br/>
/// "Metadata": {<br/>
/// "adultscore": "0.xxx",<br/>
/// "a": "False",<br/>
/// "racyscore": "0.xxx",<br/>
/// "r": "True"<br/>
/// }<br/>
/// }<br/>
///
/// </p>
/// <p>
/// <h4>Review Completion CallBack Sample</h4><br/>
///
/// {
/// "ReviewId": "<Review Id>",<br/>
/// "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
/// "ModifiedBy": "<Name of the Reviewer>",<br/>
/// "CallBackType": "Review",<br/>
/// "ContentId": "<The ContentId that was specified
/// input>",<br/>
/// "Metadata": {<br/>
/// "adultscore": "0.xxx",
/// "a": "False",<br/>
/// "racyscore": "0.xxx",<br/>
/// "r": "True"<br/>
/// },<br/>
/// "ReviewerResultTags": {<br/>
/// "a": "False",<br/>
/// "r": "True"<br/>
/// }<br/>
/// }<br/>
///
/// </p>
/// </summary>
/// <param name='teamName'>
/// Your team name
/// </param>
/// <param name='contentId'>
/// Content Id/Name
/// </param>
/// <param name='workflowName'>
/// Workflow Name, if left empty your teams default workflow would be
/// used
/// </param>
/// <param name='callBackEndpoint'>
/// Callback endpoint for posting the reviews result.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> JobCreateWithHttpMessagesAsync(string teamName, string contentId, string workflowName, string callBackEndpoint = default(string), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get all the Workflows available for you Team
/// </summary>
/// <param name='team'>
/// Your Team name
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> WorkflowGetAllWithHttpMessagesAsync(string team, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get the details of a specific Workflow on your Team
/// </summary>
/// <param name='team'>
/// Your Team name
/// </param>
/// <param name='workflowname'>
/// Provide a name for this workflow
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> WorkflowGetWithHttpMessagesAsync(string team, string workflowname, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Create a new workflow or update an existing one.
/// </summary>
/// <param name='team'>
/// Your Team name
/// </param>
/// <param name='workflowname'>
/// Provide a name for this workflow
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> WorkflowCreateOrUpdateWithHttpMessagesAsync(string team, string workflowname, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServerManagement
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SessionOperations operations.
/// </summary>
internal partial class SessionOperations : Microsoft.Rest.IServiceOperations<ServerManagementClient>, ISessionOperations
{
/// <summary>
/// Initializes a new instance of the SessionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SessionOperations(ServerManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ServerManagementClient
/// </summary>
public ServerManagementClient Client { get; private set; }
/// <summary>
/// Creates a session for a node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='session'>
/// The sessionId from the user
/// </param>
/// <param name='userName'>
/// encrypted User name to be used to connect to node
/// </param>
/// <param name='password'>
/// encrypted Password associated with user name
/// </param>
/// <param name='retentionPeriod'>
/// session retention period. Possible values include: 'Session', 'Persistent'
/// </param>
/// <param name='credentialDataFormat'>
/// credential data format. Possible values include: 'RsaEncrypted'
/// </param>
/// <param name='encryptionCertificateThumbprint'>
/// encryption certificate thumbprint
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SessionResource>> CreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string userName = default(string), string password = default(string), RetentionPeriod? retentionPeriod = default(RetentionPeriod?), CredentialDataFormat? credentialDataFormat = default(CredentialDataFormat?), string encryptionCertificateThumbprint = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send Request
Microsoft.Rest.Azure.AzureOperationResponse<SessionResource> _response = await BeginCreateWithHttpMessagesAsync(
resourceGroupName, nodeName, session, userName, password, retentionPeriod, credentialDataFormat, encryptionCertificateThumbprint, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Creates a session for a node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='session'>
/// The sessionId from the user
/// </param>
/// <param name='userName'>
/// encrypted User name to be used to connect to node
/// </param>
/// <param name='password'>
/// encrypted Password associated with user name
/// </param>
/// <param name='retentionPeriod'>
/// session retention period. Possible values include: 'Session', 'Persistent'
/// </param>
/// <param name='credentialDataFormat'>
/// credential data format. Possible values include: 'RsaEncrypted'
/// </param>
/// <param name='encryptionCertificateThumbprint'>
/// encryption certificate thumbprint
/// </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="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SessionResource>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string userName = default(string), string password = default(string), RetentionPeriod? retentionPeriod = default(RetentionPeriod?), CredentialDataFormat? credentialDataFormat = default(CredentialDataFormat?), string encryptionCertificateThumbprint = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
if (session == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "session");
}
SessionParameters sessionParameters = new SessionParameters();
if (userName != null || password != null || encryptionCertificateThumbprint != null)
{
sessionParameters.UserName = userName;
sessionParameters.Password = password;
sessionParameters.RetentionPeriod = retentionPeriod;
sessionParameters.CredentialDataFormat = credentialDataFormat;
sessionParameters.EncryptionCertificateThumbprint = encryptionCertificateThumbprint;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("session", session);
tracingParameters.Add("sessionParameters", sessionParameters);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}/sessions/{session}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", System.Uri.EscapeDataString(nodeName));
_url = _url.Replace("{session}", System.Uri.EscapeDataString(session));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(sessionParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(sessionParameters, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202)
{
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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SessionResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SessionResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SessionResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a session for a node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='session'>
/// The sessionId from the user
/// </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="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
if (session == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "session");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("session", session);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}/sessions/{session}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", System.Uri.EscapeDataString(nodeName));
_url = _url.Replace("{session}", System.Uri.EscapeDataString(session));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a session for a node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='session'>
/// The sessionId from the user
/// </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="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SessionResource>> GetWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
if (session == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "session");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("session", session);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}/sessions/{session}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", System.Uri.EscapeDataString(nodeName));
_url = _url.Replace("{session}", System.Uri.EscapeDataString(session));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<SessionResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<SessionResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Copyright (c) 2007 Microsoft Corporation. All rights reserved.
//
using System;
using System.Management.Automation;
using System.Globalization;
using System.Reflection;
using System.Diagnostics.Eventing;
using System.Diagnostics.Eventing.Reader;
using System.Resources;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Xml;
using System.IO;
namespace Microsoft.PowerShell.Commands
{
///
/// Class that implements the New-WinEvent cmdlet.
/// This cmdlet writes a new Etw event using the provider specified in parameter.
///
[Cmdlet(VerbsCommon.New, "WinEvent", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217469")]
public sealed class NewWinEventCommand : PSCmdlet
{
private ProviderMetadata _providerMetadata;
private EventDescriptor? _eventDescriptor;
private const string TemplateTag = "template";
private const string DataTag = "data";
private ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();
/// <summary>
/// ProviderName
/// </summary>
[Parameter(
Position = 0,
Mandatory = true,
ParameterSetName = ParameterAttribute.AllParameterSets)]
public string ProviderName
{
get
{
return _providerName;
}
set
{
_providerName = value;
}
}
private string _providerName;
/// <summary>
/// Id (EventId defined in manifest file)
/// </summary>
[Parameter(
Position = 1,
Mandatory = true,
ParameterSetName = ParameterAttribute.AllParameterSets)]
public int Id
{
get
{
return _id;
}
set
{
_id = value;
_idSpecified = true;
}
}
private int _id;
private bool _idSpecified = false;
/// <summary>
/// Version (event version)
/// </summary>
[Parameter(
Mandatory = false,
ParameterSetName = ParameterAttribute.AllParameterSets)]
public byte Version
{
get
{
return _version;
}
set
{
_version = value;
_versionSpecified = true;
}
}
private byte _version;
private bool _versionSpecified = false;
/// <summary>
/// Event Payload
/// </summary>
[Parameter(
Position = 2,
Mandatory = false,
ParameterSetName = ParameterAttribute.AllParameterSets),
AllowEmptyCollection,
SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Target = "Microsoft.PowerShell.Commands",
Justification = "A string[] is required here because that is the type Powershell supports")]
public object[] Payload
{
get
{
return _payload;
}
set
{
_payload = value;
}
}
private object[] _payload;
/// <summary>
/// BeginProcessing
/// </summary>
protected override void BeginProcessing()
{
LoadProvider();
LoadEventDescriptor();
base.BeginProcessing();
}
private void LoadProvider()
{
if (string.IsNullOrEmpty(_providerName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName");
}
using (EventLogSession session = new EventLogSession())
{
foreach (string providerName in session.GetProviderNames())
{
if (string.Equals(providerName, _providerName, StringComparison.OrdinalIgnoreCase))
{
try
{
_providerMetadata = new ProviderMetadata(providerName);
}
catch (EventLogException exc)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message);
throw new Exception(msg, exc);
}
break;
}
}
}
if (_providerMetadata == null)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), _providerName);
throw new ArgumentException(msg);
}
}
private void LoadEventDescriptor()
{
if (_idSpecified)
{
List<EventMetadata> matchedEvents = new List<EventMetadata>();
foreach (EventMetadata emd in _providerMetadata.Events)
{
if (emd.Id == _id)
{
matchedEvents.Add(emd);
}
}
if (matchedEvents.Count == 0)
{
string msg = string.Format(CultureInfo.InvariantCulture,
_resourceMgr.GetString("IncorrectEventId"),
_id,
_providerName);
throw new EventWriteException(msg);
}
EventMetadata matchedEvent = null;
if (!_versionSpecified && matchedEvents.Count == 1)
{
matchedEvent = matchedEvents[0];
}
else
{
if (_versionSpecified)
{
foreach (EventMetadata emd in matchedEvents)
{
if (emd.Version == _version)
{
matchedEvent = emd;
break;
}
}
if (matchedEvent == null)
{
string msg = string.Format(CultureInfo.InvariantCulture,
_resourceMgr.GetString("IncorrectEventVersion"),
_version,
_id,
_providerName);
throw new EventWriteException(msg);
}
}
else
{
string msg = string.Format(CultureInfo.InvariantCulture,
_resourceMgr.GetString("VersionNotSpecified"),
_id,
_providerName);
throw new EventWriteException(msg);
}
}
VerifyTemplate(matchedEvent);
_eventDescriptor = CreateEventDescriptor(_providerMetadata, matchedEvent);
}
else
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("EventIdNotSpecified")), "Id");
}
}
private bool VerifyTemplate(EventMetadata emd)
{
if (emd.Template != null)
{
XmlReaderSettings readerSettings = new XmlReaderSettings
{
CheckCharacters = false,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
MaxCharactersInDocument = 0, // no limit
ConformanceLevel = ConformanceLevel.Fragment,
#if !CORECLR
XmlResolver = null,
#endif
};
int definedParameterCount = 0;
using (XmlReader reader = XmlReader.Create(new StringReader(emd.Template), readerSettings))
{
if (reader.ReadToFollowing(TemplateTag))
{
bool found = reader.ReadToDescendant(DataTag);
while (found)
{
definedParameterCount++;
found = reader.ReadToFollowing(DataTag);
}
}
}
if ((_payload == null && definedParameterCount != 0)
|| ((_payload != null) && _payload.Length != definedParameterCount))
{
string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template);
WriteWarning(warning);
return false;
}
}
return true;
}
private static EventDescriptor CreateEventDescriptor(ProviderMetadata providerMetaData, EventMetadata emd)
{
long keywords = 0;
foreach (EventKeyword keyword in emd.Keywords)
{
keywords |= keyword.Value;
}
byte channel = 0;
foreach (EventLogLink logLink in providerMetaData.LogLinks)
{
if (string.Equals(logLink.LogName, emd.LogLink.LogName, StringComparison.OrdinalIgnoreCase))
break;
channel++;
}
return new EventDescriptor(
(int)emd.Id,
emd.Version,
channel,
(byte)emd.Level.Value,
(byte)emd.Opcode.Value,
emd.Task.Value,
keywords);
}
/// <summary>
/// ProcessRecord
/// </summary>
protected override void ProcessRecord()
{
using (EventProvider provider = new EventProvider(_providerMetadata.Id))
{
EventDescriptor ed = _eventDescriptor.Value;
if (_payload != null && _payload.Length > 0)
{
for (int i = 0; i < _payload.Length; i++)
{
if (_payload[i] == null)
{
_payload[i] = string.Empty;
}
}
provider.WriteEvent(ref ed, _payload);
}
else
{
provider.WriteEvent(ref ed);
}
}
base.ProcessRecord();
}
/// <summary>
/// EndProcessing
/// </summary>
protected override void EndProcessing()
{
if (_providerMetadata != null)
_providerMetadata.Dispose();
base.EndProcessing();
}
}
internal class EventWriteException : Exception
{
internal EventWriteException(string msg, Exception innerException)
: base(msg, innerException)
{ }
internal EventWriteException(string msg)
: base(msg)
{ }
}
}
| |
using System;
using System.Collections;
using System.Reflection;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Expression;
namespace Business
{
/// <summary>
/// Summary description for BaseDataAccess.
/// </summary>
public class BaseDataAccess
{
protected ISession m_session;
public BaseDataAccess()
{
m_session = NHibernateHttpModule.CurrentSession;
}
/// <summary>
/// Save a collection.
/// </summary>
/// <param name="items"></param>
public virtual void Save(IList items)
{
ITransaction tx = null;
try
{
if (items!=null)
{
tx = m_session.BeginTransaction();
foreach(object item in items)
{
m_session.Save(item);
}
tx.Commit();
}
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
public virtual void SaveOrUpdate(IList items, bool withTX)
{
ITransaction tx = null;
try
{
if (items!=null)
{
if (withTX) tx = m_session.BeginTransaction();
foreach(object item in items)
{
m_session.SaveOrUpdate(item) ;
}
if (withTX) tx.Commit();
}
}
catch (Exception ex)
{
if (withTX) tx.Rollback();
throw ex;
}
}
public virtual void SaveOrUpdate(IList items)
{
ITransaction tx = null;
try
{
if (items!=null)
{
tx = m_session.BeginTransaction();
foreach(object item in items)
{
m_session.SaveOrUpdate(item) ;
}
tx.Commit();
}
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
public virtual void Save(ISession sesion, IList items)
{
try
{
if (items!=null)
{
foreach(object item in items)
{
sesion.SaveOrUpdate(item);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Saves an item and then saves the child items inside of a transaction.
/// </summary>
/// <param name="parentItem"></param>
/// <param name="childItems"></param>
public virtual void Save(object parentItem, IList childItems)
{
ITransaction tx = null;
try
{
if (childItems!=null)
{
tx = m_session.BeginTransaction();
m_session.SaveOrUpdate(parentItem);
foreach(object item in childItems)
{
m_session.SaveOrUpdate(item);
}
tx.Commit();
}
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
public virtual void Save(object parentItem, IList childItems, bool withTx)
{
ITransaction tx = null;
try
{
if (childItems!=null)
{
if (withTx) tx = m_session.BeginTransaction();
m_session.SaveOrUpdate(parentItem);
foreach(object item in childItems)
{
m_session.SaveOrUpdate(item);
}
if (withTx) tx.Commit();
}
}
catch (Exception ex)
{
if (tx != null) tx.Rollback();
throw ex;
}
}
/// <summary>
/// Saves the item.
/// </summary>
/// <param name="item"></param>
public virtual void Save(object item)
{
Save(item, true);
}
public virtual void Save()
{
Save(this, true);
}
/// <summary>
/// Guarda el item con o sin transaction.
/// </summary>
/// <param name="item"></param>
public virtual void Save(object item, bool withTx)
{
ITransaction tx=null;
try
{
if (withTx) tx = m_session.BeginTransaction();
m_session.SaveOrUpdate(item);
if (withTx) tx.Commit();
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
/// <summary>
/// Modifica el item.
/// </summary>
/// <param name="item"></param>
public virtual void Update()
{
this.Update(this);
}
public virtual void Update(object item)
{
this.Update(this,true);
}
public virtual void Update(object item, bool withTx)
{
ITransaction tx=null;
try
{
tx = m_session.BeginTransaction();
m_session.Update(item);
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
public virtual void Update(IList items)
{
ITransaction tx=null;
try
{
tx = m_session.BeginTransaction();
foreach (object item in items)
{
m_session.Update(item);
}
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
/// <summary>
/// Returns a list of items matching the type supplied.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public IList Get(Type type)
{
return GetByType(type);
}
public object Get(Type type, object id)
{
object returnValue=null;
try
{
returnValue=m_session.Load(type, id);
return returnValue;
}
catch (Exception ex)
{
//TODO: disciminar en caso q la excepcion sea del tipo id inexistente.
throw ex;
}
}
public object Get(object id)
{
return this.Get(this.GetType(),id);
}
public IList GetListByPropertyValue(Type type, string propertyName, object propertyValue)
{
try
{
ICriteria crit=m_session.CreateCriteria(type);
crit.Add(Expression.Eq(propertyName, propertyValue));
return crit.List();
}
catch (Exception ex)
{
throw ex;
}
}
public IList GetListByPropertyValue(Type type, string propertyName, object propertyValue,
string propertyName2, object propertyValue2)
{
try
{
ICriteria crit=m_session.CreateCriteria(type);
crit.Add(Expression.Eq(propertyName, propertyValue));
crit.Add(Expression.Eq(propertyName2, propertyValue2));
return crit.List();
}
catch (Exception ex)
{
throw ex;
}
}
public IList GetListByPropertyValue(Type type, string[] propertyName, object[] propertyValue)
{
try
{
ICriteria crit=m_session.CreateCriteria(type);
for(int i= 0;i<=propertyName.GetUpperBound(0);i++)
{
crit.Add(Expression.Eq(propertyName[i], propertyValue[i]));
}
return crit.List();
}
catch (Exception ex)
{
throw ex;
}
}
public object Get(Type type, string propertyName, object propertyValue)
{
try
{
ICriteria crit=m_session.CreateCriteria(type);
crit.Add(Expression.Eq(propertyName, propertyValue));
IList list = crit.List();
if (list==null || list.Count<1)
{
return null;
}
else
{
return list[0];
}
}
catch (Exception ex)
{
throw ex;
}
}
public object Get(Type type, string propertyName, object propertyValue,string propertyName2, object propertyValue2)
{
try
{
ICriteria crit=m_session.CreateCriteria(type);
crit.Add(Expression.Eq(propertyName, propertyValue));
crit.Add(Expression.Eq(propertyName2, propertyValue2));
IList list = crit.List();
if (list==null || list.Count<1)
{
return null;
}
else
{
return list[0];
}
}
catch (Exception ex)
{
throw ex;
}
}
private IList GetByType(Type type)
{
IList items = null;
ITransaction tx = null;
try
{
tx = m_session.BeginTransaction();
items = m_session.CreateCriteria(type).List();
tx.Commit();
return items;
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
public void Delete(object item)
{
ITransaction tx = null;
try
{
tx = m_session.BeginTransaction();
m_session.Delete(item);
tx.Commit();
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
public void Delete()
{
this.Delete(this);
}
public void Delete(IList items)
{
ITransaction tx = null;
try
{
tx = m_session.BeginTransaction();
foreach (object item in items)
{
m_session.Delete(item);
}
tx.Commit();
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
public void Delete(object parent, IList childs)
{
ITransaction tx = null;
try
{
tx = m_session.BeginTransaction();
foreach (object item in childs)
{
m_session.Delete(item);
}
m_session.Delete(parent);
tx.Commit();
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
public void Delete(ISession sesion, IList items)
{
try
{
foreach (object item in items)
{
sesion.Delete(item);
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Delete(IList items, bool withTx)
{
ITransaction tx = null;
try
{
if (withTx) tx = m_session.BeginTransaction();
foreach (object item in items)
{
m_session.Delete(item);
}
if (withTx) tx.Commit();
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
public void DeleteAll(ISession sesion, Type tipo)
{
try
{
IList lista = sesion.CreateCriteria(tipo).List() ;
foreach (object item in lista)
{
sesion.Delete(item);
}
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteAll(Type tipo)
{
ITransaction tx = null;
try
{
tx = m_session.BeginTransaction();
IList lista = m_session.CreateCriteria(tipo).List() ;
foreach (object item in lista)
{
m_session.Delete(item);
}
tx.Commit ();
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
/// <summary>
/// limpia el cache de datos, si hay algo que no se haya persistido se borra
/// </summary>
/// <example >usado en el caso del boton cancelar donde los obj de memoria se han cambiado
/// y son distintos de los de la BD</example>
public void Clear()
{
try
{
m_session.Clear();
}
catch (Exception ex)
{
throw ex;
}
}
public void Flush ()
{
try
{
NHibernateHttpModule.CurrentSession.Flush() ;
}
catch (Exception ex)
{
throw ex;
}
}
public void Refresh (object item)
{
try
{
NHibernateHttpModule.CurrentSession.Refresh(item);
}
catch
{}
}
public void Refresh (object item, NHibernate.LockMode lockMode)
{
try
{
NHibernateHttpModule.CurrentSession.Refresh(item, lockMode);
}
catch
{}
}
public IList getListByQuery (string HQL)
{
IList items = null;
ITransaction tx = null;
IQuery query = null;
try
{
tx = m_session.BeginTransaction();
query = m_session.CreateQuery(HQL);
items = query.List();
tx.Commit();
return items;
}
catch (Exception ex)
{
if (tx!=null) tx.Rollback();
throw ex;
}
}
}
}
| |
// Copyright (c) 2012 Calvin Rien
// http://the.darktable.com
//
// This software is provided 'as-is', without any express or implied warranty. In
// no event will the authors be held liable for any damages arising from the use
// of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim
// that you wrote the original software. If you use this software in a product,
// an acknowledgment in the product documentation would be appreciated but is not
// required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
using System.Collections;
using System.Collections.Generic;
namespace UnityEngine {
public class UnityNameValuePair<V> : UnityKeyValuePair<string, V> {
public string name = null;
override public string Key {
get { return name; }
set { name = value; }
}
public UnityNameValuePair() : base() {
}
public UnityNameValuePair(string key, V value) : base(key, value) {
}
}
public class UnityKeyValuePair<K, V> {
virtual public K Key {
get;
set;
}
virtual public V Value {
get;
set;
}
public UnityKeyValuePair() {
Key = default(K);
Value = default(V);
}
public UnityKeyValuePair(K key, V value) {
Key = key;
Value = value;
}
}
public abstract class UnityDictionary<K,V> : IDictionary<K,V> {
abstract protected List<UnityKeyValuePair<K,V>> KeyValuePairs {
get;
set;
}
protected abstract void SetKeyValuePair(K k, V v); /* {
var index = Collection.FindIndex(x => {return x.Key == k;});
if (index != -1) {
if (v == null) {
Collection.RemoveAt(index);
return;
}
values[index] = new UnityKeyValuePair(key, value);
return;
}
values.Add(new UnityKeyValuePair(key, value));
} */
virtual public V this[K key] {
get {
var result = KeyValuePairs.Find(x => {
return x.Key.Equals(key);});
if (result == null) {
return default(V);
}
return result.Value;
}
set {
if (key == null) {
return;
}
SetKeyValuePair(key, value);
}
}
#region IDictionary interface
public void Add(K key, V value) {
this[key] = value;
}
public void Add(KeyValuePair<K, V> kvp) {
this[kvp.Key] = kvp.Value;
}
public bool TryGetValue(K key, out V value) {
if (!this.ContainsKey(key)) {
value = default(V);
return false;
}
value = this[key];
return true;
}
public bool Remove(KeyValuePair<K, V> item) {
return Remove(item.Key);
}
public bool Remove(K key) {
var list = KeyValuePairs;
var index = list.FindIndex(x => {
return x.Key.Equals(key);});
if (index == -1) {
return false;
}
list.RemoveAt(index);
KeyValuePairs = list;
return true;
}
public void Clear() {
var list = KeyValuePairs;
list.Clear();
KeyValuePairs = list;
}
public bool ContainsKey(K key) {
return KeyValuePairs.FindIndex(x => {
return x.Key.Equals(key);}) != -1;
}
public bool Contains(KeyValuePair<K, V> kvp) {
return this[kvp.Key].Equals(kvp.Value);
}
public int Count {
get {
return KeyValuePairs.Count;
}
}
public void CopyTo(KeyValuePair<K, V>[] array, int index) {
List<KeyValuePair<K, V>> copy = new List<KeyValuePair<K, V>>();
for (int i = 0; i < KeyValuePairs.Count;i++)
{
copy[i] = ConvertUkvp(KeyValuePairs[i]);
}
copy.CopyTo(array, index);
}
public KeyValuePair<K,V> ConvertUkvp(UnityKeyValuePair<K, V> ukvp)
{
return new KeyValuePair<K,V>(ukvp.Key,(V)ukvp.Value);
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator() as IEnumerator;
}
public IEnumerator<KeyValuePair<K, V>> GetEnumerator() {
return new UnityDictionaryEnumerator(this);
}
public ICollection<K> Keys {
get {
ICollection<K> keys = new List<K>();
foreach(UnityKeyValuePair<K,V> ukvp in KeyValuePairs)
{
keys.Add(ukvp.Key);
}
return keys;
}
}
public ICollection<V> Values {
get {
ICollection<V> values = new List<V>();
foreach (UnityKeyValuePair<K, V> ukvp in KeyValuePairs)
{
values.Add(ukvp.Value);
}
return values;
}
}
public ICollection<KeyValuePair<K, V>> Items {
get {
List<KeyValuePair<K,V>> items = new List<KeyValuePair<K,V>>();
foreach(UnityKeyValuePair<K,V> value in KeyValuePairs)
{
items.Add(new KeyValuePair<K, V>(value.Key, value.Value));
}
return items;
}
}
public V SyncRoot {
get { return default(V); }
}
public bool IsFixedSize {
get { return false; }
}
public bool IsReadOnly {
get { return false; }
}
public bool IsSynchronized {
get { return false; }
}
internal sealed class UnityDictionaryEnumerator : IEnumerator<KeyValuePair<K, V>> {
// A copy of the SimpleDictionary T's key/value pairs.
KeyValuePair<K, V>[] items;
int index = -1;
internal UnityDictionaryEnumerator() {
}
internal UnityDictionaryEnumerator(UnityDictionary<K,V> ud) {
// Make a copy of the dictionary entries currently in the SimpleDictionary T.
items = new KeyValuePair<K, V>[ud.Count];
ud.CopyTo(items, 0);
}
object IEnumerator.Current {
get { return Current; }
}
public KeyValuePair<K, V> Current {
get {
ValidateIndex();
return items[index];
}
}
// Return the current dictionary entry.
public KeyValuePair<K, V> Entry {
get { return (KeyValuePair<K, V>) Current; }
}
public void Dispose() {
index = -1;
items = null;
}
// Return the key of the current item.
public K Key {
get {
ValidateIndex();
return items[index].Key;
}
}
// Return the value of the current item.
public V Value {
get {
ValidateIndex();
return items[index].Value;
}
}
// Advance to the next item.
public bool MoveNext() {
if (index < items.Length - 1) {
index++;
return true;
}
return false;
}
// Validate the enumeration index and throw an exception if the index is out of range.
private void ValidateIndex() {
if (index < 0 || index >= items.Length) {
throw new System.InvalidOperationException("Enumerator is before or after the collection.");
}
}
// Reset the index to restart the enumeration.
public void Reset() {
index = -1;
}
#endregion
}
}
public abstract class UnityDictionary<V> : UnityDictionary<string, V> {
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
namespace Lucene.Net.Search
{
/// <summary> A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum
/// score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries.
/// This is useful when searching for a word in multiple fields with different boost factors (so that the fields cannot be
/// combined equivalently into a single search field). We want the primary score to be the one associated with the highest boost,
/// not the sum of the field scores (as BooleanQuery would give).
/// If the query is "albino elephant" this ensures that "albino" matching one field and "elephant" matching
/// another gets a higher score than "albino" matching both fields.
/// To get this result, use both BooleanQuery and DisjunctionMaxQuery: for each term a DisjunctionMaxQuery searches for it in
/// each field, while the set of these DisjunctionMaxQuery's is combined into a BooleanQuery.
/// The tie breaker capability allows results that include the same term in multiple fields to be judged better than results that
/// include this term in only the best of those multiple fields, without confusing this with the better case of two different terms
/// in the multiple fields.
/// </summary>
[Serializable]
public class DisjunctionMaxQuery:Query, System.ICloneable
{
/* The subqueries */
private SupportClass.EquatableList<Query> disjuncts = new SupportClass.EquatableList<Query>();
/* Multiple of the non-max disjunct scores added into our final score. Non-zero values support tie-breaking. */
private float tieBreakerMultiplier = 0.0f;
/// <summary>Creates a new empty DisjunctionMaxQuery. Use add() to add the subqueries.</summary>
/// <param name="tieBreakerMultiplier">the score of each non-maximum disjunct for a document is multiplied by this weight
/// and added into the final score. If non-zero, the value should be small, on the order of 0.1, which says that
/// 10 occurrences of word in a lower-scored field that is also in a higher scored field is just as good as a unique
/// word in the lower scored field (i.e., one that is not in any higher scored field.
/// </param>
public DisjunctionMaxQuery(float tieBreakerMultiplier)
{
this.tieBreakerMultiplier = tieBreakerMultiplier;
}
/// <summary> Creates a new DisjunctionMaxQuery</summary>
/// <param name="disjuncts">a Collection<Query> of all the disjuncts to add
/// </param>
/// <param name="tieBreakerMultiplier"> the weight to give to each matching non-maximum disjunct
/// </param>
public DisjunctionMaxQuery(System.Collections.ICollection disjuncts, float tieBreakerMultiplier)
{
this.tieBreakerMultiplier = tieBreakerMultiplier;
Add(disjuncts);
}
/// <summary>Add a subquery to this disjunction</summary>
/// <param name="query">the disjunct added
/// </param>
public virtual void Add(Query query)
{
disjuncts.Add(query);
}
/// <summary>Add a collection of disjuncts to this disjunction
/// via Iterable
/// </summary>
public virtual void Add(System.Collections.ICollection disjuncts)
{
this.disjuncts.AddRange(disjuncts);
}
/// <summary>An Iterator<Query> over the disjuncts </summary>
public virtual System.Collections.IEnumerator Iterator()
{
return disjuncts.GetEnumerator();
}
/// <summary> Expert: the Weight for DisjunctionMaxQuery, used to
/// normalize, score and explain these queries.
///
/// <p/>NOTE: this API and implementation is subject to
/// change suddenly in the next release.<p/>
/// </summary>
[Serializable]
protected internal class DisjunctionMaxWeight:Weight
{
private void InitBlock(DisjunctionMaxQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private DisjunctionMaxQuery enclosingInstance;
public DisjunctionMaxQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
/// <summary>The Similarity implementation. </summary>
protected internal Similarity similarity;
/// <summary>The Weights for our subqueries, in 1-1 correspondence with disjuncts </summary>
protected internal System.Collections.ArrayList weights = new System.Collections.ArrayList(); // The Weight's for our subqueries, in 1-1 correspondence with disjuncts
/* Construct the Weight for this Query searched by searcher. Recursively construct subquery weights. */
public DisjunctionMaxWeight(DisjunctionMaxQuery enclosingInstance, Searcher searcher)
{
InitBlock(enclosingInstance);
this.similarity = searcher.GetSimilarity();
for (System.Collections.IEnumerator iter = Enclosing_Instance.disjuncts.GetEnumerator(); iter.MoveNext(); )
{
weights.Add(((Query) iter.Current).CreateWeight(searcher));
}
}
/* Return our associated DisjunctionMaxQuery */
public override Query GetQuery()
{
return Enclosing_Instance;
}
/* Return our boost */
public override float GetValue()
{
return Enclosing_Instance.GetBoost();
}
/* Compute the sub of squared weights of us applied to our subqueries. Used for normalization. */
public override float SumOfSquaredWeights()
{
float max = 0.0f, sum = 0.0f;
for (System.Collections.IEnumerator iter = weights.GetEnumerator(); iter.MoveNext(); )
{
float sub = ((Weight) iter.Current).SumOfSquaredWeights();
sum += sub;
max = System.Math.Max(max, sub);
}
float boost = Enclosing_Instance.GetBoost();
return (((sum - max) * Enclosing_Instance.tieBreakerMultiplier * Enclosing_Instance.tieBreakerMultiplier) + max) * boost * boost;
}
/* Apply the computed normalization factor to our subqueries */
public override void Normalize(float norm)
{
norm *= Enclosing_Instance.GetBoost(); // Incorporate our boost
for (System.Collections.IEnumerator iter = weights.GetEnumerator(); iter.MoveNext(); )
{
((Weight) iter.Current).Normalize(norm);
}
}
/* Create the scorer used to score our associated DisjunctionMaxQuery */
public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer)
{
Scorer[] scorers = new Scorer[weights.Count];
int idx = 0;
for (System.Collections.IEnumerator iter = weights.GetEnumerator(); iter.MoveNext(); )
{
Weight w = (Weight) iter.Current;
Scorer subScorer = w.Scorer(reader, true, false);
if (subScorer != null && subScorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
scorers[idx++] = subScorer;
}
}
if (idx == 0)
return null; // all scorers did not have documents
DisjunctionMaxScorer result = new DisjunctionMaxScorer(Enclosing_Instance.tieBreakerMultiplier, similarity, scorers, idx);
return result;
}
/* Explain the score we computed for doc */
public override Explanation Explain(IndexReader reader, int doc)
{
if (Enclosing_Instance.disjuncts.Count == 1)
return ((Weight) weights[0]).Explain(reader, doc);
ComplexExplanation result = new ComplexExplanation();
float max = 0.0f, sum = 0.0f;
result.SetDescription(Enclosing_Instance.tieBreakerMultiplier == 0.0f?"max of:":"max plus " + Enclosing_Instance.tieBreakerMultiplier + " times others of:");
for (System.Collections.IEnumerator iter = weights.GetEnumerator(); iter.MoveNext(); )
{
Explanation e = ((Weight) iter.Current).Explain(reader, doc);
if (e.IsMatch())
{
System.Boolean tempAux = true;
result.SetMatch(tempAux);
result.AddDetail(e);
sum += e.GetValue();
max = System.Math.Max(max, e.GetValue());
}
}
result.SetValue(max + (sum - max) * Enclosing_Instance.tieBreakerMultiplier);
return result;
}
} // end of DisjunctionMaxWeight inner class
/* Create the Weight used to score us */
public override Weight CreateWeight(Searcher searcher)
{
return new DisjunctionMaxWeight(this, searcher);
}
/// <summary>Optimize our representation and our subqueries representations</summary>
/// <param name="reader">the IndexReader we query
/// </param>
/// <returns> an optimized copy of us (which may not be a copy if there is nothing to optimize)
/// </returns>
public override Query Rewrite(IndexReader reader)
{
int numDisjunctions = disjuncts.Count;
if (numDisjunctions == 1)
{
Query singleton = (Query) disjuncts[0];
Query result = singleton.Rewrite(reader);
if (GetBoost() != 1.0f)
{
if (result == singleton)
result = (Query) result.Clone();
result.SetBoost(GetBoost() * result.GetBoost());
}
return result;
}
DisjunctionMaxQuery clone = null;
for (int i = 0; i < numDisjunctions; i++)
{
Query clause = (Query) disjuncts[i];
Query rewrite = clause.Rewrite(reader);
if (rewrite != clause)
{
if (clone == null)
clone = (DisjunctionMaxQuery) this.Clone();
clone.disjuncts[i] = rewrite;
}
}
if (clone != null)
return clone;
else
return this;
}
/// <summary>Create a shallow copy of us -- used in rewriting if necessary</summary>
/// <returns> a copy of us (but reuse, don't copy, our subqueries)
/// </returns>
public override System.Object Clone()
{
DisjunctionMaxQuery clone = (DisjunctionMaxQuery) base.Clone();
clone.disjuncts = (SupportClass.EquatableList<Query>) this.disjuncts.Clone();
return clone;
}
// inherit javadoc
public override void ExtractTerms(System.Collections.Hashtable terms)
{
for (System.Collections.IEnumerator iter = disjuncts.GetEnumerator(); iter.MoveNext(); )
{
((Query) iter.Current).ExtractTerms(terms);
}
}
/// <summary>Prettyprint us.</summary>
/// <param name="field">the field to which we are applied
/// </param>
/// <returns> a string that shows what we do, of the form "(disjunct1 | disjunct2 | ... | disjunctn)^boost"
/// </returns>
public override System.String ToString(System.String field)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append("(");
int numDisjunctions = disjuncts.Count;
for (int i = 0; i < numDisjunctions; i++)
{
Query subquery = (Query) disjuncts[i];
if (subquery is BooleanQuery)
{
// wrap sub-bools in parens
buffer.Append("(");
buffer.Append(subquery.ToString(field));
buffer.Append(")");
}
else
buffer.Append(subquery.ToString(field));
if (i != numDisjunctions - 1)
buffer.Append(" | ");
}
buffer.Append(")");
if (tieBreakerMultiplier != 0.0f)
{
buffer.Append("~");
buffer.Append(tieBreakerMultiplier);
}
if (GetBoost() != 1.0)
{
buffer.Append("^");
buffer.Append(GetBoost());
}
return buffer.ToString();
}
/// <summary>Return true iff we represent the same query as o</summary>
/// <param name="o">another object
/// </param>
/// <returns> true iff o is a DisjunctionMaxQuery with the same boost and the same subqueries, in the same order, as us
/// </returns>
public override bool Equals(System.Object o)
{
if (!(o is DisjunctionMaxQuery))
return false;
DisjunctionMaxQuery other = (DisjunctionMaxQuery) o;
return this.GetBoost() == other.GetBoost() && this.tieBreakerMultiplier == other.tieBreakerMultiplier && this.disjuncts.Equals(other.disjuncts);
}
/// <summary>Compute a hash code for hashing us</summary>
/// <returns> the hash code
/// </returns>
public override int GetHashCode()
{
return BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0) + BitConverter.ToInt32(BitConverter.GetBytes(tieBreakerMultiplier), 0) + disjuncts.GetHashCode();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Commands;
using NUnit.Framework.Internal.Execution;
using UnityEngine.TestTools.Logging;
using UnityEngine.TestTools.TestRunner;
namespace UnityEngine.TestRunner.NUnitExtensions.Runner
{
internal class CompositeWorkItem : UnityWorkItem
{
private readonly TestSuite _suite;
private readonly TestSuiteResult _suiteResult;
private readonly ITestFilter _childFilter;
private TestCommand _setupCommand;
private TestCommand _teardownCommand;
public List<UnityWorkItem> Children { get; private set; }
private int _countOrder;
private CountdownEvent _childTestCountdown;
public CompositeWorkItem(TestSuite suite, ITestFilter childFilter, WorkItemFactory factory)
: base(suite, factory)
{
_suite = suite;
_suiteResult = Result as TestSuiteResult;
_childFilter = childFilter;
_countOrder = 0;
}
protected override IEnumerable PerformWork()
{
InitializeSetUpAndTearDownCommands();
if (UnityTestExecutionContext.CurrentContext != null && m_DontRunRestoringResult && EditModeTestCallbacks.RestoringTestContext != null)
{
EditModeTestCallbacks.RestoringTestContext();
}
if (!CheckForCancellation())
if (Test.RunState == RunState.Explicit && !_childFilter.IsExplicitMatch(Test))
SkipFixture(ResultState.Explicit, GetSkipReason(), null);
else
switch (Test.RunState)
{
default:
case RunState.Runnable:
case RunState.Explicit:
Result.SetResult(ResultState.Success);
CreateChildWorkItems();
if (Children.Count > 0)
{
if (!m_DontRunRestoringResult)
{
//This is needed to give the editor a chance to go out of playmode if needed before creating objects.
//If we do not, the objects could be automatically destroyed when exiting playmode and could result in errors later on
yield return null;
PerformOneTimeSetUp();
}
if (!CheckForCancellation())
{
switch (Result.ResultState.Status)
{
case TestStatus.Passed:
foreach (var child in RunChildren())
{
if (CheckForCancellation())
{
yield break;
}
yield return child;
}
break;
case TestStatus.Skipped:
case TestStatus.Inconclusive:
case TestStatus.Failed:
SkipChildren(_suite, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message);
break;
}
}
if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested && !m_DontRunRestoringResult)
{
PerformOneTimeTearDown();
}
}
break;
case RunState.Skipped:
SkipFixture(ResultState.Skipped, GetSkipReason(), null);
break;
case RunState.Ignored:
SkipFixture(ResultState.Ignored, GetSkipReason(), null);
break;
case RunState.NotRunnable:
SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace());
break;
}
if (!ResultedInDomainReload)
{
WorkItemComplete();
}
}
private bool CheckForCancellation()
{
if (Context.ExecutionStatus != TestExecutionStatus.Running)
{
Result.SetResult(ResultState.Cancelled, "Test cancelled by user");
return true;
}
return false;
}
private void InitializeSetUpAndTearDownCommands()
{
List<SetUpTearDownItem> setUpTearDownItems = _suite.TypeInfo != null
? CommandBuilder.BuildSetUpTearDownList(_suite.TypeInfo.Type, typeof(OneTimeSetUpAttribute), typeof(OneTimeTearDownAttribute))
: new List<SetUpTearDownItem>();
var actionItems = new List<TestActionItem>();
foreach (ITestAction action in Actions)
{
bool applyToSuite = (action.Targets & ActionTargets.Suite) == ActionTargets.Suite
|| action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite);
bool applyToTest = (action.Targets & ActionTargets.Test) == ActionTargets.Test
&& !(Test is ParameterizedMethodSuite);
if (applyToSuite)
actionItems.Add(new TestActionItem(action));
if (applyToTest)
Context.UpstreamActions.Add(action);
}
_setupCommand = CommandBuilder.MakeOneTimeSetUpCommand(_suite, setUpTearDownItems, actionItems);
_teardownCommand = CommandBuilder.MakeOneTimeTearDownCommand(_suite, setUpTearDownItems, actionItems);
}
private void PerformOneTimeSetUp()
{
var logScope = new LogScope();
try
{
_setupCommand.Execute(Context);
}
catch (Exception ex)
{
if (ex is NUnitException || ex is TargetInvocationException)
ex = ex.InnerException;
Result.RecordException(ex, FailureSite.SetUp);
}
if (logScope.AnyFailingLogs())
{
Result.RecordException(new UnhandledLogMessageException(logScope.FailingLogs.First()));
}
logScope.Dispose();
}
private IEnumerable RunChildren()
{
int childCount = Children.Count;
if (childCount == 0)
throw new InvalidOperationException("RunChildren called but item has no children");
_childTestCountdown = new CountdownEvent(childCount);
foreach (UnityWorkItem child in Children)
{
if (CheckForCancellation())
{
yield break;
}
var unityTestExecutionContext = new UnityTestExecutionContext(Context);
child.InitializeContext(unityTestExecutionContext);
var enumerable = child.Execute().GetEnumerator();
while (true)
{
if (!enumerable.MoveNext())
{
break;
}
ResultedInDomainReload |= child.ResultedInDomainReload;
yield return enumerable.Current;
}
_suiteResult.AddResult(child.Result);
childCount--;
}
if (childCount > 0)
{
while (childCount-- > 0)
CountDownChildTest();
}
}
private void CreateChildWorkItems()
{
Children = new List<UnityWorkItem>();
var testSuite = _suite;
foreach (ITest test in testSuite.Tests)
{
if (_childFilter.Pass(test))
{
var child = m_Factory.Create(test, _childFilter);
if (test.Properties.ContainsKey(PropertyNames.Order))
{
Children.Insert(0, child);
_countOrder++;
}
else
{
Children.Add(child);
}
}
}
if (_countOrder != 0) SortChildren();
}
private class UnityWorkItemOrderComparer : IComparer<UnityWorkItem>
{
public int Compare(UnityWorkItem x, UnityWorkItem y)
{
var xKey = int.MaxValue;
var yKey = int.MaxValue;
if (x.Test.Properties.ContainsKey(PropertyNames.Order))
xKey = (int)x.Test.Properties[PropertyNames.Order][0];
if (y.Test.Properties.ContainsKey(PropertyNames.Order))
yKey = (int)y.Test.Properties[PropertyNames.Order][0];
return xKey.CompareTo(yKey);
}
}
private void SortChildren()
{
Children.Sort(0, _countOrder, new UnityWorkItemOrderComparer());
}
private void SkipFixture(ResultState resultState, string message, string stackTrace)
{
Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.Filter(stackTrace));
SkipChildren(_suite, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message);
}
private void SkipChildren(TestSuite suite, ResultState resultState, string message)
{
foreach (Test child in suite.Tests)
{
if (_childFilter.Pass(child))
{
Context.Listener.TestStarted(child);
TestResult childResult = child.MakeTestResult();
childResult.SetResult(resultState, message);
_suiteResult.AddResult(childResult);
if (child.IsSuite)
SkipChildren((TestSuite)child, resultState, message);
Context.Listener.TestFinished(childResult);
}
}
}
private void PerformOneTimeTearDown()
{
_teardownCommand.Execute(Context);
}
private string GetSkipReason()
{
return (string)Test.Properties.Get(PropertyNames.SkipReason);
}
private string GetProviderStackTrace()
{
return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace);
}
private void CountDownChildTest()
{
_childTestCountdown.Signal();
if (_childTestCountdown.CurrentCount == 0)
{
if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested)
PerformOneTimeTearDown();
foreach (var childResult in _suiteResult.Children)
if (childResult.ResultState == ResultState.Cancelled)
{
this.Result.SetResult(ResultState.Cancelled, "Cancelled by user");
break;
}
WorkItemComplete();
}
}
public override void Cancel(bool force)
{
if (Children == null)
return;
foreach (var child in Children)
{
var ctx = child.Context;
if (ctx != null)
ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested;
if (child.State == WorkItemState.Running)
child.Cancel(force);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Internal.IL;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL.Stubs
{
public class ILCodeStream
{
private struct LabelAndOffset
{
public readonly ILCodeLabel Label;
public readonly int Offset;
public LabelAndOffset(ILCodeLabel label, int offset)
{
Label = label;
Offset = offset;
}
}
internal byte[] _instructions;
internal int _length;
internal int _startOffsetForLinking;
private ArrayBuilder<LabelAndOffset> _offsetsNeedingPatching;
private ILEmitter _emitter;
internal ILCodeStream(ILEmitter emitter)
{
_instructions = Array.Empty<byte>();
_startOffsetForLinking = -1;
_emitter = emitter;
}
private void EmitByte(byte b)
{
if (_instructions.Length == _length)
Array.Resize<byte>(ref _instructions, 2 * _instructions.Length + 10);
_instructions[_length++] = b;
}
private void EmitUInt16(ushort value)
{
EmitByte((byte)value);
EmitByte((byte)(value >> 8));
}
private void EmitUInt32(int value)
{
EmitByte((byte)value);
EmitByte((byte)(value >> 8));
EmitByte((byte)(value >> 16));
EmitByte((byte)(value >> 24));
}
public void Emit(ILOpcode opcode)
{
if ((int)opcode > 0x100)
EmitByte((byte)ILOpcode.prefix1);
EmitByte((byte)opcode);
}
public void Emit(ILOpcode opcode, ILToken token)
{
Emit(opcode);
EmitUInt32((int)token);
}
public void EmitLdc(int value)
{
if (-1 <= value && value <= 8)
{
Emit((ILOpcode)(ILOpcode.ldc_i4_0 + value));
}
else if (value == (sbyte)value)
{
Emit(ILOpcode.ldc_i4_s);
EmitByte((byte)value);
}
else
{
Emit(ILOpcode.ldc_i4);
EmitUInt32(value);
}
}
public void EmitLdArg(int index)
{
if (index < 4)
{
Emit((ILOpcode)(ILOpcode.ldarg_0 + index));
}
else
{
Emit(ILOpcode.ldarg);
EmitUInt16((ushort)index);
}
}
public void EmitLdArga(int index)
{
if (index < 0x100)
{
Emit(ILOpcode.ldarga_s);
EmitByte((byte)index);
}
else
{
Emit(ILOpcode.ldarga);
EmitUInt16((ushort)index);
}
}
public void EmitLdLoc(ILLocalVariable variable)
{
int index = (int)variable;
if (index < 4)
{
Emit((ILOpcode)(ILOpcode.ldloc_0 + index));
}
else if (index < 0x100)
{
Emit(ILOpcode.ldloc_s);
EmitByte((byte)index);
}
else
{
Emit(ILOpcode.ldloc);
EmitUInt16((ushort)index);
}
}
public void EmitLdLoca(ILLocalVariable variable)
{
int index = (int)variable;
if (index < 0x100)
{
Emit(ILOpcode.ldloca_s);
EmitByte((byte)index);
}
else
{
Emit(ILOpcode.ldloca);
EmitUInt16((ushort)index);
}
}
public void EmitStLoc(ILLocalVariable variable)
{
int index = (int)variable;
if (index < 4)
{
Emit((ILOpcode)(ILOpcode.stloc_0 + index));
}
else if (index < 0x100)
{
Emit(ILOpcode.stloc_s);
EmitByte((byte)index);
}
else
{
Emit(ILOpcode.stloc);
EmitUInt16((ushort)index);
}
}
public void Emit(ILOpcode opcode, ILCodeLabel label)
{
Debug.Assert(opcode == ILOpcode.br || opcode == ILOpcode.brfalse ||
opcode == ILOpcode.brtrue || opcode == ILOpcode.beq ||
opcode == ILOpcode.bge || opcode == ILOpcode.bgt ||
opcode == ILOpcode.ble || opcode == ILOpcode.blt ||
opcode == ILOpcode.bne_un || opcode == ILOpcode.bge_un ||
opcode == ILOpcode.bgt_un || opcode == ILOpcode.ble_un ||
opcode == ILOpcode.blt_un || opcode == ILOpcode.leave);
Emit(opcode);
_offsetsNeedingPatching.Add(new LabelAndOffset(label, _length));
EmitUInt32(4);
}
public void EmitSwitch(ILCodeLabel[] labels)
{
Emit(ILOpcode.switch_);
EmitUInt32(labels.Length);
int remainingBytes = labels.Length * 4;
foreach (var label in labels)
{
_offsetsNeedingPatching.Add(new LabelAndOffset(label, _length));
EmitUInt32(remainingBytes);
remainingBytes -= 4;
}
}
public void EmitUnaligned()
{
Emit(ILOpcode.unaligned);
EmitByte(1);
}
public void EmitLdInd(TypeDesc type)
{
switch (type.UnderlyingType.Category)
{
case TypeFlags.Byte:
case TypeFlags.SByte:
case TypeFlags.Boolean:
Emit(ILOpcode.ldind_i1);
break;
case TypeFlags.Char:
case TypeFlags.UInt16:
case TypeFlags.Int16:
Emit(ILOpcode.ldind_i2);
break;
case TypeFlags.UInt32:
case TypeFlags.Int32:
Emit(ILOpcode.ldind_i4);
break;
case TypeFlags.UInt64:
case TypeFlags.Int64:
Emit(ILOpcode.ldind_i8);
break;
case TypeFlags.Single:
Emit(ILOpcode.ldind_r4);
break;
case TypeFlags.Double:
Emit(ILOpcode.ldind_r8);
break;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
case TypeFlags.Pointer:
case TypeFlags.FunctionPointer:
Emit(ILOpcode.ldind_i);
break;
case TypeFlags.Array:
case TypeFlags.SzArray:
case TypeFlags.Class:
case TypeFlags.Interface:
Emit(ILOpcode.ldind_ref);
break;
case TypeFlags.ValueType:
case TypeFlags.Nullable:
Emit(ILOpcode.ldobj, _emitter.NewToken(type));
break;
default:
Debug.Assert(false, "Unexpected TypeDesc category");
break;
}
}
public void EmitStInd(TypeDesc type)
{
switch (type.UnderlyingType.Category)
{
case TypeFlags.Byte:
case TypeFlags.SByte:
case TypeFlags.Boolean:
Emit(ILOpcode.stind_i1);
break;
case TypeFlags.Char:
case TypeFlags.UInt16:
case TypeFlags.Int16:
Emit(ILOpcode.stind_i2);
break;
case TypeFlags.UInt32:
case TypeFlags.Int32:
Emit(ILOpcode.stind_i4);
break;
case TypeFlags.UInt64:
case TypeFlags.Int64:
Emit(ILOpcode.stind_i8);
break;
case TypeFlags.Single:
Emit(ILOpcode.stind_r4);
break;
case TypeFlags.Double:
Emit(ILOpcode.stind_r8);
break;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
case TypeFlags.Pointer:
case TypeFlags.FunctionPointer:
Emit(ILOpcode.stind_i);
break;
case TypeFlags.Array:
case TypeFlags.SzArray:
case TypeFlags.Class:
case TypeFlags.Interface:
Emit(ILOpcode.stind_ref);
break;
case TypeFlags.ValueType:
case TypeFlags.Nullable:
Emit(ILOpcode.stobj, _emitter.NewToken(type));
break;
default:
Debug.Assert(false, "Unexpected TypeDesc category");
break;
}
}
public void EmitStElem(TypeDesc type)
{
switch (type.UnderlyingType.Category)
{
case TypeFlags.Byte:
case TypeFlags.SByte:
case TypeFlags.Boolean:
Emit(ILOpcode.stelem_i1);
break;
case TypeFlags.Char:
case TypeFlags.UInt16:
case TypeFlags.Int16:
Emit(ILOpcode.stelem_i2);
break;
case TypeFlags.UInt32:
case TypeFlags.Int32:
Emit(ILOpcode.stelem_i4);
break;
case TypeFlags.UInt64:
case TypeFlags.Int64:
Emit(ILOpcode.stelem_i8);
break;
case TypeFlags.Single:
Emit(ILOpcode.stelem_r4);
break;
case TypeFlags.Double:
Emit(ILOpcode.stelem_r8);
break;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
case TypeFlags.Pointer:
case TypeFlags.FunctionPointer:
Emit(ILOpcode.stelem_i);
break;
case TypeFlags.Array:
case TypeFlags.SzArray:
case TypeFlags.Class:
case TypeFlags.Interface:
Emit(ILOpcode.stelem_ref);
break;
case TypeFlags.ValueType:
case TypeFlags.Nullable:
Emit(ILOpcode.stelem, _emitter.NewToken(type));
break;
default:
Debug.Assert(false, "Unexpected TypeDesc category");
break;
}
}
public void EmitLdElem(TypeDesc type)
{
switch (type.UnderlyingType.Category)
{
case TypeFlags.Byte:
case TypeFlags.SByte:
case TypeFlags.Boolean:
Emit(ILOpcode.ldelem_i1);
break;
case TypeFlags.Char:
case TypeFlags.UInt16:
case TypeFlags.Int16:
Emit(ILOpcode.ldelem_i2);
break;
case TypeFlags.UInt32:
case TypeFlags.Int32:
Emit(ILOpcode.ldelem_i4);
break;
case TypeFlags.UInt64:
case TypeFlags.Int64:
Emit(ILOpcode.ldelem_i8);
break;
case TypeFlags.Single:
Emit(ILOpcode.ldelem_r4);
break;
case TypeFlags.Double:
Emit(ILOpcode.ldelem_r8);
break;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
case TypeFlags.Pointer:
case TypeFlags.FunctionPointer:
Emit(ILOpcode.ldelem_i);
break;
case TypeFlags.Array:
case TypeFlags.SzArray:
case TypeFlags.Class:
case TypeFlags.Interface:
Emit(ILOpcode.ldelem_ref);
break;
case TypeFlags.ValueType:
case TypeFlags.Nullable:
Emit(ILOpcode.ldelem, _emitter.NewToken(type));
break;
default:
Debug.Assert(false, "Unexpected TypeDesc category");
break;
}
}
public void EmitLabel(ILCodeLabel label)
{
label.Place(this, _length);
}
internal void PatchLabels()
{
for (int i = 0; i < _offsetsNeedingPatching.Count; i++)
{
LabelAndOffset patch = _offsetsNeedingPatching[i];
Debug.Assert(patch.Label.IsPlaced);
Debug.Assert(_startOffsetForLinking > -1);
int offset = patch.Offset;
int delta = _instructions[offset + 3] << 24 |
_instructions[offset + 2] << 16 |
_instructions[offset + 1] << 8 |
_instructions[offset];
int value = patch.Label.AbsoluteOffset - _startOffsetForLinking - patch.Offset - delta;
_instructions[offset] = (byte)value;
_instructions[offset + 1] = (byte)(value >> 8);
_instructions[offset + 2] = (byte)(value >> 16);
_instructions[offset + 3] = (byte)(value >> 24);
}
}
}
/// <summary>
/// Represent a token. Use one of the overloads of <see cref="ILEmitter.NewToken"/>
/// to create a new token.
/// </summary>
public enum ILToken { }
/// <summary>
/// Represents a local variable. Use <see cref="ILEmitter.NewLocal"/> to create a new local variable.
/// </summary>
public enum ILLocalVariable { }
public class ILStubMethodIL : MethodIL
{
private byte[] _ilBytes;
private LocalVariableDefinition[] _locals;
private Object[] _tokens;
private MethodDesc _method;
public ILStubMethodIL(MethodDesc owningMethod, byte[] ilBytes, LocalVariableDefinition[] locals, Object[] tokens)
{
_ilBytes = ilBytes;
_locals = locals;
_tokens = tokens;
_method = owningMethod;
}
public ILStubMethodIL(ILStubMethodIL methodIL)
{
_ilBytes = methodIL._ilBytes;
_locals = methodIL._locals;
_tokens = methodIL._tokens;
_method = methodIL._method;
}
public override MethodDesc OwningMethod
{
get
{
return _method;
}
}
public override byte[] GetILBytes()
{
return _ilBytes;
}
public override int MaxStack
{
get
{
// Conservative estimate...
return _ilBytes.Length;
}
}
public override ILExceptionRegion[] GetExceptionRegions()
{
return Array.Empty<ILExceptionRegion>();
}
public override bool IsInitLocals
{
get
{
return true;
}
}
public override LocalVariableDefinition[] GetLocals()
{
return _locals;
}
public override Object GetObject(int token)
{
return _tokens[(token & 0xFFFFFF) - 1];
}
}
public class ILCodeLabel
{
private ILCodeStream _codeStream;
private int _offsetWithinCodeStream;
internal bool IsPlaced
{
get
{
return _codeStream != null;
}
}
internal int AbsoluteOffset
{
get
{
Debug.Assert(IsPlaced);
Debug.Assert(_codeStream._startOffsetForLinking >= 0);
return _codeStream._startOffsetForLinking + _offsetWithinCodeStream;
}
}
internal ILCodeLabel()
{
}
internal void Place(ILCodeStream codeStream, int offsetWithinCodeStream)
{
Debug.Assert(!IsPlaced);
_codeStream = codeStream;
_offsetWithinCodeStream = offsetWithinCodeStream;
}
}
public class ILEmitter
{
private ArrayBuilder<ILCodeStream> _codeStreams;
private ArrayBuilder<LocalVariableDefinition> _locals;
private ArrayBuilder<Object> _tokens;
public ILEmitter()
{
}
public ILCodeStream NewCodeStream()
{
ILCodeStream stream = new ILCodeStream(this);
_codeStreams.Add(stream);
return stream;
}
private ILToken NewToken(Object value, int tokenType)
{
Debug.Assert(value != null);
_tokens.Add(value);
return (ILToken)(_tokens.Count | tokenType);
}
public ILToken NewToken(TypeDesc value)
{
return NewToken(value, 0x01000000);
}
public ILToken NewToken(MethodDesc value)
{
return NewToken(value, 0x0a000000);
}
public ILToken NewToken(FieldDesc value)
{
return NewToken(value, 0x0a000000);
}
public ILToken NewToken(string value)
{
return NewToken(value, 0x70000000);
}
public ILToken NewToken(MethodSignature value)
{
return NewToken(value, 0x11000000);
}
public ILLocalVariable NewLocal(TypeDesc localType, bool isPinned = false)
{
int index = _locals.Count;
_locals.Add(new LocalVariableDefinition(localType, isPinned));
return (ILLocalVariable)index;
}
public ILCodeLabel NewCodeLabel()
{
var newLabel = new ILCodeLabel();
return newLabel;
}
public MethodIL Link(MethodDesc owningMethod)
{
int totalLength = 0;
for (int i = 0; i < _codeStreams.Count; i++)
{
ILCodeStream ilCodeStream = _codeStreams[i];
ilCodeStream._startOffsetForLinking = totalLength;
totalLength += ilCodeStream._length;
}
byte[] ilInstructions = new byte[totalLength];
int copiedLength = 0;
for (int i = 0; i < _codeStreams.Count; i++)
{
ILCodeStream ilCodeStream = _codeStreams[i];
ilCodeStream.PatchLabels();
Array.Copy(ilCodeStream._instructions, 0, ilInstructions, copiedLength, ilCodeStream._length);
copiedLength += ilCodeStream._length;
}
return new ILStubMethodIL(owningMethod, ilInstructions, _locals.ToArray(), _tokens.ToArray());
}
}
public abstract partial class ILStubMethod : MethodDesc
{
public abstract MethodIL EmitIL();
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WorkitemEventSubscriptionTool;
using System.Diagnostics;
using Microsoft.TeamFoundation.Proxy;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation;
using Microsoft.TeamFoundation.Framework.Client;
namespace SubscriptionManager
{
public partial class MainForm : Form
{
private int sortColumn = -1;
public MainForm()
{
// set default system font
this.Font = SystemInformation.MenuFont;
InitializeComponent();
this.Show();
Application.DoEvents();
connectButton_Click(this, null);
}
void DisplayServerInfo()
{
Boolean connected = (Shared.ProjectCollection != null);
subscribeButton.Enabled = connected;
unsubscribeButton.Enabled = connected;
refreshButton.Enabled = connected;
if (!connected)
{
textBoxExpression.Text = "";
textBoxSendTo.Text = "";
TFSNameLabel.Text = "(not connected)";
subscriptionslistView.Items.Clear();
return;
}
TFSNameLabel.Text = Shared.ProjectCollection.Name;
userTextBox.Text =
Shared.ProjectCollection.AuthorizedIdentity.Descriptor.Identifier;
}
private void ShowSubscriptions()
{
Cursor.Current = Cursors.WaitCursor;
subscriptionslistView.Items.Clear();
Shared.ConnectServer();
if (Shared.EventService == null)
{
return;
}
foreach (Subscription s in Shared.EventService.GetEventSubscriptions(userTextBox.Text))
{
ListViewItem item = new ListViewItem(s.ID.ToString());
item.SubItems.Add(s.EventType);
item.SubItems.Add(s.ConditionString);
item.SubItems.Add(s.DeliveryPreference.Type.ToString());
item.SubItems.Add(s.DeliveryPreference.Address);
subscriptionslistView.Items.Add(item);
}
Cursor.Current = Cursors.Default;
}
private void closeButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void refreshButton_Click(object sender, EventArgs e)
{
ShowSubscriptions();
}
private void deleteSubscriptionButton_Click(object sender, EventArgs e)
{
Unsubscribe();
}
private void Unsubscribe()
{
if (subscriptionslistView.SelectedItems.Count == 0)
{
MessageBox.Show("No subscriptions are selected.");
return;
}
foreach (ListViewItem item in subscriptionslistView.SelectedItems)
{
Shared.EventService.UnsubscribeEvent(Int32.Parse(item.Text));
}
ShowSubscriptions();
}
private void SubscribeButton_Click(object sender, EventArgs e)
{
if (textBoxSendTo.Text.Trim().Length == 0)
{
MessageBox.Show("There are no email/SOAP addresses in the Send To box.");
return;
}
//if (textBoxExpression.Text.Trim().Length == 0)
//{
// MessageBox.Show("No XPath expression has been entered.");
// return;
//}
if (Shared.ProjectCollection == null)
{
MainForm.DisplayException("No Team Foundation Server Selected");
return;
}
DeliveryPreference preference = new DeliveryPreference();
preference.Schedule = DeliverySchedule.Immediate;
switch (comboBoxFormat.Text)
{
case "Soap":
preference.Type = DeliveryType.Soap;
break;
case "PlainText":
preference.Type = DeliveryType.EmailPlaintext;
break;
default:
preference.Type = DeliveryType.EmailHtml;
break;
}
preference.Address = textBoxSendTo.Text;
string userName = Environment.UserDomainName + @"\" + Environment.UserName;
try
{
int id = Shared.EventService.SubscribeEvent(userName, eventComboBox.SelectedItem.ToString(), textBoxExpression.Text, preference);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error subscribing to event", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ShowSubscriptions();
}
private static void DisplayException(string message)
{
MessageBox.Show(message);
return;
}
private void buildButton_Click(object sender, EventArgs e)
{
XPathBuilderForm f = new XPathBuilderForm();
f.ShowDialog();
if (!String.IsNullOrEmpty(Shared.FormSharedData))
{
textBoxExpression.Text = Shared.FormSharedData;
}
}
private void subscriptionslistView_SelectedIndexChanged(object sender, EventArgs e)
{
if (subscriptionslistView.SelectedItems.Count == 0)
{
return;
}
textBoxExpression.Text = subscriptionslistView.SelectedItems[0].SubItems[2].Text;
textBoxSendTo.Text = subscriptionslistView.SelectedItems[0].SubItems[4].Text;
comboBoxFormat.SelectedItem = subscriptionslistView.SelectedItems[0].SubItems[3].Text;
eventComboBox.SelectedItem = subscriptionslistView.SelectedItems[0].SubItems[1].Text;
}
private void MainForm_Load(object sender, EventArgs e)
{
// necessary hack due to bug in WinForms splitter control
splitContainer1.Panel2MinSize = 310;
}
/// <summary>
/// Presents the DomainProjectPicker just as in Team Explorer to select the TFS Server and prompts for
/// login information if needed.
/// </summary>
protected void ChooseAppServer()
{
TeamProjectPicker dpp = new TeamProjectPicker();
if (dpp.ShowDialog() == DialogResult.OK)
{
try
{
Cursor.Current = Cursors.WaitCursor;
TfsTeamProjectCollection tfs = dpp.SelectedTeamProjectCollection;
tfs.Authenticate();
Shared.ProjectCollection = tfs;
}
catch (Exception ex)
{
DisplayException(ex.Message);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
DisplayServerInfo();
}
private void connectButton_Click(object sender, EventArgs e)
{
ChooseAppServer();
ShowSubscriptions();
}
private void userTextBox_TextChanged(object sender, EventArgs e)
{
this.refreshButton.Enabled = (userTextBox.Text != String.Empty);
}
#region "listview sorting"
private void subscriptionslistView_ColumnClick(object sender, ColumnClickEventArgs e)
{
Sort(subscriptionslistView, e);
}
private void Sort(ListView lv, ColumnClickEventArgs e)
{
// Determine whether the column is the same as the last column clicked.
if (e.Column != sortColumn)
{
// Set the sort column to the new column.
sortColumn = e.Column;
// Set the sort order to ascending by default.
lv.Sorting = SortOrder.Ascending;
}
else
{
// Determine what the last sort order was and change it.
if (lv.Sorting == SortOrder.Ascending)
lv.Sorting = SortOrder.Descending;
else
lv.Sorting = SortOrder.Ascending;
}
// Call the sort method to manually sort.
lv.Sort();
lv.ListViewItemSorter = new ListViewItemComparer(e.Column, lv.Sorting);
}
#endregion
private void unsubscribeToolStripMenuItem_Click(object sender, EventArgs e)
{
Unsubscribe();
}
}
#region "listview sorting"
// Implements the manual sorting of items by columns.
class ListViewItemComparer : System.Collections.IComparer
{
private int col;
private SortOrder order;
public ListViewItemComparer()
{
col = 0;
order = SortOrder.Ascending;
}
public ListViewItemComparer(int column, SortOrder order)
{
col = column;
this.order = order;
}
public int Compare(object x, object y)
{
int returnVal = -1;
returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
Debug.WriteLine(String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text));
if (order == SortOrder.Descending)
returnVal *= -1;
return returnVal;
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpContentHeadersTest
{
private HttpContentHeaders _headers;
public HttpContentHeadersTest()
{
_headers = new HttpContentHeaders(null);
}
[Fact]
public void ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
{
_headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15));
// Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
Assert.Throws<FormatException>(() => { _headers.Add("CoNtEnT-LeNgTh", "this is invalid"); });
}
[Fact]
public void ContentLength_ReadValue_TryComputeLengthInvoked()
{
_headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15));
// The delegate is invoked to return the length.
Assert.Equal(15, _headers.ContentLength);
Assert.Equal((long)15, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor));
// After getting the calculated content length, set it to null.
_headers.ContentLength = null;
Assert.Equal(null, _headers.ContentLength);
Assert.False(_headers.Contains(KnownHeaders.ContentLength.Name));
_headers.ContentLength = 27;
Assert.Equal((long)27, _headers.ContentLength);
Assert.Equal((long)27, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor));
}
[Fact]
public void ContentLength_SetCustomValue_TryComputeLengthNotInvoked()
{
_headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => { throw new ShouldNotBeInvokedException(); }));
_headers.ContentLength = 27;
Assert.Equal((long)27, _headers.ContentLength);
Assert.Equal((long)27, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor));
// After explicitly setting the content length, set it to null.
_headers.ContentLength = null;
Assert.Equal(null, _headers.ContentLength);
Assert.False(_headers.Contains(KnownHeaders.ContentLength.Name));
// Make sure the header gets serialized correctly
_headers.ContentLength = 12345;
Assert.Equal("12345", _headers.GetValues("Content-Length").First());
}
[Fact]
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => { throw new ShouldNotBeInvokedException(); }));
_headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n ");
Assert.Equal(68, _headers.ContentLength);
}
[Fact]
public void ContentType_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain");
value.CharSet = "utf-8";
value.Parameters.Add(new NameValueHeaderValue("custom", "value"));
Assert.Null(_headers.ContentType);
_headers.ContentType = value;
Assert.Same(value, _headers.ContentType);
_headers.ContentType = null;
Assert.Null(_headers.ContentType);
}
[Fact]
public void ContentType_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value");
MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain");
value.CharSet = "utf-8";
value.Parameters.Add(new NameValueHeaderValue("custom", "value"));
Assert.Equal(value, _headers.ContentType);
}
[Fact]
public void ContentType_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value, other/type");
Assert.Null(_headers.ContentType);
Assert.Equal(1, _headers.GetValues("Content-Type").Count());
Assert.Equal("text/plain; charset=utf-8; custom=value, other/type",
_headers.GetValues("Content-Type").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Type", ",text/plain"); // leading separator
Assert.Null(_headers.ContentType);
Assert.Equal(1, _headers.GetValues("Content-Type").Count());
Assert.Equal(",text/plain", _headers.GetValues("Content-Type").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Type", "text/plain,"); // trailing separator
Assert.Null(_headers.ContentType);
Assert.Equal(1, _headers.GetValues("Content-Type").Count());
Assert.Equal("text/plain,", _headers.GetValues("Content-Type").First());
}
[Fact]
public void ContentRange_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.ContentRange);
ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2, 3);
_headers.ContentRange = value;
Assert.Equal(value, _headers.ContentRange);
_headers.ContentRange = null;
Assert.Null(_headers.ContentRange);
}
[Fact]
public void ContentRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Range", "custom 1-2/*");
ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2);
value.Unit = "custom";
Assert.Equal(value, _headers.ContentRange);
}
[Fact]
public void ContentLocation_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.ContentLocation);
Uri expected = new Uri("http://example.com/path/");
_headers.ContentLocation = expected;
Assert.Equal(expected, _headers.ContentLocation);
_headers.ContentLocation = null;
Assert.Null(_headers.ContentLocation);
Assert.False(_headers.Contains("Content-Location"));
}
[Fact]
public void ContentLocation_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Location", " http://www.example.com/path/?q=v ");
Assert.Equal(new Uri("http://www.example.com/path/?q=v"), _headers.ContentLocation);
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Location", "/relative/uri/");
Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), _headers.ContentLocation);
}
[Fact]
public void ContentLocation_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Location", " http://example.com http://other");
Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentLocation.Descriptor));
Assert.Equal(1, _headers.GetValues("Content-Location").Count());
Assert.Equal(" http://example.com http://other", _headers.GetValues("Content-Location").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-Location", "http://host /other");
Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentLocation.Descriptor));
Assert.Equal(1, _headers.GetValues("Content-Location").Count());
Assert.Equal("http://host /other", _headers.GetValues("Content-Location").First());
}
[Fact]
public void ContentEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, _headers.ContentEncoding.Count);
_headers.ContentEncoding.Add("custom1");
_headers.ContentEncoding.Add("custom2");
Assert.Equal(2, _headers.ContentEncoding.Count);
Assert.Equal(2, _headers.GetValues("Content-Encoding").Count());
Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0));
Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1));
_headers.ContentEncoding.Clear();
Assert.Equal(0, _headers.ContentEncoding.Count);
Assert.False(_headers.Contains("Content-Encoding"));
}
[Fact]
public void ContentEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Encoding", ",custom1, custom2, custom3,");
Assert.Equal(3, _headers.ContentEncoding.Count);
Assert.Equal(3, _headers.GetValues("Content-Encoding").Count());
Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0));
Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1));
Assert.Equal("custom3", _headers.ContentEncoding.ElementAt(2));
_headers.ContentEncoding.Clear();
Assert.Equal(0, _headers.ContentEncoding.Count);
Assert.False(_headers.Contains("Content-Encoding"));
}
[Fact]
public void ContentEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Encoding", "custom1 custom2"); // no separator
Assert.Equal(0, _headers.ContentEncoding.Count);
Assert.Equal(1, _headers.GetValues("Content-Encoding").Count());
Assert.Equal("custom1 custom2", _headers.GetValues("Content-Encoding").First());
}
[Fact]
public void ContentLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, _headers.ContentLanguage.Count);
// Note that Content-Language for us is just a list of tokens. We don't verify if the format is a valid
// language tag. Users will pass the language tag to other classes like Encoding.GetEncoding() to retrieve
// an encoding. These classes will do not only syntax checking but also verify if the language tag exists.
_headers.ContentLanguage.Add("custom1");
_headers.ContentLanguage.Add("custom2");
Assert.Equal(2, _headers.ContentLanguage.Count);
Assert.Equal(2, _headers.GetValues("Content-Language").Count());
Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0));
Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1));
_headers.ContentLanguage.Clear();
Assert.Equal(0, _headers.ContentLanguage.Count);
Assert.False(_headers.Contains("Content-Language"));
}
[Fact]
public void ContentLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-Language", ",custom1, custom2, custom3,");
Assert.Equal(3, _headers.ContentLanguage.Count);
Assert.Equal(3, _headers.GetValues("Content-Language").Count());
Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0));
Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1));
Assert.Equal("custom3", _headers.ContentLanguage.ElementAt(2));
_headers.ContentLanguage.Clear();
Assert.Equal(0, _headers.ContentLanguage.Count);
Assert.False(_headers.Contains("Content-Language"));
}
[Fact]
public void ContentLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-Language", "custom1 custom2"); // no separator
Assert.Equal(0, _headers.ContentLanguage.Count);
Assert.Equal(1, _headers.GetValues("Content-Language").Count());
Assert.Equal("custom1 custom2", _headers.GetValues("Content-Language").First());
}
[Fact]
public void ContentMD5_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.ContentMD5);
byte[] expected = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
_headers.ContentMD5 = expected;
Assert.Equal(expected, _headers.ContentMD5); // must be the same object reference
// Make sure the header gets serialized correctly
Assert.Equal("AQIDBAUGBw==", _headers.GetValues("Content-MD5").First());
_headers.ContentMD5 = null;
Assert.Null(_headers.ContentMD5);
Assert.False(_headers.Contains("Content-MD5"));
}
[Fact]
public void ContentMD5_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Content-MD5", " lvpAKQ== ");
Assert.Equal(new byte[] { 150, 250, 64, 41 }, _headers.ContentMD5);
_headers.Clear();
_headers.TryAddWithoutValidation("Content-MD5", "+dIkS/MnOP8=");
Assert.Equal(new byte[] { 249, 210, 36, 75, 243, 39, 56, 255 }, _headers.ContentMD5);
}
[Fact]
public void ContentMD5_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Content-MD5", "AQ--");
Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentMD5.Descriptor));
Assert.Equal(1, _headers.GetValues("Content-MD5").Count());
Assert.Equal("AQ--", _headers.GetValues("Content-MD5").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Content-MD5", "AQ==, CD");
Assert.Null(_headers.GetParsedValues(KnownHeaders.ContentMD5.Descriptor));
Assert.Equal(1, _headers.GetValues("Content-MD5").Count());
Assert.Equal("AQ==, CD", _headers.GetValues("Content-MD5").First());
}
[Fact]
public void Allow_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, _headers.Allow.Count);
_headers.Allow.Add("custom1");
_headers.Allow.Add("custom2");
Assert.Equal(2, _headers.Allow.Count);
Assert.Equal(2, _headers.GetValues("Allow").Count());
Assert.Equal("custom1", _headers.Allow.ElementAt(0));
Assert.Equal("custom2", _headers.Allow.ElementAt(1));
_headers.Allow.Clear();
Assert.Equal(0, _headers.Allow.Count);
Assert.False(_headers.Contains("Allow"));
}
[Fact]
public void Allow_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Allow", ",custom1, custom2, custom3,");
Assert.Equal(3, _headers.Allow.Count);
Assert.Equal(3, _headers.GetValues("Allow").Count());
Assert.Equal("custom1", _headers.Allow.ElementAt(0));
Assert.Equal("custom2", _headers.Allow.ElementAt(1));
Assert.Equal("custom3", _headers.Allow.ElementAt(2));
_headers.Allow.Clear();
Assert.Equal(0, _headers.Allow.Count);
Assert.False(_headers.Contains("Allow"));
}
[Fact]
public void Allow_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Allow", "custom1 custom2"); // no separator
Assert.Equal(0, _headers.Allow.Count);
Assert.Equal(1, _headers.GetValues("Allow").Count());
Assert.Equal("custom1 custom2", _headers.GetValues("Allow").First());
}
[Fact]
public void Expires_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.Expires);
DateTimeOffset expected = DateTimeOffset.Now;
_headers.Expires = expected;
Assert.Equal(expected, _headers.Expires);
_headers.Expires = null;
Assert.Null(_headers.Expires);
Assert.False(_headers.Contains("Expires"));
}
[Fact]
public void Expires_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires);
_headers.Clear();
_headers.TryAddWithoutValidation("Expires", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires);
}
[Fact]
public void Expires_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(_headers.GetParsedValues(KnownHeaders.Expires.Descriptor));
Assert.Equal(1, _headers.GetValues("Expires").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Expires").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov ");
Assert.Null(_headers.GetParsedValues(KnownHeaders.Expires.Descriptor));
Assert.Equal(1, _headers.GetValues("Expires").Count());
Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Expires").First());
}
[Fact]
public void LastModified_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(_headers.LastModified);
DateTimeOffset expected = DateTimeOffset.Now;
_headers.LastModified = expected;
Assert.Equal(expected, _headers.LastModified);
_headers.LastModified = null;
Assert.Null(_headers.LastModified);
Assert.False(_headers.Contains("Last-Modified"));
}
[Fact]
public void LastModified_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified);
_headers.Clear();
_headers.TryAddWithoutValidation("Last-Modified", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified);
}
[Fact]
public void LastModified_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
_headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(_headers.GetParsedValues(KnownHeaders.LastModified.Descriptor));
Assert.Equal(1, _headers.GetValues("Last-Modified").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Last-Modified").First());
_headers.Clear();
_headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov ");
Assert.Null(_headers.GetParsedValues(KnownHeaders.LastModified.Descriptor));
Assert.Equal(1, _headers.GetValues("Last-Modified").Count());
Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Last-Modified").First());
}
[Fact]
public void InvalidHeaders_AddRequestAndResponseHeaders_Throw()
{
// Try adding request, response, and general _headers. Use different casing to make sure case-insensitive
// comparison is used.
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Ranges", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("age", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("ETag", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Location", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authenticate", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Retry-After", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Server", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Vary", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("WWW-Authenticate", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Charset", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Language", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Authorization", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Expect", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("From", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Host", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Match", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Modified-Since", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-None-Match", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Unmodified-Since", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Max-Forwards", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authorization", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Referer", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("TE", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("User-Agent", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Cache-Control", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Connection", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Date", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Pragma", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Trailer", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Transfer-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Upgrade", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Via", "v"); });
Assert.Throws<InvalidOperationException>(() => { _headers.Add("Warning", "v"); });
}
private sealed class ComputeLengthHttpContent : HttpContent
{
private readonly Func<long?> _tryComputeLength;
internal ComputeLengthHttpContent(Func<long?> tryComputeLength)
{
_tryComputeLength = tryComputeLength;
}
protected internal override bool TryComputeLength(out long length)
{
long? result = _tryComputeLength();
length = result.GetValueOrDefault();
return result.HasValue;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { throw new NotImplementedException(); }
}
}
}
| |
// 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.KeyVault.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Definition;
using Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Update;
using Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.UpdateDefinition;
using Microsoft.Azure.Management.KeyVault.Fluent.Models;
using Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition;
using Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System.Collections.Generic;
internal partial class VaultImpl
{
/// <summary>
/// Refreshes the resource to sync with Azure.
/// </summary>
/// <return>the refreshed resource</returns>
Microsoft.Azure.Management.KeyVault.Fluent.IVault Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IRefreshable<Microsoft.Azure.Management.KeyVault.Fluent.IVault>.Refresh()
{
return this.Refresh();
}
/// <summary>
/// Gets the Azure Active Directory tenant ID that should be used for
/// authenticating requests to the key vault.
/// </summary>
string Microsoft.Azure.Management.KeyVault.Fluent.IVault.TenantId
{
get
{
return this.TenantId;
}
}
/// <summary>
/// Gets whether Azure Resource Manager is permitted to
/// retrieve secrets from the key vault.
/// </summary>
bool Microsoft.Azure.Management.KeyVault.Fluent.IVault.EnabledForTemplateDeployment
{
get
{
return this.EnabledForTemplateDeployment;
}
}
/// <summary>
/// Gets whether Azure Disk Encryption is permitted to
/// retrieve secrets from the vault and unwrap keys.
/// </summary>
bool Microsoft.Azure.Management.KeyVault.Fluent.IVault.EnabledForDiskEncryption
{
get
{
return this.EnabledForDiskEncryption;
}
}
/// <summary>
/// Gets the URI of the vault for performing operations on keys and secrets.
/// </summary>
string Microsoft.Azure.Management.KeyVault.Fluent.IVault.VaultUri
{
get
{
return this.VaultUri;
}
}
/// <summary>
/// Gets SKU details.
/// </summary>
Microsoft.Azure.Management.KeyVault.Fluent.Models.Sku Microsoft.Azure.Management.KeyVault.Fluent.IVault.Sku
{
get
{
return this.Sku;
}
}
/// <summary>
/// Gets whether Azure Virtual Machines are permitted to
/// retrieve certificates stored as secrets from the key vault.
/// </summary>
bool Microsoft.Azure.Management.KeyVault.Fluent.IVault.EnabledForDeployment
{
get
{
return this.EnabledForDeployment;
}
}
/// <summary>
/// Gets an array of 0 to 16 identities that have access to the key vault. All
/// identities in the array must use the same tenant ID as the key vault's
/// tenant ID.
/// </summary>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.KeyVault.Fluent.IAccessPolicy> Microsoft.Azure.Management.KeyVault.Fluent.IVault.AccessPolicies
{
get
{
return this.AccessPolicies;
}
}
/// <summary>
/// Enable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithConfigurations.WithDiskEncryptionEnabled()
{
return this.WithDiskEncryptionEnabled();
}
/// <summary>
/// Enable Azure Resource Manager to retrieve secrets from the key vault.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithConfigurations.WithTemplateDeploymentEnabled()
{
return this.WithTemplateDeploymentEnabled();
}
/// <summary>
/// Enable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithConfigurations.WithDeploymentEnabled()
{
return this.WithDeploymentEnabled();
}
/// <summary>
/// Disable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithConfigurations.WithDeploymentDisabled()
{
return this.WithDeploymentDisabled();
}
/// <summary>
/// Disable Azure Resource Manager to retrieve secrets from the key vault.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithConfigurations.WithTemplateDeploymentDisabled()
{
return this.WithTemplateDeploymentDisabled();
}
/// <summary>
/// Disable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithConfigurations.WithDiskEncryptionDisabled()
{
return this.WithDiskEncryptionDisabled();
}
/// <summary>
/// Enable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys.
/// </summary>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithConfigurations.WithDiskEncryptionEnabled()
{
return this.WithDiskEncryptionEnabled();
}
/// <summary>
/// Enable Azure Resource Manager to retrieve secrets from the key vault.
/// </summary>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithConfigurations.WithTemplateDeploymentEnabled()
{
return this.WithTemplateDeploymentEnabled();
}
/// <summary>
/// Enable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault.
/// </summary>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithConfigurations.WithDeploymentEnabled()
{
return this.WithDeploymentEnabled();
}
/// <summary>
/// Disable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault.
/// </summary>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithConfigurations.WithDeploymentDisabled()
{
return this.WithDeploymentDisabled();
}
/// <summary>
/// Disable Azure Resource Manager to retrieve secrets from the key vault.
/// </summary>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithConfigurations.WithTemplateDeploymentDisabled()
{
return this.WithTemplateDeploymentDisabled();
}
/// <summary>
/// Disable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithConfigurations.WithDiskEncryptionDisabled()
{
return this.WithDiskEncryptionDisabled();
}
/// <summary>
/// Attach no access policy.
/// </summary>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithAccessPolicy.WithEmptyAccessPolicy()
{
return this.WithEmptyAccessPolicy();
}
/// <summary>
/// Begins the definition of a new access policy to be added to this key vault.
/// </summary>
/// <return>The first stage of the access policy definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Definition.IBlank<Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate> Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithAccessPolicy.DefineAccessPolicy()
{
return this.DefineAccessPolicy();
}
/// <summary>
/// Attach an existing access policy.
/// </summary>
/// <param name="accessPolicy">The existing access policy.</param>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithAccessPolicy.WithAccessPolicy(IAccessPolicy accessPolicy)
{
return this.WithAccessPolicy(accessPolicy);
}
/// <summary>
/// Remove an access policy from the access policy list.
/// </summary>
/// <param name="objectId">The object ID of the Active Directory identity the access policy is for.</param>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithAccessPolicy.WithoutAccessPolicy(string objectId)
{
return this.WithoutAccessPolicy(objectId);
}
/// <summary>
/// Begins the definition of a new access policy to be added to this key vault.
/// </summary>
/// <return>The first stage of the access policy definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.UpdateDefinition.IBlank<Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate> Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithAccessPolicy.DefineAccessPolicy()
{
return this.DefineAccessPolicy();
}
/// <summary>
/// Begins the update of an existing access policy attached to this key vault.
/// </summary>
/// <param name="objectId">The object ID of the Active Directory identity the access policy is for.</param>
/// <return>The update stage of the access policy definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithAccessPolicy.UpdateAccessPolicy(string objectId)
{
return this.UpdateAccessPolicy(objectId);
}
/// <summary>
/// Attach an existing access policy.
/// </summary>
/// <param name="accessPolicy">The existing access policy.</param>
/// <return>The key vault update stage.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Update.IWithAccessPolicy.WithAccessPolicy(IAccessPolicy accessPolicy)
{
return this.WithAccessPolicy(accessPolicy);
}
/// <summary>
/// Specifies the sku of the key vault.
/// </summary>
/// <param name="skuName">The sku.</param>
/// <return>The next stage of key vault definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithSku.WithSku(SkuName skuName)
{
return this.WithSku(skuName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Priority_Queue;
public class Camera
{
#region Members
private Vector2 position_;
private float scale_ = 50;
public int pixelSize { get; private set; } = -1;
//Rendering
public float AspectRatio => MainRenderTarget != null ? MainRenderTarget.Width / (float)MainRenderTarget.Height : 1;
public RenderTarget2D MainRenderTarget => renderTargets_[0].renderTarget;
public CameraRenderTarget GetRenderTarget(int idx) { return renderTargets_[idx]; }
private readonly List<CameraRenderTarget> renderTargets_ = new List<CameraRenderTarget>(); //Camera render buffers
private readonly SimplePriorityQueue<RenderLayer> renderLayers_ = new SimplePriorityQueue<RenderLayer>();
public static readonly SimplePriorityQueue<RenderLayer> DEFAULT_RENDER_PATH = new SimplePriorityQueue<RenderLayer>();
//Debug stuff
public static float DEBUGMULT = 1;//5;
public static float INVDEBUGMULT = 1;//1/5f;
#endregion
#region Constructors
public Camera(int pixelSize = 1, int renderTargetsAmount = 2)
{
for (int i = 0; i < renderTargetsAmount; i++)
{
renderTargets_.Add(new CameraRenderTarget(Color.Black));
}
SetPixelSize(pixelSize, false); //this also inits targets
#if ORIGIN_SHIFT
Entity.OnOriginShift += v =>
{
position_ += v;
};
#endif
}
#endregion
#region Rendering Objects
public class CameraRenderTarget
{
public Color clearColor;
public int cameraTargetPixelSize;
public RenderTarget2D renderTarget;
public BlendState blendMode = BlendState.Opaque;
public CameraRenderTarget(Color clearColor, int cameraTargetPixelSize = 1)
{
this.clearColor = clearColor;
this.cameraTargetPixelSize = cameraTargetPixelSize;
}
public void PrepareForDrawing(Point baseSize, bool clear = true)
{
if (renderTarget == null || renderTarget.Dimensions() != baseSize.DividedBy(cameraTargetPixelSize))
InitRT(baseSize);
Graphics.Device.SetRenderTarget(renderTarget);
Graphics.Device.SetStatesToDefault();
Graphics.Device.Clear(clearColor);
}
public static int inc = 0; //todo remove this
public void InitRT(Point baseSize)
{
Debug.WriteLine("Initting RenderTarget");
renderTarget?.Dispose();
renderTarget = new RenderTarget2D(Graphics.Device, baseSize.X / cameraTargetPixelSize, baseSize.Y / cameraTargetPixelSize, false, SurfaceFormat.Color, DepthFormat.Depth16, 0, RenderTargetUsage.PreserveContents);
renderTarget.Name = inc++.ToString();
}
}
public class RenderLayer
{
private readonly IRenderableSystem system_;
public int renderTargetIndex; //TODO FIXME
public RenderLayer(IRenderableSystem system, int renderTargetIndex)
{
system_ = system;
this.renderTargetIndex = renderTargetIndex;
}
public void Draw(Camera camera)
{
system_.Draw(camera, camera.GetRenderTarget(renderTargetIndex).renderTarget);
}
}
#endregion
#region Rendering
/// <summary> Adding layers will invalidate the default layers (fallback) </summary>
public void AddRenderLayer(IRenderableSystem system, int priority = 0, int layer = 0)
{
renderLayers_.Enqueue(new RenderLayer(system, layer), priority);
}
public List<Tuple<Texture2D, BlendState>> Render()
{
UpdateBeforeDrawing();
var viewportSize = Graphics.Viewport.Size().DividedBy(pixelSize);
List<Tuple<Texture2D, BlendState>> retList = new List<Tuple<Texture2D, BlendState>>();
//render all targets
for (var index = 0; index < renderTargets_.Count; index++)
{
CameraRenderTarget target = renderTargets_[index];
target.PrepareForDrawing(viewportSize);
var layers = renderLayers_.Count > 0 ? renderLayers_ : DEFAULT_RENDER_PATH;
//can't get ordered ienumerator :( TODO make extension or subclass
var queue = new SimplePriorityQueue<RenderLayer>();
foreach (RenderLayer layer in layers)
{
queue.Enqueue(layer, layers.GetPriority(layer));
}
while (queue.TryDequeue(out var command))
{
if(command.renderTargetIndex == index) //TODO optimize
command.Draw(this);
}
retList.Add(new Tuple<Texture2D, BlendState>(target.renderTarget, target.blendMode));
}
return retList;
// backBufferEffect_.Projection = globalMatrix;
// backBufferEffect_.Texture = atlas;
// backBufferEffect_.TextureEnabled = true;
// backBufferEffect_.CurrentTechnique.Passes[0].Apply();
}
public void UpdateBeforeDrawing()
{
if (MainRenderTarget.Width != Graphics.Viewport.Width / pixelSize || MainRenderTarget.Height != Graphics.Viewport.Height / pixelSize)
SetPixelSize(pixelSize);
}
public void UpdateRenderTargets()
{
var viewportSize = Graphics.Viewport.Size().DividedBy(pixelSize);
foreach (CameraRenderTarget rt in renderTargets_)
{
rt.InitRT(viewportSize);
}
scale_ = (float)MainRenderTarget.Height / Graphics.PixelsPerUnit;
}
#endregion
#region Geometrics
public RectF GetCullRect(float overscan = 0)
{
return new RectF(position_.X - overscan, position_.Y - overscan, (scale_ * AspectRatio + overscan * 2), (scale_ + overscan * 2));
}
public Matrix GetGlobalViewMatrix()
{
float x = Core.SnapToPixel(position_.X);
float y = Core.SnapToPixel(position_.Y);
return Matrix.CreateOrthographicOffCenter(
x, x + scale_ * AspectRatio * DEBUGMULT, //FIXME TODO
y, y + scale_ * DEBUGMULT,
-10, 10f);
}
public Matrix GetSpritesViewMatrix() //TODO invert y
{
/* client space viewport space
*
* 0,0 ------- 1,0 -1,1 ------- 1,1
* | | | |
* | [1,1]/2 | | 0,0 |
* | | | |
* 0,1 ------- 1,1 -1,-1------- 1,-1
*/
float x = Core.SnapToPixel(position_.X);
float y = Core.SnapToPixel(position_.Y);
float top = MainRenderTarget.Height + y * Graphics.PixelsPerUnit * INVDEBUGMULT; // we sum height to invert Y coords
float left = x * Graphics.PixelsPerUnit * INVDEBUGMULT;
return Matrix.CreateOrthographicOffCenter(left, left + 2, top + 2, top, -10, 10);
}
public void SetPixelSize(int size, bool recenter = true)
{
Vector2 oldCenter = recenter ? Center : Vector2.Zero; //skip getting center
int newPixelSize = MathUtils.ClampInt(size, 1, 10000);
if (pixelSize == newPixelSize) return;
pixelSize = newPixelSize;
UpdateRenderTargets();
if (recenter)
Center = oldCenter;
}
#endregion
#region Positional
public Vector2 Center
{
get => position_ + new Vector2(scale_ / 2 * AspectRatio, scale_ / 2f);
set => position_ = value - new Vector2(scale_ / 2 * AspectRatio, scale_ / 2f);
}
public void LerpCenterTo(Vector2 position, float t)
{
Center = MathUtils.Lerp(Center, position, t);
}
public Vector2 WorldMousePosition
{
get
{
Vector2 screenPos = Input.MousePosition;
Vector2 screenToWorldScaled = new Vector2(
screenPos.X / Graphics.Viewport.Width * scale_ * AspectRatio,
(Graphics.Viewport.Height - screenPos.Y) / Graphics.Viewport.Height * scale_
);
return position_ + screenToWorldScaled;
}
}
public Vector2 WorldToScreenPosition(Vector2 pos) //FIXME
{
float y = (pos.Y - position_.Y) / scale_;
float x = (pos.X - position_.X) / scale_ * AspectRatio;
return new Vector2(x, y);
}
#endregion
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2015 Tim Stair
//
// 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 CardMaker.Forms
{
partial class MDIElementControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.groupBoxElement = new System.Windows.Forms.GroupBox();
this.btnAssist = new System.Windows.Forms.Button();
this.tabControl = new System.Windows.Forms.TabControl();
this.tabPageFont = new System.Windows.Forms.TabPage();
this.checkBoxItalic = new System.Windows.Forms.CheckBox();
this.checkBoxBold = new System.Windows.Forms.CheckBox();
this.numericWordSpace = new System.Windows.Forms.NumericUpDown();
this.lblLineSpace = new System.Windows.Forms.Label();
this.numericLineSpace = new System.Windows.Forms.NumericUpDown();
this.checkFontAutoScale = new System.Windows.Forms.CheckBox();
this.comboFontName = new System.Windows.Forms.ComboBox();
this.panelFontColor = new System.Windows.Forms.Panel();
this.btnElementFontColor = new System.Windows.Forms.Button();
this.checkBoxUnderline = new System.Windows.Forms.CheckBox();
this.label12 = new System.Windows.Forms.Label();
this.checkBoxStrikeout = new System.Windows.Forms.CheckBox();
this.label13 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.comboTextHorizontalAlign = new System.Windows.Forms.ComboBox();
this.numericFontSize = new System.Windows.Forms.NumericUpDown();
this.comboTextVerticalAlign = new System.Windows.Forms.ComboBox();
this.lblWordSpacing = new System.Windows.Forms.Label();
this.tabPageShape = new System.Windows.Forms.TabPage();
this.panelShapeColor = new System.Windows.Forms.Panel();
this.comboShapeType = new System.Windows.Forms.ComboBox();
this.btnElementShapeColor = new System.Windows.Forms.Button();
this.propertyGridShape = new System.Windows.Forms.PropertyGrid();
this.tabPageGraphic = new System.Windows.Forms.TabPage();
this.checkKeepOriginalSize = new System.Windows.Forms.CheckBox();
this.btnSetSizeToImage = new System.Windows.Forms.Button();
this.label15 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.comboGraphicHorizontalAlign = new System.Windows.Forms.ComboBox();
this.comboGraphicVerticalAlign = new System.Windows.Forms.ComboBox();
this.checkLockAspect = new System.Windows.Forms.CheckBox();
this.groupBoxOutline = new System.Windows.Forms.GroupBox();
this.panelOutlineColor = new System.Windows.Forms.Panel();
this.label11 = new System.Windows.Forms.Label();
this.numericElementOutLineThickness = new System.Windows.Forms.NumericUpDown();
this.btnElementOutlineColor = new System.Windows.Forms.Button();
this.listViewElementColumns = new System.Windows.Forms.ListView();
this.label8 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.numericElementOpacity = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.numericElementRotation = new System.Windows.Forms.NumericUpDown();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBoxElementBorder = new System.Windows.Forms.GroupBox();
this.panelBorderColor = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.numericElementBorderThickness = new System.Windows.Forms.NumericUpDown();
this.btnElementBorderColor = new System.Windows.Forms.Button();
this.numericElementH = new System.Windows.Forms.NumericUpDown();
this.numericElementW = new System.Windows.Forms.NumericUpDown();
this.numericElementY = new System.Windows.Forms.NumericUpDown();
this.numericElementX = new System.Windows.Forms.NumericUpDown();
this.btnElementBrowseImage = new System.Windows.Forms.Button();
this.txtElementVariable = new System.Windows.Forms.TextBox();
this.comboElementType = new System.Windows.Forms.ComboBox();
this.contextMenuReferenceStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.contextMenuStripAssist = new System.Windows.Forms.ContextMenuStrip(this.components);
this.checkJustifiedText = new System.Windows.Forms.CheckBox();
this.groupBoxElement.SuspendLayout();
this.tabControl.SuspendLayout();
this.tabPageFont.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericWordSpace)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericLineSpace)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericFontSize)).BeginInit();
this.tabPageShape.SuspendLayout();
this.tabPageGraphic.SuspendLayout();
this.groupBoxOutline.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericElementOutLineThickness)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementOpacity)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementRotation)).BeginInit();
this.groupBoxElementBorder.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericElementBorderThickness)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementH)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementW)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementY)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementX)).BeginInit();
this.SuspendLayout();
//
// groupBoxElement
//
this.groupBoxElement.Controls.Add(this.btnAssist);
this.groupBoxElement.Controls.Add(this.tabControl);
this.groupBoxElement.Controls.Add(this.groupBoxOutline);
this.groupBoxElement.Controls.Add(this.listViewElementColumns);
this.groupBoxElement.Controls.Add(this.label8);
this.groupBoxElement.Controls.Add(this.label14);
this.groupBoxElement.Controls.Add(this.numericElementOpacity);
this.groupBoxElement.Controls.Add(this.label7);
this.groupBoxElement.Controls.Add(this.numericElementRotation);
this.groupBoxElement.Controls.Add(this.label6);
this.groupBoxElement.Controls.Add(this.label5);
this.groupBoxElement.Controls.Add(this.label4);
this.groupBoxElement.Controls.Add(this.label3);
this.groupBoxElement.Controls.Add(this.label2);
this.groupBoxElement.Controls.Add(this.groupBoxElementBorder);
this.groupBoxElement.Controls.Add(this.numericElementH);
this.groupBoxElement.Controls.Add(this.numericElementW);
this.groupBoxElement.Controls.Add(this.numericElementY);
this.groupBoxElement.Controls.Add(this.numericElementX);
this.groupBoxElement.Controls.Add(this.btnElementBrowseImage);
this.groupBoxElement.Controls.Add(this.txtElementVariable);
this.groupBoxElement.Controls.Add(this.comboElementType);
this.groupBoxElement.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBoxElement.Location = new System.Drawing.Point(0, 0);
this.groupBoxElement.Name = "groupBoxElement";
this.groupBoxElement.Size = new System.Drawing.Size(732, 312);
this.groupBoxElement.TabIndex = 11;
this.groupBoxElement.TabStop = false;
this.groupBoxElement.Text = "Element";
//
// btnAssist
//
this.btnAssist.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAssist.Location = new System.Drawing.Point(701, 264);
this.btnAssist.Name = "btnAssist";
this.btnAssist.Size = new System.Drawing.Size(25, 20);
this.btnAssist.TabIndex = 47;
this.btnAssist.Text = "+";
this.btnAssist.UseVisualStyleBackColor = true;
this.btnAssist.Click += new System.EventHandler(this.btnAssist_Click);
//
// tabControl
//
this.tabControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl.Controls.Add(this.tabPageFont);
this.tabControl.Controls.Add(this.tabPageShape);
this.tabControl.Controls.Add(this.tabPageGraphic);
this.tabControl.Location = new System.Drawing.Point(12, 97);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(714, 86);
this.tabControl.TabIndex = 46;
//
// tabPageFont
//
this.tabPageFont.Controls.Add(this.checkJustifiedText);
this.tabPageFont.Controls.Add(this.checkBoxItalic);
this.tabPageFont.Controls.Add(this.checkBoxBold);
this.tabPageFont.Controls.Add(this.numericWordSpace);
this.tabPageFont.Controls.Add(this.lblLineSpace);
this.tabPageFont.Controls.Add(this.numericLineSpace);
this.tabPageFont.Controls.Add(this.checkFontAutoScale);
this.tabPageFont.Controls.Add(this.comboFontName);
this.tabPageFont.Controls.Add(this.panelFontColor);
this.tabPageFont.Controls.Add(this.btnElementFontColor);
this.tabPageFont.Controls.Add(this.checkBoxUnderline);
this.tabPageFont.Controls.Add(this.label12);
this.tabPageFont.Controls.Add(this.checkBoxStrikeout);
this.tabPageFont.Controls.Add(this.label13);
this.tabPageFont.Controls.Add(this.label10);
this.tabPageFont.Controls.Add(this.comboTextHorizontalAlign);
this.tabPageFont.Controls.Add(this.numericFontSize);
this.tabPageFont.Controls.Add(this.comboTextVerticalAlign);
this.tabPageFont.Controls.Add(this.lblWordSpacing);
this.tabPageFont.Location = new System.Drawing.Point(4, 22);
this.tabPageFont.Name = "tabPageFont";
this.tabPageFont.Padding = new System.Windows.Forms.Padding(3);
this.tabPageFont.Size = new System.Drawing.Size(706, 60);
this.tabPageFont.TabIndex = 0;
this.tabPageFont.Text = "Font";
this.tabPageFont.UseVisualStyleBackColor = true;
//
// checkBoxItalic
//
this.checkBoxItalic.Location = new System.Drawing.Point(251, 7);
this.checkBoxItalic.Name = "checkBoxItalic";
this.checkBoxItalic.Size = new System.Drawing.Size(82, 20);
this.checkBoxItalic.TabIndex = 51;
this.checkBoxItalic.Text = "Italic";
this.checkBoxItalic.UseVisualStyleBackColor = true;
this.checkBoxItalic.CheckedChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// checkBoxBold
//
this.checkBoxBold.Location = new System.Drawing.Point(182, 7);
this.checkBoxBold.Name = "checkBoxBold";
this.checkBoxBold.Size = new System.Drawing.Size(71, 20);
this.checkBoxBold.TabIndex = 50;
this.checkBoxBold.Text = "Bold";
this.checkBoxBold.UseVisualStyleBackColor = true;
this.checkBoxBold.CheckedChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// numericWordSpace
//
this.numericWordSpace.Location = new System.Drawing.Point(421, 32);
this.numericWordSpace.Minimum = new decimal(new int[] {
100,
0,
0,
-2147483648});
this.numericWordSpace.Name = "numericWordSpace";
this.numericWordSpace.Size = new System.Drawing.Size(48, 20);
this.numericWordSpace.TabIndex = 48;
this.numericWordSpace.ValueChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// lblLineSpace
//
this.lblLineSpace.Location = new System.Drawing.Point(335, 6);
this.lblLineSpace.Name = "lblLineSpace";
this.lblLineSpace.Size = new System.Drawing.Size(80, 21);
this.lblLineSpace.TabIndex = 47;
this.lblLineSpace.Text = "Line Spacing:";
this.lblLineSpace.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// numericLineSpace
//
this.numericLineSpace.Location = new System.Drawing.Point(421, 5);
this.numericLineSpace.Maximum = new decimal(new int[] {
2000,
0,
0,
0});
this.numericLineSpace.Name = "numericLineSpace";
this.numericLineSpace.Size = new System.Drawing.Size(48, 20);
this.numericLineSpace.TabIndex = 46;
this.numericLineSpace.ValueChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// checkFontAutoScale
//
this.checkFontAutoScale.Location = new System.Drawing.Point(344, 32);
this.checkFontAutoScale.Name = "checkFontAutoScale";
this.checkFontAutoScale.Size = new System.Drawing.Size(97, 20);
this.checkFontAutoScale.TabIndex = 45;
this.checkFontAutoScale.Text = "Auto-Scale";
this.checkFontAutoScale.UseVisualStyleBackColor = true;
this.checkFontAutoScale.CheckedChanged += new System.EventHandler(this.HandleElementValueChange);
//
// comboFontName
//
this.comboFontName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboFontName.FormattingEnabled = true;
this.comboFontName.Location = new System.Drawing.Point(6, 6);
this.comboFontName.Name = "comboFontName";
this.comboFontName.Size = new System.Drawing.Size(170, 21);
this.comboFontName.TabIndex = 36;
this.comboFontName.SelectedIndexChanged += new System.EventHandler(this.comboFontName_SelectedIndexChanged);
//
// panelFontColor
//
this.panelFontColor.Location = new System.Drawing.Point(61, 32);
this.panelFontColor.Name = "panelFontColor";
this.panelFontColor.Size = new System.Drawing.Size(20, 20);
this.panelFontColor.TabIndex = 44;
//
// btnElementFontColor
//
this.btnElementFontColor.Location = new System.Drawing.Point(6, 32);
this.btnElementFontColor.Name = "btnElementFontColor";
this.btnElementFontColor.Size = new System.Drawing.Size(49, 20);
this.btnElementFontColor.TabIndex = 23;
this.btnElementFontColor.Text = "Color";
this.btnElementFontColor.UseVisualStyleBackColor = true;
this.btnElementFontColor.Click += new System.EventHandler(this.btnColor_Click);
//
// checkBoxUnderline
//
this.checkBoxUnderline.Location = new System.Drawing.Point(156, 32);
this.checkBoxUnderline.Name = "checkBoxUnderline";
this.checkBoxUnderline.Size = new System.Drawing.Size(82, 20);
this.checkBoxUnderline.TabIndex = 42;
this.checkBoxUnderline.Text = "Underline";
this.checkBoxUnderline.UseVisualStyleBackColor = true;
this.checkBoxUnderline.CheckedChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// label12
//
this.label12.Location = new System.Drawing.Point(465, 5);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(76, 21);
this.label12.TabIndex = 32;
this.label12.Text = "H Alignment:";
this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// checkBoxStrikeout
//
this.checkBoxStrikeout.Location = new System.Drawing.Point(87, 32);
this.checkBoxStrikeout.Name = "checkBoxStrikeout";
this.checkBoxStrikeout.Size = new System.Drawing.Size(71, 20);
this.checkBoxStrikeout.TabIndex = 41;
this.checkBoxStrikeout.Text = "Strikeout";
this.checkBoxStrikeout.UseVisualStyleBackColor = true;
this.checkBoxStrikeout.CheckedChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// label13
//
this.label13.Location = new System.Drawing.Point(465, 31);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(76, 21);
this.label13.TabIndex = 33;
this.label13.Text = "V Alignment:";
this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label10
//
this.label10.Location = new System.Drawing.Point(232, 30);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(32, 21);
this.label10.TabIndex = 40;
this.label10.Text = "Size:";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// comboTextHorizontalAlign
//
this.comboTextHorizontalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboTextHorizontalAlign.FormattingEnabled = true;
this.comboTextHorizontalAlign.Items.AddRange(new object[] {
"Left",
"Center",
"Right"});
this.comboTextHorizontalAlign.Location = new System.Drawing.Point(547, 5);
this.comboTextHorizontalAlign.Name = "comboTextHorizontalAlign";
this.comboTextHorizontalAlign.Size = new System.Drawing.Size(74, 21);
this.comboTextHorizontalAlign.TabIndex = 34;
this.comboTextHorizontalAlign.SelectedIndexChanged += new System.EventHandler(this.HandleElementValueChange);
//
// numericFontSize
//
this.numericFontSize.Location = new System.Drawing.Point(268, 31);
this.numericFontSize.Maximum = new decimal(new int[] {
2000,
0,
0,
0});
this.numericFontSize.Minimum = new decimal(new int[] {
6,
0,
0,
0});
this.numericFontSize.Name = "numericFontSize";
this.numericFontSize.Size = new System.Drawing.Size(48, 20);
this.numericFontSize.TabIndex = 39;
this.numericFontSize.Value = new decimal(new int[] {
10,
0,
0,
0});
this.numericFontSize.ValueChanged += new System.EventHandler(this.HandleFontSettingChange);
//
// comboTextVerticalAlign
//
this.comboTextVerticalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboTextVerticalAlign.FormattingEnabled = true;
this.comboTextVerticalAlign.Items.AddRange(new object[] {
"Top",
"Middle",
"Bottom"});
this.comboTextVerticalAlign.Location = new System.Drawing.Point(547, 32);
this.comboTextVerticalAlign.Name = "comboTextVerticalAlign";
this.comboTextVerticalAlign.Size = new System.Drawing.Size(74, 21);
this.comboTextVerticalAlign.TabIndex = 35;
this.comboTextVerticalAlign.SelectedIndexChanged += new System.EventHandler(this.HandleElementValueChange);
//
// lblWordSpacing
//
this.lblWordSpacing.Location = new System.Drawing.Point(335, 31);
this.lblWordSpacing.Name = "lblWordSpacing";
this.lblWordSpacing.Size = new System.Drawing.Size(80, 21);
this.lblWordSpacing.TabIndex = 49;
this.lblWordSpacing.Text = "Word Spacing:";
this.lblWordSpacing.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// tabPageShape
//
this.tabPageShape.Controls.Add(this.panelShapeColor);
this.tabPageShape.Controls.Add(this.comboShapeType);
this.tabPageShape.Controls.Add(this.btnElementShapeColor);
this.tabPageShape.Controls.Add(this.propertyGridShape);
this.tabPageShape.Location = new System.Drawing.Point(4, 22);
this.tabPageShape.Name = "tabPageShape";
this.tabPageShape.Padding = new System.Windows.Forms.Padding(3);
this.tabPageShape.Size = new System.Drawing.Size(628, 60);
this.tabPageShape.TabIndex = 1;
this.tabPageShape.Text = "Shape";
this.tabPageShape.UseVisualStyleBackColor = true;
//
// panelShapeColor
//
this.panelShapeColor.Location = new System.Drawing.Point(76, 34);
this.panelShapeColor.Name = "panelShapeColor";
this.panelShapeColor.Size = new System.Drawing.Size(20, 20);
this.panelShapeColor.TabIndex = 44;
//
// comboShapeType
//
this.comboShapeType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboShapeType.FormattingEnabled = true;
this.comboShapeType.Location = new System.Drawing.Point(3, 3);
this.comboShapeType.Name = "comboShapeType";
this.comboShapeType.Size = new System.Drawing.Size(121, 21);
this.comboShapeType.TabIndex = 26;
this.comboShapeType.SelectedIndexChanged += new System.EventHandler(this.comboShapeType_SelectedIndexChanged);
//
// btnElementShapeColor
//
this.btnElementShapeColor.Location = new System.Drawing.Point(3, 34);
this.btnElementShapeColor.Name = "btnElementShapeColor";
this.btnElementShapeColor.Size = new System.Drawing.Size(64, 20);
this.btnElementShapeColor.TabIndex = 24;
this.btnElementShapeColor.Text = "Color";
this.btnElementShapeColor.UseVisualStyleBackColor = true;
this.btnElementShapeColor.Click += new System.EventHandler(this.btnColor_Click);
//
// propertyGridShape
//
this.propertyGridShape.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.propertyGridShape.CategoryForeColor = System.Drawing.SystemColors.InactiveCaptionText;
this.propertyGridShape.HelpVisible = false;
this.propertyGridShape.Location = new System.Drawing.Point(130, 3);
this.propertyGridShape.Name = "propertyGridShape";
this.propertyGridShape.Size = new System.Drawing.Size(494, 52);
this.propertyGridShape.TabIndex = 25;
this.propertyGridShape.ToolbarVisible = false;
this.propertyGridShape.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.propertyGridShape_PropertyValueChanged);
//
// tabPageGraphic
//
this.tabPageGraphic.Controls.Add(this.checkKeepOriginalSize);
this.tabPageGraphic.Controls.Add(this.btnSetSizeToImage);
this.tabPageGraphic.Controls.Add(this.label15);
this.tabPageGraphic.Controls.Add(this.label16);
this.tabPageGraphic.Controls.Add(this.comboGraphicHorizontalAlign);
this.tabPageGraphic.Controls.Add(this.comboGraphicVerticalAlign);
this.tabPageGraphic.Controls.Add(this.checkLockAspect);
this.tabPageGraphic.Location = new System.Drawing.Point(4, 22);
this.tabPageGraphic.Name = "tabPageGraphic";
this.tabPageGraphic.Size = new System.Drawing.Size(628, 60);
this.tabPageGraphic.TabIndex = 2;
this.tabPageGraphic.Text = "Graphic";
this.tabPageGraphic.UseVisualStyleBackColor = true;
//
// checkKeepOriginalSize
//
this.checkKeepOriginalSize.Location = new System.Drawing.Point(150, 3);
this.checkKeepOriginalSize.Name = "checkKeepOriginalSize";
this.checkKeepOriginalSize.Size = new System.Drawing.Size(142, 24);
this.checkKeepOriginalSize.TabIndex = 41;
this.checkKeepOriginalSize.Text = "Keep Original Size";
this.checkKeepOriginalSize.UseVisualStyleBackColor = true;
this.checkKeepOriginalSize.CheckedChanged += new System.EventHandler(this.HandleElementValueChange);
//
// btnSetSizeToImage
//
this.btnSetSizeToImage.Location = new System.Drawing.Point(3, 32);
this.btnSetSizeToImage.Name = "btnSetSizeToImage";
this.btnSetSizeToImage.Size = new System.Drawing.Size(125, 23);
this.btnSetSizeToImage.TabIndex = 40;
this.btnSetSizeToImage.Text = "Set Size To Image";
this.btnSetSizeToImage.UseVisualStyleBackColor = true;
this.btnSetSizeToImage.Click += new System.EventHandler(this.btnSetSizeToImage_Click);
//
// label15
//
this.label15.Location = new System.Drawing.Point(461, 6);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(76, 21);
this.label15.TabIndex = 36;
this.label15.Text = "H Alignment:";
this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label16
//
this.label16.Location = new System.Drawing.Point(461, 32);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(76, 21);
this.label16.TabIndex = 37;
this.label16.Text = "V Alignment:";
this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// comboGraphicHorizontalAlign
//
this.comboGraphicHorizontalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboGraphicHorizontalAlign.FormattingEnabled = true;
this.comboGraphicHorizontalAlign.Items.AddRange(new object[] {
"Left",
"Center",
"Right"});
this.comboGraphicHorizontalAlign.Location = new System.Drawing.Point(543, 6);
this.comboGraphicHorizontalAlign.Name = "comboGraphicHorizontalAlign";
this.comboGraphicHorizontalAlign.Size = new System.Drawing.Size(74, 21);
this.comboGraphicHorizontalAlign.TabIndex = 38;
this.comboGraphicHorizontalAlign.SelectedIndexChanged += new System.EventHandler(this.HandleElementValueChange);
//
// comboGraphicVerticalAlign
//
this.comboGraphicVerticalAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboGraphicVerticalAlign.FormattingEnabled = true;
this.comboGraphicVerticalAlign.Items.AddRange(new object[] {
"Top",
"Middle",
"Bottom"});
this.comboGraphicVerticalAlign.Location = new System.Drawing.Point(543, 33);
this.comboGraphicVerticalAlign.Name = "comboGraphicVerticalAlign";
this.comboGraphicVerticalAlign.Size = new System.Drawing.Size(74, 21);
this.comboGraphicVerticalAlign.TabIndex = 39;
this.comboGraphicVerticalAlign.SelectedIndexChanged += new System.EventHandler(this.HandleElementValueChange);
//
// checkLockAspect
//
this.checkLockAspect.Location = new System.Drawing.Point(3, 3);
this.checkLockAspect.Name = "checkLockAspect";
this.checkLockAspect.Size = new System.Drawing.Size(142, 24);
this.checkLockAspect.TabIndex = 0;
this.checkLockAspect.Text = "Lock Aspect Ratio";
this.checkLockAspect.UseVisualStyleBackColor = true;
this.checkLockAspect.CheckedChanged += new System.EventHandler(this.HandleElementValueChange);
//
// groupBoxOutline
//
this.groupBoxOutline.Controls.Add(this.panelOutlineColor);
this.groupBoxOutline.Controls.Add(this.label11);
this.groupBoxOutline.Controls.Add(this.numericElementOutLineThickness);
this.groupBoxOutline.Controls.Add(this.btnElementOutlineColor);
this.groupBoxOutline.Location = new System.Drawing.Point(577, 19);
this.groupBoxOutline.Name = "groupBoxOutline";
this.groupBoxOutline.Size = new System.Drawing.Size(146, 74);
this.groupBoxOutline.TabIndex = 44;
this.groupBoxOutline.TabStop = false;
this.groupBoxOutline.Text = "Outline";
//
// panelOutlineColor
//
this.panelOutlineColor.Location = new System.Drawing.Point(80, 18);
this.panelOutlineColor.Name = "panelOutlineColor";
this.panelOutlineColor.Size = new System.Drawing.Size(53, 20);
this.panelOutlineColor.TabIndex = 43;
//
// label11
//
this.label11.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label11.Location = new System.Drawing.Point(6, 46);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(68, 20);
this.label11.TabIndex = 22;
this.label11.Text = "Thickness:";
this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// numericElementOutLineThickness
//
this.numericElementOutLineThickness.Location = new System.Drawing.Point(80, 46);
this.numericElementOutLineThickness.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericElementOutLineThickness.Name = "numericElementOutLineThickness";
this.numericElementOutLineThickness.Size = new System.Drawing.Size(53, 20);
this.numericElementOutLineThickness.TabIndex = 21;
this.numericElementOutLineThickness.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// btnElementOutlineColor
//
this.btnElementOutlineColor.Location = new System.Drawing.Point(9, 18);
this.btnElementOutlineColor.Name = "btnElementOutlineColor";
this.btnElementOutlineColor.Size = new System.Drawing.Size(65, 20);
this.btnElementOutlineColor.TabIndex = 20;
this.btnElementOutlineColor.Text = "Color";
this.btnElementOutlineColor.UseVisualStyleBackColor = true;
this.btnElementOutlineColor.Click += new System.EventHandler(this.btnColor_Click);
//
// listViewElementColumns
//
this.listViewElementColumns.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listViewElementColumns.FullRowSelect = true;
this.listViewElementColumns.GridLines = true;
this.listViewElementColumns.HideSelection = false;
this.listViewElementColumns.Location = new System.Drawing.Point(12, 189);
this.listViewElementColumns.MultiSelect = false;
this.listViewElementColumns.Name = "listViewElementColumns";
this.listViewElementColumns.Size = new System.Drawing.Size(714, 69);
this.listViewElementColumns.TabIndex = 35;
this.listViewElementColumns.UseCompatibleStateImageBehavior = false;
this.listViewElementColumns.View = System.Windows.Forms.View.Details;
this.listViewElementColumns.MouseClick += new System.Windows.Forms.MouseEventHandler(this.listViewElementColumns_MouseClick);
//
// label8
//
this.label8.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.label8.Location = new System.Drawing.Point(6, 264);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(61, 41);
this.label8.TabIndex = 34;
this.label8.Text = "Definition:";
this.label8.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label14
//
this.label14.Location = new System.Drawing.Point(228, 49);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(52, 20);
this.label14.TabIndex = 33;
this.label14.Text = "Opacity:";
this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// numericElementOpacity
//
this.numericElementOpacity.Location = new System.Drawing.Point(286, 49);
this.numericElementOpacity.Maximum = new decimal(new int[] {
255,
0,
0,
0});
this.numericElementOpacity.Name = "numericElementOpacity";
this.numericElementOpacity.Size = new System.Drawing.Size(56, 20);
this.numericElementOpacity.TabIndex = 32;
this.numericElementOpacity.Value = new decimal(new int[] {
255,
0,
0,
0});
this.numericElementOpacity.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// label7
//
this.label7.Location = new System.Drawing.Point(228, 73);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(52, 20);
this.label7.TabIndex = 31;
this.label7.Text = "Rotation:";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// numericElementRotation
//
this.numericElementRotation.Location = new System.Drawing.Point(286, 73);
this.numericElementRotation.Maximum = new decimal(new int[] {
359,
0,
0,
0});
this.numericElementRotation.Minimum = new decimal(new int[] {
359,
0,
0,
-2147483648});
this.numericElementRotation.Name = "numericElementRotation";
this.numericElementRotation.Size = new System.Drawing.Size(56, 20);
this.numericElementRotation.TabIndex = 30;
this.numericElementRotation.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// label6
//
this.label6.Location = new System.Drawing.Point(117, 73);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(43, 20);
this.label6.TabIndex = 29;
this.label6.Text = "Height:";
this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label5
//
this.label5.Location = new System.Drawing.Point(6, 49);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(43, 20);
this.label5.TabIndex = 28;
this.label5.Text = "X:";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label4
//
this.label4.Location = new System.Drawing.Point(117, 49);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(43, 20);
this.label4.TabIndex = 27;
this.label4.Text = "Y:";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label3
//
this.label3.Location = new System.Drawing.Point(6, 73);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(43, 20);
this.label3.TabIndex = 26;
this.label3.Text = "Width:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label2
//
this.label2.Location = new System.Drawing.Point(6, 18);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(43, 21);
this.label2.TabIndex = 23;
this.label2.Text = "Type:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// groupBoxElementBorder
//
this.groupBoxElementBorder.Controls.Add(this.panelBorderColor);
this.groupBoxElementBorder.Controls.Add(this.label1);
this.groupBoxElementBorder.Controls.Add(this.numericElementBorderThickness);
this.groupBoxElementBorder.Controls.Add(this.btnElementBorderColor);
this.groupBoxElementBorder.Location = new System.Drawing.Point(425, 19);
this.groupBoxElementBorder.Name = "groupBoxElementBorder";
this.groupBoxElementBorder.Size = new System.Drawing.Size(146, 74);
this.groupBoxElementBorder.TabIndex = 24;
this.groupBoxElementBorder.TabStop = false;
this.groupBoxElementBorder.Text = "Border";
//
// panelBorderColor
//
this.panelBorderColor.Location = new System.Drawing.Point(80, 18);
this.panelBorderColor.Name = "panelBorderColor";
this.panelBorderColor.Size = new System.Drawing.Size(53, 20);
this.panelBorderColor.TabIndex = 43;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label1.Location = new System.Drawing.Point(6, 46);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(68, 20);
this.label1.TabIndex = 22;
this.label1.Text = "Thickness:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// numericElementBorderThickness
//
this.numericElementBorderThickness.Location = new System.Drawing.Point(80, 46);
this.numericElementBorderThickness.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericElementBorderThickness.Name = "numericElementBorderThickness";
this.numericElementBorderThickness.Size = new System.Drawing.Size(53, 20);
this.numericElementBorderThickness.TabIndex = 21;
this.numericElementBorderThickness.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// btnElementBorderColor
//
this.btnElementBorderColor.Location = new System.Drawing.Point(9, 18);
this.btnElementBorderColor.Name = "btnElementBorderColor";
this.btnElementBorderColor.Size = new System.Drawing.Size(65, 20);
this.btnElementBorderColor.TabIndex = 20;
this.btnElementBorderColor.Text = "Color";
this.btnElementBorderColor.UseVisualStyleBackColor = true;
this.btnElementBorderColor.Click += new System.EventHandler(this.btnColor_Click);
//
// numericElementH
//
this.numericElementH.Location = new System.Drawing.Point(166, 73);
this.numericElementH.Maximum = new decimal(new int[] {
65536,
0,
0,
0});
this.numericElementH.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericElementH.Name = "numericElementH";
this.numericElementH.Size = new System.Drawing.Size(56, 20);
this.numericElementH.TabIndex = 17;
this.numericElementH.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericElementH.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// numericElementW
//
this.numericElementW.Location = new System.Drawing.Point(55, 73);
this.numericElementW.Maximum = new decimal(new int[] {
65536,
0,
0,
0});
this.numericElementW.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericElementW.Name = "numericElementW";
this.numericElementW.Size = new System.Drawing.Size(56, 20);
this.numericElementW.TabIndex = 16;
this.numericElementW.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericElementW.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// numericElementY
//
this.numericElementY.Location = new System.Drawing.Point(166, 49);
this.numericElementY.Maximum = new decimal(new int[] {
65536,
0,
0,
0});
this.numericElementY.Minimum = new decimal(new int[] {
65536,
0,
0,
-2147483648});
this.numericElementY.Name = "numericElementY";
this.numericElementY.Size = new System.Drawing.Size(56, 20);
this.numericElementY.TabIndex = 15;
this.numericElementY.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// numericElementX
//
this.numericElementX.Location = new System.Drawing.Point(55, 49);
this.numericElementX.Maximum = new decimal(new int[] {
65536,
0,
0,
0});
this.numericElementX.Minimum = new decimal(new int[] {
65536,
0,
0,
-2147483648});
this.numericElementX.Name = "numericElementX";
this.numericElementX.Size = new System.Drawing.Size(56, 20);
this.numericElementX.TabIndex = 14;
this.numericElementX.ValueChanged += new System.EventHandler(this.HandleElementValueChange);
//
// btnElementBrowseImage
//
this.btnElementBrowseImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnElementBrowseImage.Location = new System.Drawing.Point(701, 286);
this.btnElementBrowseImage.Name = "btnElementBrowseImage";
this.btnElementBrowseImage.Size = new System.Drawing.Size(25, 20);
this.btnElementBrowseImage.TabIndex = 12;
this.btnElementBrowseImage.Text = "...";
this.btnElementBrowseImage.UseVisualStyleBackColor = true;
this.btnElementBrowseImage.Click += new System.EventHandler(this.btnElementBrowseImage_Click);
//
// txtElementVariable
//
this.txtElementVariable.AcceptsReturn = true;
this.txtElementVariable.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtElementVariable.Font = new System.Drawing.Font("Lucida Console", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtElementVariable.HideSelection = false;
this.txtElementVariable.Location = new System.Drawing.Point(73, 264);
this.txtElementVariable.Multiline = true;
this.txtElementVariable.Name = "txtElementVariable";
this.txtElementVariable.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtElementVariable.Size = new System.Drawing.Size(622, 43);
this.txtElementVariable.TabIndex = 1;
this.txtElementVariable.WordWrap = false;
this.txtElementVariable.TextChanged += new System.EventHandler(this.HandleElementValueChange);
this.txtElementVariable.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtElementVariable_KeyDown);
//
// comboElementType
//
this.comboElementType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboElementType.FormattingEnabled = true;
this.comboElementType.Location = new System.Drawing.Point(55, 19);
this.comboElementType.Name = "comboElementType";
this.comboElementType.Size = new System.Drawing.Size(105, 21);
this.comboElementType.TabIndex = 0;
this.comboElementType.SelectedIndexChanged += new System.EventHandler(this.comboElementType_SelectedIndexChanged);
//
// contextMenuReferenceStrip
//
this.contextMenuReferenceStrip.Name = "contextMenuReferenceStrip";
this.contextMenuReferenceStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.contextMenuReferenceStrip.Size = new System.Drawing.Size(61, 4);
//
// contextMenuStripAssist
//
this.contextMenuStripAssist.Name = "contextMenuStripAssist";
this.contextMenuStripAssist.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.contextMenuStripAssist.Size = new System.Drawing.Size(61, 4);
//
// checkJustifiedText
//
this.checkJustifiedText.Location = new System.Drawing.Point(627, 6);
this.checkJustifiedText.Name = "checkJustifiedText";
this.checkJustifiedText.Size = new System.Drawing.Size(77, 20);
this.checkJustifiedText.TabIndex = 52;
this.checkJustifiedText.Text = "Justified";
this.checkJustifiedText.UseVisualStyleBackColor = true;
this.checkJustifiedText.CheckedChanged += new System.EventHandler(this.HandleElementValueChange);
//
// MDIElementControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(732, 312);
this.Controls.Add(this.groupBoxElement);
this.MinimumSize = new System.Drawing.Size(740, 339);
this.Name = "MDIElementControl";
this.ShowIcon = false;
this.Text = " Element Control";
this.Load += new System.EventHandler(this.MDIElementControl_Load);
this.groupBoxElement.ResumeLayout(false);
this.groupBoxElement.PerformLayout();
this.tabControl.ResumeLayout(false);
this.tabPageFont.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericWordSpace)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericLineSpace)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericFontSize)).EndInit();
this.tabPageShape.ResumeLayout(false);
this.tabPageGraphic.ResumeLayout(false);
this.groupBoxOutline.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericElementOutLineThickness)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementOpacity)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementRotation)).EndInit();
this.groupBoxElementBorder.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericElementBorderThickness)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementH)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementW)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementY)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericElementX)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBoxElement;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.NumericUpDown numericElementOpacity;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.NumericUpDown numericElementRotation;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox comboTextVerticalAlign;
private System.Windows.Forms.ComboBox comboTextHorizontalAlign;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Button btnElementFontColor;
private System.Windows.Forms.GroupBox groupBoxElementBorder;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numericElementBorderThickness;
private System.Windows.Forms.Button btnElementBorderColor;
private System.Windows.Forms.Button btnElementBrowseImage;
private System.Windows.Forms.TextBox txtElementVariable;
private System.Windows.Forms.ComboBox comboElementType;
private System.Windows.Forms.NumericUpDown numericElementH;
private System.Windows.Forms.NumericUpDown numericElementW;
private System.Windows.Forms.NumericUpDown numericElementY;
private System.Windows.Forms.NumericUpDown numericElementX;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.ListView listViewElementColumns;
private System.Windows.Forms.ComboBox comboFontName;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.NumericUpDown numericFontSize;
private System.Windows.Forms.CheckBox checkBoxUnderline;
private System.Windows.Forms.CheckBox checkBoxStrikeout;
private System.Windows.Forms.Button btnElementShapeColor;
private System.Windows.Forms.PropertyGrid propertyGridShape;
private System.Windows.Forms.ComboBox comboShapeType;
private System.Windows.Forms.Panel panelBorderColor;
private System.Windows.Forms.Panel panelShapeColor;
private System.Windows.Forms.Panel panelFontColor;
private System.Windows.Forms.GroupBox groupBoxOutline;
private System.Windows.Forms.Panel panelOutlineColor;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.NumericUpDown numericElementOutLineThickness;
private System.Windows.Forms.Button btnElementOutlineColor;
private System.Windows.Forms.CheckBox checkFontAutoScale;
private System.Windows.Forms.CheckBox checkLockAspect;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage tabPageFont;
private System.Windows.Forms.TabPage tabPageShape;
private System.Windows.Forms.TabPage tabPageGraphic;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.ComboBox comboGraphicHorizontalAlign;
private System.Windows.Forms.ComboBox comboGraphicVerticalAlign;
private System.Windows.Forms.Label lblLineSpace;
private System.Windows.Forms.NumericUpDown numericLineSpace;
private System.Windows.Forms.NumericUpDown numericWordSpace;
private System.Windows.Forms.Label lblWordSpacing;
private System.Windows.Forms.Button btnSetSizeToImage;
private System.Windows.Forms.CheckBox checkBoxItalic;
private System.Windows.Forms.CheckBox checkBoxBold;
private System.Windows.Forms.ContextMenuStrip contextMenuReferenceStrip;
private System.Windows.Forms.ContextMenuStrip contextMenuStripAssist;
private System.Windows.Forms.Button btnAssist;
private System.Windows.Forms.CheckBox checkKeepOriginalSize;
private System.Windows.Forms.CheckBox checkJustifiedText;
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
namespace OpenLiveWriter.CoreServices
{
public class CommandLineOptions
{
private static int errorCode = 100;
private static readonly ErrorType ERROR_UNPARSEABLE_ARG = new ErrorType(errorCode++, "The argument \"{0}\" was not understood.");
private static readonly ErrorType ERROR_UNRECOGNIZED_ARG = new ErrorType(errorCode++, "The argument \"{0}\" was not understood.");
private static readonly ErrorType ERROR_ARG_REQUIRED = new ErrorType(errorCode++, "The /{1} argument is required.");
private static readonly ErrorType ERROR_VALUE_REQUIRED = new ErrorType(errorCode++, "The /{1} argument needs a value.");
private static readonly ErrorType ERROR_FLAG_HAD_VALUE = new ErrorType(errorCode++, "The /{1} argument does not take a value.");
private static readonly ErrorType ERROR_NOT_AN_INT = new ErrorType(errorCode++, "The argument value \"{2}\" was not a valid integer.");
private static readonly ErrorType ERROR_NOT_HEX_INT = new ErrorType(errorCode++, "The argument value \"{2}\" was not a valid hex value.");
private static readonly ErrorType ERROR_TOO_FEW_UNNAMED_ARGS = new ErrorType(errorCode++, "Not enough arguments were provided.");
private static readonly ErrorType ERROR_TOO_MANY_UNNAMED_ARGS = new ErrorType(errorCode++, "The argument \"{0}\" was unexpected--too many arguments.");
private readonly bool _caseSensitive;
private readonly int _minUnnamedArgCount;
private readonly int _maxUnnamedArgCount;
private ArrayList _required = new ArrayList();
private Hashtable _args = new Hashtable();
private ArrayList _unnamedArgs = new ArrayList();
private Hashtable _values = new Hashtable();
private HashSet _argsPresent = new HashSet();
private ArrayList _errors = new ArrayList();
public CommandLineOptions(params ArgSpec[] args) : this(false, 0, int.MaxValue, args)
{
}
public CommandLineOptions(bool caseSensitive, int minUnnamedArgCount, int maxUnnamedArgCount, params ArgSpec[] args)
{
_caseSensitive = caseSensitive;
_maxUnnamedArgCount = maxUnnamedArgCount;
_minUnnamedArgCount = minUnnamedArgCount;
foreach (ArgSpec arg in args)
{
string name = arg.Name;
NormalizeName(ref name);
ValidateArgName(name);
if (arg.IsRequired)
_required.Add(name);
_args.Add(name, arg);
}
}
public bool IsArgPresent(string name)
{
NormalizeName(ref name);
return _values.ContainsKey(name);
}
public bool GetFlagValue(string name, bool defaultValue)
{
return (bool)GetValue(name, defaultValue);
}
public long GetIntegerValue(string name, int defaultValue)
{
return (long) GetValue(name, defaultValue);
}
public object[] GetValues(string name)
{
NormalizeName(ref name);
ArgSpec argSpec = (ArgSpec)_args[name];
Type t = argSpec.IsInteger ? typeof(long) :
argSpec.IsHexNumber ? typeof(long) :
typeof(string);
return (object[]) ((ArrayList) GetValue(name, new ArrayList())).ToArray(t);
}
public object GetValue(string name, object defaultValue)
{
NormalizeName(ref name);
if (!_values.ContainsKey(name))
return defaultValue;
else
return _values[name];
}
public string[] UnnamedArgs
{
get
{
return (string[]) _unnamedArgs.ToArray(typeof (string));
}
}
public int UnnamedArgCount
{
get
{
return _unnamedArgs.Count;
}
}
public string GetUnnamedArg(int index, string defaultValue)
{
if (index < _unnamedArgs.Count)
return (string) _unnamedArgs[index];
else
return defaultValue;
}
/// <summary>
/// Parse the arguments, returning true if everything was kosher
/// and false if not.
/// </summary>
/// <param name="args">Command line arguments, as passed to Main(string[] args) or Environment.GetCommandLineArgs()</param>
/// <param name="stopOnFirstError">Return false at the first error encountered.</param>
/// <returns>True if arguments were valid and all required arguments were provided.</returns>
public bool Parse(string[] args, bool stopOnFirstError)
{
_values.Clear();
_errors.Clear();
_argsPresent.Clear();
_unnamedArgs.Clear();
bool success = true;
for (int i = 0; i < args.Length && (!stopOnFirstError || success); i++)
success &= ParseArg(args[i]);
if (stopOnFirstError && !success)
return false;
if (_minUnnamedArgCount > _unnamedArgs.Count)
success &= AddError(ERROR_TOO_FEW_UNNAMED_ARGS, null, null, null);
if (stopOnFirstError && !success)
return false;
for (int i = 0; i < _required.Count && (!stopOnFirstError || success); i++)
{
string requiredArg = (string)_required[i];
if (!_argsPresent.Contains(requiredArg))
success &= AddError(ERROR_ARG_REQUIRED, null, requiredArg, null);
}
if (stopOnFirstError && !success)
return false;
return success;
}
/// <summary>
/// The errors that were found during the parse.
/// </summary>
public Error[] Errors
{
get
{
return (Error[]) _errors.ToArray(typeof (Error));
}
}
/// <summary>
/// List of errors that were found during the parse.
/// </summary>
public string ErrorMessage
{
get
{
Error[] errs = Errors;
if (errs.Length == 0)
return null;
return StringHelper.Join(errs, "\r\n");
}
}
/// <summary>
/// Parse an individual argument; returns false if error.
/// </summary>
private bool ParseArg(string arg)
{
arg = arg.Trim();
if (arg.Length == 0)
return true;
if (!arg.StartsWith("/", StringComparison.OrdinalIgnoreCase))
{
if (_unnamedArgs.Count >= _maxUnnamedArgCount)
return AddError(ERROR_TOO_MANY_UNNAMED_ARGS, arg, null, null);
_unnamedArgs.Add(arg);
return true;
}
else
{
return ParseNamedArg(arg);
}
}
private bool ParseNamedArg(string arg)
{
Match m = Regex.Match(arg, @"^/(-)?([a-z0-9]+)(?:\:(.+))?$");
if (!m.Success)
return AddError(ERROR_UNPARSEABLE_ARG, arg, null, null);
bool unset = m.Groups[1].Success;
string argName = m.Groups[2].Value;
string argValue = (m.Groups[3].Success) ? m.Groups[3].Value : null;
NormalizeName(ref argName);
_argsPresent.Add(argName);
ArgSpec argSpec = (ArgSpec)_args[argName];
ErrorType err =
(argSpec == null) ? ERROR_UNRECOGNIZED_ARG :
(argSpec.IsFlag && argValue != null) ? ERROR_FLAG_HAD_VALUE :
(argSpec.IsRequired && argValue == null) ? ERROR_VALUE_REQUIRED :
(!argSpec.IsUnsettable && unset) ? ERROR_UNRECOGNIZED_ARG :
null;
if (err != null)
return AddError(err, arg, argName, argValue);
object parsedValue = null;
if (argSpec.IsFlag)
{
parsedValue = !unset;
}
else if (argSpec.IsInteger)
{
try { parsedValue = long.Parse(argValue, CultureInfo.InvariantCulture); }
catch { err = ERROR_NOT_AN_INT; }
}
else if (argSpec.IsHexNumber)
{
try { parsedValue = long.Parse(argValue, NumberStyles.AllowHexSpecifier | NumberStyles.HexNumber, CultureInfo.InvariantCulture); }
catch { err = ERROR_NOT_HEX_INT; }
}
else
{
parsedValue = argValue;
}
if (err != null)
return AddError(err, arg, argName, argValue);
if (!argSpec.IsMultiple)
{
_values[argName] = parsedValue;
}
else
{
ArrayList values = (ArrayList)_values[argName];
if (values == null)
{
values = new ArrayList();
_values[argName] = values;
}
values.Add(parsedValue);
}
return true;
}
private bool AddError(ErrorType error, string arg, string argName, string argValue)
{
_errors.Add(new Error(error, arg, argName, argValue));
return false;
}
private void NormalizeName(ref string name)
{
if (!_caseSensitive)
name = name.ToLower(CultureInfo.InvariantCulture);
}
private void ValidateArgName(string name)
{
if (!Regex.IsMatch(name, "^[a-z0-9]+$", RegexOptions.IgnoreCase))
throw new ArgumentException("The argument name \"" + name + "\" is invalid; only letters and numbers may be used.");
}
public class ErrorType
{
private int _errorCode;
private string _messageFormat;
public ErrorType(int errorCode, string message)
{
_errorCode = errorCode;
_messageFormat = message;
}
public int ErrorCode
{
get { return _errorCode; }
}
public string MessageFormat
{
get { return _messageFormat; }
}
public override bool Equals(object obj)
{
ErrorType other = obj as ErrorType;
return (object)other != null && other._errorCode == _errorCode;
}
public override int GetHashCode()
{
return _errorCode;
}
public static bool operator==(ErrorType e1, ErrorType e2)
{
if (null == (object)e1 ^ null == (object)e2)
return false;
if ((object)e1 == null)
return true;
return e1.Equals(e2);
}
public static bool operator!=(ErrorType e1, ErrorType e2)
{
return !(e1 == e2);
}
}
public class Error
{
private readonly ErrorType _errorType;
private readonly string _arg;
private readonly string _argName;
private readonly string _argValue;
public Error(ErrorType errorType, string arg, string argName, string argValue)
{
_errorType = errorType;
_arg = arg;
_argName = argName;
_argValue = argValue;
}
public ErrorType ErrorType
{
get { return _errorType; }
}
public string Message
{
get
{
return string.Format(CultureInfo.CurrentCulture, _errorType.MessageFormat, _arg, _argName, _argValue);
}
}
public override string ToString()
{
return Message;
}
}
}
/// <summary>
/// Describes a named argument--its name, options, and description.
///
/// Examples:
///
/// /foo
/// /bar:10
/// /baz:C30BD034
/// /blurdyboop:hello
/// /-recursive
/// </summary>
public class ArgSpec
{
[Flags]
public enum Options
{
Default = 0, // optional, string value required, not unsettable, single (last-one-wins)
Required = 1, // argument is required
Flag = 2, // value is not allowed
ValueOptional = 4, // value is not required
Unsettable = 8, // "-" prefix is allowed (e.g. /-foo), meaning negation
Integer = 0x10, // value must be a decimal integer
HexNumber = 0x20, // value must be a hex value
Multiple = 0x40 // may be used multiple times in one command line
}
private readonly string _name;
private readonly Options _options;
private readonly string _description;
public ArgSpec(string name, Options options, string description)
{
_name = name;
_options = options;
_description = description;
ValidateOptions();
}
[Conditional("DEBUG")]
private void ValidateOptions()
{
if (IsFlag && (IsValueOptional || IsInteger || IsHexNumber || IsMultiple))
throw new ArgumentException("Invalid combination of arg options: Flag cannot be combined with ValueOptional, Integer, HexNumber, or Multiple");
if (!IsFlag && IsUnsettable)
throw new ArgumentException("Invalid combination of arg options: Flag cannot be combined with Unsettable");
if (IsInteger && IsHexNumber)
throw new ArgumentException("Invalid combination of arg options: Integer cannot be combined with HexNumber");
}
public string Name
{
get { return _name; }
}
public string Description
{
get { return _description; }
}
public bool IsRequired { get { return Test(Options.Required); }}
public bool IsFlag { get { return Test(Options.Flag); }}
public bool IsValueOptional { get { return Test(Options.ValueOptional); }}
public bool IsUnsettable { get { return Test(Options.Unsettable); }}
public bool IsInteger { get { return Test(Options.Integer); }}
public bool IsHexNumber { get { return Test(Options.HexNumber); }}
public bool IsMultiple { get { return Test(Options.Multiple); }}
private bool Test(Options options)
{
return (_options & options) == options;
}
}
}
| |
/**
* Portions Copyright (c) Microsoft Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
* PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
#pragma warning disable 1998
namespace Edge.Tests
{
public class Startup
{
string ValidateMarshalNodeJsToNet(dynamic input, bool expectFunction)
{
string result = "yes";
var data = (IDictionary<string, object>)input;
try
{
int a = (int)data["a"];
if (a != 1) throw new Exception("a is not 1");
double b = (double)data["b"];
if (b != 3.1415) throw new Exception("b is not 3.1415");
string c = (string)data["c"];
if (c != "foo") throw new Exception("c is not foo");
bool d = (bool)data["d"];
if (d != true) throw new Exception("d is not true");
bool e = (bool)data["e"];
if (e != false) throw new Exception("e is not false");
byte[] f = (byte[])data["f"];
if (f.Length != 10) throw new Exception("f.length is not 10");
object[] g = (object[])data["g"];
if (g.Length != 2) throw new Exception("g.length is not 2");
if ((int)g[0] != 1) throw new Exception("g[0] is not 1");
if ((string)g[1] != "foo") throw new Exception("g[1] is not foo");
IDictionary<string, object> h = (IDictionary<string,object>)data["h"];
if ((string)h["a"] != "foo") throw new Exception("h.a is not foo");
if ((int)h["b"] != 12) throw new Exception("h.b is not 12");
if (expectFunction)
{
var i = data["i"] as Func<object, Task<object>>;
if (i == null) throw new Exception("i is not a Func<object,Task<object>>");
}
}
catch (Exception e)
{
result = e.ToString();
}
try
{
int a = input.a;
if (a != 1) throw new Exception("dynamic a is not 1");
double b = input.b;
if (b != 3.1415) throw new Exception("dynamic b is not 3.1415");
string c = input.c;
if (c != "foo") throw new Exception("dynamic c is not foo");
bool d = input.d;
if (d != true) throw new Exception("dynamic d is not true");
bool e = input.e;
if (e != false) throw new Exception("dynamic e is not false");
byte[] f = input.f;
if (f.Length != 10) throw new Exception("dynamic f.length is not 10");
dynamic[] g = input.g;
if (g.Length != 2) throw new Exception("dynamic g.length is not 2");
if ((int)g[0] != 1) throw new Exception("dynamic g[0] is not 1");
if ((string)g[1] != "foo") throw new Exception("dynamic g[1] is not foo");
dynamic h = input.h;
if ((string)h.a != "foo") throw new Exception("dynamic h.a is not foo");
if ((int)h.b != 12) throw new Exception("dynamic h.b is not 12");
if (expectFunction)
{
var i = input.i as Func<object, Task<object>>;
if (i == null) throw new Exception("dynamic i is not a Func<object,Task<object>>");
}
}
catch (Exception e)
{
result = e.ToString();
}
return result;
}
public Task<object> Invoke(dynamic input)
{
return Task.FromResult<object>(".NET welcomes " + input);
}
public Task<object> MarshalIn(dynamic input)
{
string result = ValidateMarshalNodeJsToNet(input, true);
return Task.FromResult<object>(result);
}
public Task<object> MarshalBack(dynamic input)
{
var result = new {
a = 1,
b = 3.1415,
c = "foo",
d = true,
e = false,
f = new byte[10],
g = new object[] { 1, "foo" },
h = new { a = "foo", b = 12 },
i = (Func<object,Task<object>>)(async (i) => { return i; })
};
return Task.FromResult<object>(result);
}
public Task<object> NetExceptionTaskStart(dynamic input)
{
throw new Exception("Test .NET exception");
}
public Task<object> NetExceptionCLRThread(dynamic input)
{
Task<object> task = new Task<object>(() =>
{
throw new Exception("Test .NET exception");
});
task.Start();
return task;
}
public async Task<object> InvokeBack(dynamic input)
{
var result = await input.hello(".NET");
return result;
}
public async Task<object> MarshalInFromNet(dynamic input)
{
var payload = new {
a = 1,
b = 3.1415,
c = "foo",
d = true,
e = false,
f = new byte[10],
g = new object[] { 1, "foo" },
h = new { a = "foo", b = 12 },
i = (Func<object,Task<object>>)(async (i) => { return i; })
};
var result = await input.hello(payload);
return result;
}
public async Task<object> MarshalBackToNet(dynamic input)
{
var payload = await input.hello(null);
string result = ValidateMarshalNodeJsToNet(payload, false);
return result;
}
public async Task<object> MarshalException(dynamic input)
{
string result = "No exception was thrown";
try
{
await input.hello(null);
}
catch (Exception e)
{
result = e.ToString();
}
return result;
}
private WeakReference weakRefToNodejsFunc;
public Task<object> InvokeBackAfterCLRCallHasFinished(dynamic input)
{
var trace = new List<string>();
trace.Add("InvokeBackAfterCLRCallHasFinished#EnteredCLR");
Func<object, Task<object>> callback = input.eventCallback;
// The target of the callback function is the ref to the NodejsFunc acting as
// the proxy for the JS function to call.
weakRefToNodejsFunc = new WeakReference(callback.Target);
trace.Add("InvokeBackAfterCLRCallHasFinished#LeftCLR");
var result = new TaskCompletionSource<object>();
result.SetResult(trace);
// Now simulate an event callback after this CLR method has finished.
Task.Delay(50).ContinueWith(async (value) => {
GC.Collect();
// This throws an exception if the weak reference is not
// pointing to an existing object.
GC.GetGeneration(weakRefToNodejsFunc);
await callback("InvokeBackAfterCLRCallHasFinished#CallingCallbackFromDelayedTask");
});
return result.Task;
}
public Task<object> EnsureNodejsFuncIsCollected(dynamic input) {
var succeed = false;
GC.Collect();
try
{
// Throws an exception if the object the weak reference
// points to is GCed.
GC.GetGeneration(weakRefToNodejsFunc);
}
catch(Exception)
{
// The NodejsFunc is GCed.
succeed = true;
}
weakRefToNodejsFunc = null;
var result = new TaskCompletionSource<object>();
result.SetResult(succeed);
return result.Task;
}
}
}
| |
//
// Modified work Copyright 2017 Secure Decisions, a division of Applied Visions, Inc.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
namespace OpenCover.Framework.Model
{
/// <summary>
/// An instrumentable point
/// </summary>
public class InstrumentationPoint
{
private static int _instrumentPoint;
private static readonly object LockObject = new object();
private static readonly List<InstrumentationPoint> InstrumentPoints;
static InstrumentationPoint()
{
_instrumentPoint = 0;
InstrumentPoints = new List<InstrumentationPoint>(8192) {null};
}
internal static void Clear()
{
InstrumentPoints.Clear();
InstrumentPoints.Add(null);
_instrumentPoint = 0;
}
internal static void ResetAfterLoading()
{
var points = InstrumentPoints
.Where(x => x != null)
.GroupBy(x => x.UniqueSequencePoint)
.Select(g => g.OrderBy(x => x.OrigSequencePoint).First())
.ToList();
var max = (int)points.Max(x => x.UniqueSequencePoint);
InstrumentPoints.Clear();
InstrumentPoints.Add(null);
for (var i = 1; i <= max; i++)
{
var point = new SequencePoint();
InstrumentPoints[i] = point;
point.UniqueSequencePoint = (uint)i;
}
foreach (var instrumentationPoint in points)
{
InstrumentPoints[(int)instrumentationPoint.UniqueSequencePoint] = instrumentationPoint;
}
_instrumentPoint = max;
}
/// <summary>
/// Return the number of visit points
/// </summary>
public static int Count {
get { return InstrumentPoints.Count; }
}
/// <summary>
/// Get the number of recorded visit points for this identifier
/// </summary>
/// <param name="spid">the sequence point identifier - NOTE 0 is not used</param>
public static int GetVisitCount(uint spid)
{
return InstrumentPoints[(int) spid].VisitCount;
}
/// <summary>
/// Gets the method where this instrumentation point is defined.
/// </summary>
/// <param name="spid">the sequence point identifier - NOTE 0 is not used</param>
/// <returns>Method where instrumentation point is defined</returns>
public static Method GetDeclaringMethod(uint spid)
{
return spid >= InstrumentPoints.Count ? null : InstrumentPoints[(int) spid]?.DeclaringMethod;
}
/// <summary>
/// Gets source location associated with instrumentation point.
/// </summary>
/// <returns>A tuple consisting of optional source location.</returns>
public static Tuple<int?,int?,int?, int?> GetSourceLocation(uint spid)
{
return InstrumentPoints[(int) spid].GetSourceLocation();
}
/// <summary>
/// Add a number of recorded visit ppints against this identifier
/// </summary>
/// <param name="spid">the sequence point identifier - NOTE 0 is not used</param>
/// <param name="trackedMethodId">the id of a tracked method - Note 0 means no method currently tracking</param>
/// <param name="amount">the number of visit points to add</param>
public static bool AddVisitCount(uint spid, uint trackedMethodId, int amount)
{
return AddVisitCount(spid, Guid.Empty, trackedMethodId, amount);
}
/// <summary>
/// Add a number of recorded visit ppints against this identifier
/// </summary>
/// <param name="spid">the sequence point identifier - NOTE 0 is not used</param>
/// <param name="contextId">context identifier associated with code coverage</param>
/// <param name="trackedMethodId">the id of a tracked method - Note 0 means no method currently tracking</param>
/// <param name="amount">the number of visit points to add</param>
public static bool AddVisitCount(uint spid, Guid contextId, uint trackedMethodId, int amount)
{
if (spid != 0 && spid < InstrumentPoints.Count)
{
var point = InstrumentPoints[(int) spid];
point.VisitCount += amount;
if (point.VisitCount < 0)
{
point.VisitCount = int.MaxValue;
}
if (trackedMethodId != 0)
{
AddOrUpdateTrackingPoint(trackedMethodId, amount, point);
}
if (contextId == Guid.Empty)
{
return true;
}
var contextVisit = point.GetContextVisit(contextId);
contextVisit.VisitCount++;
return true;
}
return false;
}
private static void AddOrUpdateTrackingPoint(uint trackedMethodId, int amount, InstrumentationPoint point)
{
point._tracked = point._tracked ?? new List<TrackedMethodRef>();
var tracked = point._tracked.Find(x => x.UniqueId == trackedMethodId);
if (tracked == null)
{
tracked = new TrackedMethodRef {UniqueId = trackedMethodId, VisitCount = amount};
point._tracked.Add(tracked);
}
else
{
tracked.VisitCount += amount;
if (tracked.VisitCount < 0)
tracked.VisitCount = int.MaxValue;
}
}
private List<TrackedMethodRef> _tracked;
private readonly Dictionary<Guid, ContextVisit> _contextVisitsByGuid = new Dictionary<Guid, ContextVisit>();
/// <summary>
/// Initialise
/// </summary>
public InstrumentationPoint()
{
lock (LockObject)
{
UniqueSequencePoint = (uint)++_instrumentPoint;
InstrumentPoints.Add(this);
OrigSequencePoint = UniqueSequencePoint;
}
}
/// <summary>
/// Gets the context visit data for a given context identifier.
/// </summary>
/// <param name="contextId">The identifier associated with a specific context.</param>
/// <returns>The visit object containing a visit count associated with the context identifier.</returns>
public ContextVisit GetContextVisit(Guid contextId)
{
if (_contextVisitsByGuid.TryGetValue(contextId, out var contextVisit))
{
return contextVisit;
}
contextVisit = new ContextVisit { ContextId = contextId };
_contextVisitsByGuid[contextId] = contextVisit;
return contextVisit;
}
/// <summary>
/// Gets line numbers associated with instrumentation point.
/// </summary>
/// <returns>A tuple consisting of optional start and end line.</returns>
public virtual Tuple<int?, int?, int?, int?> GetSourceLocation()
{
return null;
}
/// <summary>
/// Store the number of visits
/// </summary>
[XmlAttribute("vc")]
public int VisitCount { get; set; }
/// <summary>
/// A unique number
/// </summary>
[XmlAttribute("uspid")]
public UInt32 UniqueSequencePoint { get; set; }
/// <summary>
/// An order of the point within the method
/// </summary>
[XmlAttribute("ordinal")]
public UInt32 Ordinal { get; set; }
/// <summary>
/// The IL offset of the point
/// </summary>
[XmlAttribute("offset")]
public int Offset { get; set; }
/// <summary>
/// Used to hide an instrumentation point
/// </summary>
[XmlIgnore]
public bool IsSkipped { get; set; }
/// <summary>
/// Method where the line(s) of this instrumentation point are defined.
/// </summary>
[XmlIgnore]
public Method DeclaringMethod { get; set; }
/// <summary>
/// The list of tracked methods
/// </summary>
public TrackedMethodRef[] TrackedMethodRefs
{
get
{
return _tracked?.ToArray();
}
set
{
_tracked = null;
if (value == null)
return;
_tracked = new List<TrackedMethodRef>(value);
}
}
/// <summary>
///
/// </summary>
[XmlIgnore]
public UInt32 OrigSequencePoint { get; set; }
}
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Derived from PropertyBag.cs by Tony Allowatt
* CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp
* Last Update: 04/05/2005
*
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Reflection;
using CslaGenerator.Attributes;
using CslaGenerator.Metadata;
namespace CslaGenerator.Util.PropertyBags
{
// to set PropertyGrid Form height
// PropertyCollectionForm.HandleFormCollectionType
// 1 row = 16 pixels
#region PropertySpec class
/// <summary>
/// Summary description for PropertySpec.
/// </summary>
public class PropertySpec
{
private Attribute[] attributes;
private string name;
private string category;
private string description;
private object defaultValue;
private string type;
private string editor;
private string typeConverter;
private Type targetClass;
private object targetObject = null;
private string targetProperty = "";
private string helpTopic = "";
private bool isReadonly = false;
private bool isBrowsable = true;
private string designerTypename = "";
private bool isBindable = true;
//public PropertySpec(string name, object type, object typeconverter, string category, string description, object defaultValue, object tarObject, string tarProperty, string helptopic)
public PropertySpec(string name, string type, string category, string description, object defaultValue, string editor, string typeConverter, object tarObject, string tarProperty, string helptopic, bool isreadonly, bool isbrowsable, string designertypename, bool isbindable)
{
this.Name = name;
this.TypeName = type;
if (this.TypeName == "")
throw new ArgumentException("Unable to determine PropertySpec type.");
this.category = category;
this.description = description;
this.defaultValue = defaultValue;
this.editor = editor;
this.typeConverter = typeConverter;
this.targetObject = tarObject;
this.targetProperty = tarProperty;
this.helpTopic = helptopic;
this.isReadonly = isreadonly;
this.isBrowsable = isbrowsable;
this.designerTypename = designertypename;
this.isBindable = isbindable;
}
#region properties
/// <summary>
/// Gets or sets a collection of additional Attributes for this property. This can
/// be used to specify attributes beyond those supported intrinsically by the
/// PropertySpec class, such as ReadOnly and Browsable.
/// </summary>
public Attribute[] Attributes
{
get { return attributes; }
set { attributes = value; }
}
/// <summary>
/// Gets or sets the category name of this property.
/// </summary>
public string Category
{
get { return category; }
set { category = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the type converter
/// type for this property (as string).
/// </summary>
public string ConverterTypeName
{
get { return typeConverter; }
set { typeConverter = value; }
}
/// <summary>
/// Gets or sets the default value of this property.
/// </summary>
public object DefaultValue
{
get { return defaultValue; }
set { defaultValue = value; }
}
/// <summary>
/// Gets or sets the help text description of this property.
/// </summary>
public string Description
{
get { return description; }
set { description = value; }
}
/// <summary>
/// Gets or sets the fully qualified name of the editor type for
/// this property (as string).
/// </summary>
public string EditorTypeName
{
get { return editor; }
set { editor = value; }
}
/// <summary>
/// Gets or sets the name of this property.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets or sets the fully qualfied name of the type of this
/// property (as string).
/// </summary>
public string TypeName
{
get { return type; }
set { type = value; }
}
/// <summary>
/// Gets or sets the boolean flag indicating if this property
/// is readonly
/// </summary>
public bool ReadOnly
{
get { return isReadonly; }
set { isReadonly = value; }
}
/// <summary>
/// Gets or sets the boolean flag indicating if this property
/// is browsable (i.e. visible in PropertyGrid
/// </summary>
public bool Browsable
{
get { return isBrowsable; }
set { isBrowsable = value; }
}
/// <summary>
/// Gets or sets the boolean flag indicating if this property
/// is bindable
/// </summary>
public bool Bindable
{
get { return isBindable; }
set { isBindable = value; }
}
/// <summary>
/// Test
///
/// </summary>
public Type TargetClass
{
get { return targetClass; }
set { targetClass = value; }
}
/// <summary>
/// Gets or sets the target object which is the owner of the
/// properties displayed in the PropertyGrid
/// </summary>
public object TargetObject
{
get { return targetObject; }
set { targetObject = value; }
}
/// <summary>
/// Gets or sets the target property in the target object
/// associated with the PropertyGrid item
/// </summary>
public string TargetProperty
{
get { return targetProperty; }
set { targetProperty = value; }
}
/// <summary>
/// Gets or sets the help topic key associated with this
/// PropertyGrid item
/// </summary>
public string HelpTopic
{
get { return helpTopic; }
set { helpTopic = value; }
}
#endregion
}
/// <summary>
/// Provides data for the GetValue and SetValue events of the PropertyBag class.
/// </summary>
public class PropertySpecEventArgs : EventArgs
{
private PropertySpec property;
private object val;
/// <summary>
/// Initializes a new instance of the PropertySpecEventArgs class.
/// </summary>
/// <param name="property">The PropertySpec that represents the property whose
/// value is being requested or set.</param>
/// <param name="val">The current value of the property.</param>
public PropertySpecEventArgs(PropertySpec property, object val)
{
this.property = property;
this.val = val;
}
/// <summary>
/// Gets the PropertySpec that represents the property whose value is being
/// requested or set.
/// </summary>
public PropertySpec Property
{
get { return property; }
}
/// <summary>
/// Gets or sets the current value of the property.
/// </summary>
public object Value
{
get { return val; }
set { val = value; }
}
}
/// <summary>
/// Represents the method that will handle the GetValue and SetValue events of the
/// PropertyBag class.
/// </summary>
public delegate void PropertySpecEventHandler(object sender, PropertySpecEventArgs e);
#endregion
/// <summary>
/// Represents a collection of custom properties that can be selected into a
/// PropertyGrid to provide functionality beyond that of the simple reflection
/// normally used to query an object's properties.
/// </summary>
public class PropertyBag : ICustomTypeDescriptor
{
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private ArrayList innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
innerArray = new ArrayList();
}
/// <summary>
/// Gets the number of elements in the PropertySpecCollection.
/// </summary>
/// <value>
/// The number of elements contained in the PropertySpecCollection.
/// </value>
public int Count
{
get { return innerArray.Count; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection has a fixed size.
/// </summary>
/// <value>
/// true if the PropertySpecCollection has a fixed size; otherwise, false.
/// </value>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>
/// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false.
/// </value>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
object ICollection.SyncRoot
{
get { return null; }
}
/// <summary>
/// Gets or sets the element at the specified index.
/// In C#, this property is the indexer for the PropertySpecCollection class.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>
/// The element at the specified index.
/// </value>
public PropertySpec this[int index]
{
get { return (PropertySpec)innerArray[index]; }
set { innerArray[index] = value; }
}
/// <summary>
/// Adds a PropertySpec to the end of the PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param>
/// <returns>The PropertySpecCollection index at which the value has been added.</returns>
public int Add(PropertySpec value)
{
int index = innerArray.Add(value);
return index;
}
/// <summary>
/// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
/// </summary>
/// <param name="array">The PropertySpec array whose elements should be added to the end of the
/// PropertySpecCollection.</param>
public void AddRange(PropertySpec[] array)
{
innerArray.AddRange(array);
}
/// <summary>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
innerArray.Clear();
}
/// <summary>
/// Determines whether a PropertySpec is in the PropertySpecCollection.
/// </summary>
/// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate
/// can be a null reference (Nothing in Visual Basic).</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(PropertySpec item)
{
return innerArray.Contains(item);
}
/// <summary>
/// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(string name)
{
foreach (PropertySpec spec in innerArray)
if (spec.Name == name)
return true;
return false;
}
/// <summary>
/// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the
/// beginning of the target array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from PropertySpecCollection. The Array must have zero-based indexing.</param>
public void CopyTo(PropertySpec[] array)
{
innerArray.CopyTo(array);
}
/// <summary>
/// Copies the PropertySpecCollection or a portion of it to a one-dimensional array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from the collection.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(PropertySpec[] array, int index)
{
innerArray.CopyTo(array, index);
}
/// <summary>
/// Returns an enumerator that can iterate through the PropertySpecCollection.
/// </summary>
/// <returns>An IEnumerator for the entire PropertySpecCollection.</returns>
public IEnumerator GetEnumerator()
{
return innerArray.GetEnumerator();
}
/// <summary>
/// Searches for the specified PropertySpec and returns the zero-based index of the first
/// occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(PropertySpec value)
{
return innerArray.IndexOf(value);
}
/// <summary>
/// Searches for the PropertySpec with the specified name and returns the zero-based index of
/// the first occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(string name)
{
int i = 0;
foreach (PropertySpec spec in innerArray)
{
//if (spec.Name == name)
if (spec.TargetProperty == name)
return i;
i++;
}
return -1;
}
/// <summary>
/// Inserts a PropertySpec object into the PropertySpecCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The PropertySpec to insert.</param>
public void Insert(int index, PropertySpec value)
{
innerArray.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the PropertySpecCollection.
/// </summary>
/// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(PropertySpec obj)
{
innerArray.Remove(obj);
}
/// <summary>
/// Removes the property with the specified name from the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(string name)
{
int index = IndexOf(name);
RemoveAt(index);
}
/// <summary>
/// Removes the object at the specified index of the PropertySpecCollection.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
innerArray.RemoveAt(index);
}
/// <summary>
/// Copies the elements of the PropertySpecCollection to a new PropertySpec array.
/// </summary>
/// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns>
public PropertySpec[] ToArray()
{
return (PropertySpec[])innerArray.ToArray(typeof(PropertySpec));
}
#region Explicit interface implementations for ICollection and IList
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
CopyTo((PropertySpec[])array, index);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.Add(object value)
{
return Add((PropertySpec)value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
bool IList.Contains(object obj)
{
return Contains((PropertySpec)obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (PropertySpec)value;
}
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.IndexOf(object obj)
{
return IndexOf((PropertySpec)obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Insert(int index, object value)
{
Insert(index, (PropertySpec)value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Remove(object value)
{
Remove((PropertySpec)value);
}
#endregion
}
#endregion
#region PropertySpecDescriptor class definition
private class PropertySpecDescriptor : PropertyDescriptor
{
private PropertyBag bag;
private PropertySpec item;
public PropertySpecDescriptor(PropertySpec item, PropertyBag bag, string name, Attribute[] attrs)
:
base(name, attrs)
{
this.bag = bag;
this.item = item;
}
public override Type ComponentType
{
get { return item.GetType(); }
}
public override bool IsReadOnly
{
get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); }
}
public override Type PropertyType
{
get { return Type.GetType(item.TypeName); }
}
public override bool CanResetValue(object component)
{
if (item.DefaultValue == null)
return false;
return !GetValue(component).Equals(item.DefaultValue);
}
public override object GetValue(object component)
{
// Have the property bag raise an event to get the current value
// of the property.
PropertySpecEventArgs e = new PropertySpecEventArgs(item, null);
bag.OnGetValue(e);
return e.Value;
}
public override void ResetValue(object component)
{
SetValue(component, item.DefaultValue);
}
public override void SetValue(object component, object value)
{
// Have the property bag raise an event to set the current value
// of the property.
PropertySpecEventArgs e = new PropertySpecEventArgs(item, value);
bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = this.GetValue(component);
if (item.DefaultValue == null && val == null)
return false;
return !val.Equals(item.DefaultValue);
}
}
#endregion
#region Properties and Events
private string defaultProperty;
private PropertySpecCollection _properties;
private CslaObjectInfo[] _selectedObject;
private PropertyContext _propertyContext;
/// <summary>
/// Initializes a new instance of the PropertyBag class.
/// </summary>
public PropertyBag()
{
defaultProperty = null;
_properties = new PropertySpecCollection();
}
public PropertyBag(CslaObjectInfo obj)
: this(new CslaObjectInfo[] { obj })
{ }
public PropertyBag(CslaObjectInfo[] obj)
{
defaultProperty = null;
_properties = new PropertySpecCollection();
_selectedObject = obj;
InitPropertyBag();
}
public PropertyBag(CslaObjectInfo obj, PropertyContext context)
: this(new CslaObjectInfo[] { obj }, context)
{ }
public PropertyBag(CslaObjectInfo[] obj, PropertyContext context)
{
defaultProperty = "ObjectName";
_properties = new PropertySpecCollection();
_selectedObject = obj;
_propertyContext = context;
InitPropertyBag();
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public string DefaultProperty
{
get { return defaultProperty; }
set { defaultProperty = value; }
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public CslaObjectInfo[] SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject = value;
InitPropertyBag();
}
}
/// <summary>
/// Gets or sets the property context.
/// </summary>
public PropertyContext PropertyContext
{
get { return _propertyContext; }
set
{
_propertyContext = value;
}
}
/// <summary>
/// Gets the collection of properties contained within this PropertyBag.
/// </summary>
public PropertySpecCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Occurs when a PropertyGrid requests the value of a property.
/// </summary>
public event PropertySpecEventHandler GetValue;
/// <summary>
/// Occurs when the user changes the value of a property in a PropertyGrid.
/// </summary>
public event PropertySpecEventHandler SetValue;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnGetValue(PropertySpecEventArgs e)
{
if (e.Value != null)
GetValue(this, e);
e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnSetValue(PropertySpecEventArgs e)
{
if (SetValue != null)
SetValue(this, e);
setProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value);
}
#endregion
#region Initialize Propertybag
private void InitPropertyBag()
{
PropertyInfo propertyInfo;
Type t = typeof(CslaObjectInfo);// mSelectedObject.GetType();
PropertyInfo[] props = t.GetProperties();
// Display information for all properties.
for (int i = 0; i < props.Length; i++)
{
propertyInfo = props[i];
Object[] myAttributes = propertyInfo.GetCustomAttributes(true);
string category = "";
string description = "";
bool isreadonly = false;
bool isbrowsable = true;
object defaultvalue = null;
string defaultproperty = "";
string userfriendlyname = "";
string typeconverter = "";
string designertypename = "";
string helptopic = "";
bool bindable = true;
string editor = "";
for (int n = 0; n < myAttributes.Length; n++)
{
Attribute a = (Attribute)myAttributes[n];
switch (a.GetType().ToString())
{
case "System.ComponentModel.CategoryAttribute":
category = ((CategoryAttribute)a).Category;
break;
case "System.ComponentModel.DescriptionAttribute":
description = ((DescriptionAttribute)a).Description;
break;
case "System.ComponentModel.ReadOnlyAttribute":
isreadonly = ((ReadOnlyAttribute)a).IsReadOnly;
break;
case "System.ComponentModel.BrowsableAttribute":
isbrowsable = ((BrowsableAttribute)a).Browsable;
break;
case "System.ComponentModel.DefaultValueAttribute":
defaultvalue = ((DefaultValueAttribute)a).Value;
break;
case "System.ComponentModel.DefaultPropertyAttribute":
defaultproperty = ((DefaultPropertyAttribute)a).Name;
break;
case "CslaGenerator.Attributes.UserFriendlyNameAttribute":
userfriendlyname = ((UserFriendlyNameAttribute)a).UserFriendlyName;
break;
case "CslaGenerator.Attributes.HelpTopicAttribute":
helptopic = ((HelpTopicAttribute)a).HelpTopic;
break;
case "System.ComponentModel.TypeConverterAttribute":
typeconverter = ((TypeConverterAttribute)a).ConverterTypeName;
break;
case "System.ComponentModel.DesignerAttribute":
designertypename = ((DesignerAttribute)a).DesignerTypeName;
break;
case "System.ComponentModel.BindableAttribute":
bindable = ((BindableAttribute)a).Bindable;
break;
case "System.ComponentModel.EditorAttribute":
editor = ((EditorAttribute)a).EditorTypeName;
break;
}
}
// Set ReadOnly properties
if (SelectedObject[0].IsPlaceHolder() &&
propertyInfo.Name == "Generate")
isreadonly = true;
if ((SelectedObject[0].IsBaseClass() && SelectedObject[0].CslaBaseClass != CslaBaseClasses.None) &&
(propertyInfo.Name == "IsGenericType" ||
propertyInfo.Name == "GenericArguments"))
isreadonly = true;
userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : propertyInfo.Name;
var types = new List<CslaObjectInfo>();
foreach (CslaObjectInfo obj in _selectedObject)
{
if (!types.Contains(obj))
types.Add(obj);
}
// here get rid of Parent
bool isValidProperty = propertyInfo.Name != "Parent";
if (isValidProperty && IsBrowsable(types.ToArray(), propertyInfo.Name))
{
// CR added missing parameters
//Properties.Add(new PropertySpec(userfriendlyname,propertyInfo.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, mSelectedObject, propertyInfo.Name,helptopic));
Properties.Add(new PropertySpec(userfriendlyname, propertyInfo.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable));
}
}
}
#endregion
private Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>();
private PropertyInfo GetPropertyInfoCache(string propertyName)
{
if (!propertyInfoCache.ContainsKey(propertyName))
{
propertyInfoCache.Add(propertyName, typeof(CslaObjectInfo).GetProperty(propertyName));
}
return propertyInfoCache[propertyName];
}
private bool IsEnumerable(PropertyInfo prop)
{
if (prop.PropertyType == typeof(string))
return false;
Type[] interfaces = prop.PropertyType.GetInterfaces();
foreach (Type typ in interfaces)
if (typ.Name.Contains("IEnumerable"))
return true;
return false;
}
#region IsBrowsable map objectType:propertyName -> true | false
/// <summary>
/// Determines whether the specified object type is browsable.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <param name="propertyName">Name of the property.</param>
/// <returns></returns>
private bool IsBrowsable(CslaObjectInfo[] objectType, string propertyName)
{
try
{
var authorization =
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None ||
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.PropertyLevel;
// Use PropertyContext class to determine if the combination
// objectType + propertyName should be shown in propertygrid
// else default to true (show it)
// objectType + propertyName --> true | false
if (_propertyContext != null)
{
// there is only a single element in the array. Ever.
foreach (var cslaObject in objectType)
{
var canHaveParentProperties = cslaObject.CanHaveParentProperties();
var cslaParent = new CslaObjectInfo();
if (cslaObject.ParentType != string.Empty)
cslaParent = cslaObject.Parent.CslaObjects.Find(cslaObject.ParentType);
if ((authorization || ((cslaObject.AuthzProvider == AuthorizationProvider.Custom) &&
!GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider)) &&
(propertyName == "NewRoles" ||
propertyName == "GetRoles" ||
propertyName == "UpdateRoles" ||
propertyName == "DeleteRoles"))
return false;
if ((authorization || ((cslaObject.AuthzProvider == AuthorizationProvider.IsInRole ||
cslaObject.AuthzProvider == AuthorizationProvider.IsNotInRole) &&
!GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider) ||
GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider) &&
(propertyName == "NewAuthzRuleType" ||
propertyName == "GetAuthzRuleType" ||
propertyName == "UpdateAuthzRuleType" ||
propertyName == "DeleteAuthzRuleType"))
return false;
if ((authorization ||
GeneratorController.Current.CurrentUnit.GenerationParams.UsesCslaAuthorizationProvider) &&
propertyName == "AuthzProvider")
return false;
if (GeneratorController.Current.CurrentUnit.GenerationParams.UseInlineQueries !=
UseInlineQueries.SpecifyByObject &&
propertyName == "GenerateInlineQueries")
return false;
if (!GeneratorController.Current.CurrentUnit.GenerationParams.DualListInheritance &&
propertyName == "InheritedTypeWinForms")
return false;
if (cslaObject.IsBaseClass() && cslaObject.CslaBaseClass.IsNotListBaseClass() &&
propertyName == "ItemType")
return false;
if (cslaObject.IsBaseClass() && cslaObject.CslaBaseClass.IsNotObjectBaseClass() &&
(propertyName == "ValueProperties" ||
propertyName == "InheritedValueProperties"))
return false;
if (!cslaObject.IsGenericType &&
propertyName == "GenericArguments")
return false;
if (cslaObject.ObjectType.IsReadOnlyType() &&
!string.IsNullOrEmpty(cslaObject.ParentType) &&
propertyName == "UseUnitOfWorkType")
return false;
if (!(cslaObject.IsDynamicEditableRoot() ||
cslaObject.IsReadOnlyObject()) &&
propertyName == "AddParentReference")
return false;
if (cslaObject.IsNotEditableChild() &&
propertyName == "DeleteProcedureName")
return false;
if ((cslaObject.IsNotEditableChild()) &&
propertyName == "DeleteUseTimestamp")
return false;
if ((cslaObject.IsUnitOfWork()) &&
propertyName == "CommandTimeout")
return false;
if (!(cslaObject.IsEditableChild() &&
(cslaParent == null || cslaParent.ObjectType.IsCollectionType())) &&
propertyName == "RemoveItem")
return false;
if (!canHaveParentProperties &&
(propertyName == "ParentProperties" ||
propertyName == "UseParentProperties"))
return false;
if (cslaObject.IsNotUnitOfWork() &&
(propertyName == "UnitOfWorkProperties" ||
propertyName == "UnitOfWorkType"))
return false;
if (string.IsNullOrEmpty(cslaObject.InheritedType.FinalName) &&
(propertyName == "InheritedChildCollectionProperties" ||
propertyName == "InheritedChildProperties" ||
propertyName == "InheritedValueProperties"))
return false;
if (!_propertyContext.ShowProperty(cslaObject.ObjectType.ToString(), propertyName))
return false;
}
if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName)))
return false;
return true;// TO DO return true here???
}
return true;
}
catch //(Exception e)
{
//Debug.WriteLine(objectType + ":" + propertyName);
return true;
}
}
#endregion
#region reflection functions
private object getField(Type t, string name, object target)
{
object obj = null;
Type tx;
//FieldInfo[] fields;
//fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
//fields = target.GetType().GetFields(BindingFlags.Public);
tx = target.GetType();
obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] { });
return obj;
}
private object setField(Type t, string name, object value, object target)
{
object obj;
obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new object[] { value });
return obj;
}
private bool setProperty(object obj, string propertyName, object val)
{
try
{
// get a reference to the PropertyInfo, exit if no property with that name
PropertyInfo propertyInfo = typeof(CslaObjectInfo).GetProperty(propertyName);
if (propertyInfo == null)
return false;
// convert the value to the expected type
val = Convert.ChangeType(val, propertyInfo.PropertyType);
// attempt the assignment
foreach (CslaObjectInfo bo in (CslaObjectInfo[])obj)
propertyInfo.SetValue(bo, val, null);
return true;
}
catch
{
return false;
}
}
private object GetProperty(object obj, string propertyName, object defaultValue)
{
try
{
PropertyInfo propertyInfo = GetPropertyInfoCache(propertyName);
if (!(propertyInfo == null))
{
CslaObjectInfo[] objs = (CslaObjectInfo[])obj;
ArrayList valueList = new ArrayList();
foreach (CslaObjectInfo bo in objs)
{
object value = propertyInfo.GetValue(bo, null);
if (!valueList.Contains(value))
{
valueList.Add(value);
}
}
switch (valueList.Count)
{
case 1:
return valueList[0];
default:
return string.Empty;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// if property doesn't exist or throws
return defaultValue;
}
#endregion
#region ICustomTypeDescriptor explicit interface definitions
// Most of the functions required by the ICustomTypeDescriptor are
// merely pssed on to the default TypeDescriptor for this type,
// which will do something appropriate. The exceptions are noted
// below.
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
// This function searches the property list for the property
// with the same name as the DefaultProperty specified, and
// returns a property descriptor for it. If no property is
// found that matches DefaultProperty, a null reference is
// returned instead.
PropertySpec propertySpec = null;
if (defaultProperty != null)
{
int index = _properties.IndexOf(defaultProperty);
propertySpec = _properties[index];
}
if (propertySpec != null)
return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null);
else
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of PropertyBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
var props = new ArrayList();
foreach (PropertySpec property in _properties)
{
var attrs = new ArrayList();
// If a category, description, editor, or type converter are specified
// in the PropertySpec, create attributes to define that relationship.
if (property.Category != null)
{
if (property.Category == "08. Insert & Update Options")
{
var cslaObject = (CslaObjectInfo)GeneratorController.Current.GetSelectedItem();
if (cslaObject.IsEditableChild())
{
property.Category = "08. Insert, Update, Delete Options";
}
}
attrs.Add(new CategoryAttribute(property.Category));
}
if (property.Description != null)
attrs.Add(new DescriptionAttribute(property.Description));
if (property.EditorTypeName != null)
attrs.Add(new EditorAttribute(property.EditorTypeName, typeof(UITypeEditor)));
if (property.ConverterTypeName != null)
attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
// Additionally, append the custom attributes associated with the
// PropertySpec, if any.
if (property.Attributes != null)
attrs.AddRange(property.Attributes);
if (property.DefaultValue != null)
attrs.Add(new DefaultValueAttribute(property.DefaultValue));
attrs.Add(new BrowsableAttribute(property.Browsable));
attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
attrs.Add(new BindableAttribute(property.Bindable));
Attribute[] attrArray = (Attribute[])attrs.ToArray(typeof(Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
PropertySpecDescriptor pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
PropertyDescriptor[] propArray = (PropertyDescriptor[])props.ToArray(
typeof(PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace ZXing.Common
{
/// <summary>
/// A simple, fast array of bits, represented compactly by an array of ints internally.
/// </summary>
/// <author>Sean Owen</author>
public sealed class BitArray
{
private int[] bits;
private int size;
public int Size
{
get
{
return size;
}
}
public int SizeInBytes
{
get
{
return (size + 7) >> 3;
}
}
public bool this[int i]
{
get
{
return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;
}
set
{
if (value)
bits[i >> 5] |= 1 << (i & 0x1F);
}
}
public BitArray()
{
this.size = 0;
this.bits = new int[1];
}
public BitArray(int size)
{
if (size < 1)
{
throw new ArgumentException("size must be at least 1");
}
this.size = size;
this.bits = makeArray(size);
}
// For testing only
private BitArray(int[] bits, int size)
{
this.bits = bits;
this.size = size;
}
private void ensureCapacity(int size)
{
if (size > bits.Length << 5)
{
int[] newBits = makeArray(size);
System.Array.Copy(bits, 0, newBits, 0, bits.Length);
bits = newBits;
}
}
/// <summary> Flips bit i.
///
/// </summary>
/// <param name="i">bit to set
/// </param>
public void flip(int i)
{
bits[i >> 5] ^= 1 << (i & 0x1F);
}
private static int numberOfTrailingZeros(int num)
{
var index = (-num & num)%37;
if (index < 0)
index *= -1;
return _lookup[index];
}
private static readonly int[] _lookup =
{
32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17,
0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18
};
/// <summary>
/// Gets the next set.
/// </summary>
/// <param name="from">first bit to check</param>
/// <returns>index of first bit that is set, starting from the given index, or size if none are set
/// at or beyond this given index</returns>
public int getNextSet(int from)
{
if (from >= size)
{
return size;
}
int bitsOffset = from >> 5;
int currentBits = bits[bitsOffset];
// mask off lesser bits first
currentBits &= ~((1 << (from & 0x1F)) - 1);
while (currentBits == 0)
{
if (++bitsOffset == bits.Length)
{
return size;
}
currentBits = bits[bitsOffset];
}
int result = (bitsOffset << 5) + numberOfTrailingZeros(currentBits);
return result > size ? size : result;
}
/// <summary>
/// see getNextSet(int)
/// </summary>
/// <param name="from">index to start looking for unset bit</param>
/// <returns>index of next unset bit, or <see cref="Size"/> if none are unset until the end</returns>
public int getNextUnset(int from)
{
if (from >= size)
{
return size;
}
int bitsOffset = from >> 5;
int currentBits = ~bits[bitsOffset];
// mask off lesser bits first
currentBits &= ~((1 << (from & 0x1F)) - 1);
while (currentBits == 0)
{
if (++bitsOffset == bits.Length)
{
return size;
}
currentBits = ~bits[bitsOffset];
}
int result = (bitsOffset << 5) + numberOfTrailingZeros(currentBits);
return result > size ? size : result;
}
/// <summary> Sets a block of 32 bits, starting at bit i.
///
/// </summary>
/// <param name="i">first bit to set
/// </param>
/// <param name="newBits">the new value of the next 32 bits. Note again that the least-significant bit
/// corresponds to bit i, the next-least-significant to i+1, and so on.
/// </param>
public void setBulk(int i, int newBits)
{
bits[i >> 5] = newBits;
}
/// <summary>
/// Sets a range of bits.
/// </summary>
/// <param name="start">start of range, inclusive.</param>
/// <param name="end">end of range, exclusive</param>
public void setRange(int start, int end)
{
if (end < start || start < 0 || end > size)
{
throw new ArgumentException();
}
if (end == start)
{
return;
}
end--; // will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start >> 5;
int lastInt = end >> 5;
for (int i = firstInt; i <= lastInt; i++)
{
int firstBit = i > firstInt ? 0 : start & 0x1F;
int lastBit = i < lastInt ? 31 : end & 0x1F;
// Ones from firstBit to lastBit, inclusive
int mask = (2 << lastBit) - (1 << firstBit);
bits[i] |= mask;
}
}
/// <summary> Clears all bits (sets to false).</summary>
public void clear()
{
int max = bits.Length;
for (int i = 0; i < max; i++)
{
bits[i] = 0;
}
}
/// <summary> Efficient method to check if a range of bits is set, or not set.
///
/// </summary>
/// <param name="start">start of range, inclusive.
/// </param>
/// <param name="end">end of range, exclusive
/// </param>
/// <param name="value">if true, checks that bits in range are set, otherwise checks that they are not set
/// </param>
/// <returns> true iff all bits are set or not set in range, according to value argument
/// </returns>
/// <throws> IllegalArgumentException if end is less than start or the range is not contained in the array</throws>
public bool isRange(int start, int end, bool value)
{
if (end < start || start < 0 || end > size)
{
throw new ArgumentException();
}
if (end == start)
{
return true; // empty range matches
}
end--; // will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start >> 5;
int lastInt = end >> 5;
for (int i = firstInt; i <= lastInt; i++)
{
int firstBit = i > firstInt ? 0 : start & 0x1F;
int lastBit = i < lastInt ? 31 : end & 0x1F;
// Ones from firstBit to lastBit, inclusive
int mask = (2 << lastBit) - (1 << firstBit);
// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
// equals the mask, or we're looking for 0s and the masked portion is not all 0s
if ((bits[i] & mask) != (value ? mask : 0))
{
return false;
}
}
return true;
}
/// <summary>
/// Appends the bit.
/// </summary>
/// <param name="bit">The bit.</param>
public void appendBit(bool bit)
{
ensureCapacity(size + 1);
if (bit)
{
bits[size >> 5] |= 1 << (size & 0x1F);
}
size++;
}
/// <returns> underlying array of ints. The first element holds the first 32 bits, and the least
/// significant bit is bit 0.
/// </returns>
public int[] Array
{
get { return bits; }
}
/// <summary>
/// Appends the least-significant bits, from value, in order from most-significant to
/// least-significant. For example, appending 6 bits from 0x000001E will append the bits
/// 0, 1, 1, 1, 1, 0 in that order.
/// </summary>
/// <param name="value"><see cref="int"/> containing bits to append</param>
/// <param name="numBits">bits from value to append</param>
public void appendBits(int value, int numBits)
{
if (numBits < 0 || numBits > 32)
{
throw new ArgumentException("Num bits must be between 0 and 32");
}
ensureCapacity(size + numBits);
for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--)
{
appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1);
}
}
public void appendBitArray(BitArray other)
{
int otherSize = other.size;
ensureCapacity(size + otherSize);
for (int i = 0; i < otherSize; i++)
{
appendBit(other[i]);
}
}
public void xor(BitArray other)
{
if (size != other.size)
{
throw new ArgumentException("Sizes don't match");
}
for (int i = 0; i < bits.Length; i++)
{
// The last int could be incomplete (i.e. not have 32 bits in
// it) but there is no problem since 0 XOR 0 == 0.
bits[i] ^= other.bits[i];
}
}
/// <summary>
/// Toes the bytes.
/// </summary>
/// <param name="bitOffset">first bit to start writing</param>
/// <param name="array">array to write into. Bytes are written most-significant byte first. This is the opposite
/// of the internal representation, which is exposed by BitArray</param>
/// <param name="offset">position in array to start writing</param>
/// <param name="numBytes">how many bytes to write</param>
public void toBytes(int bitOffset, byte[] array, int offset, int numBytes)
{
for (int i = 0; i < numBytes; i++)
{
int theByte = 0;
for (int j = 0; j < 8; j++)
{
if (this[bitOffset])
{
theByte |= 1 << (7 - j);
}
bitOffset++;
}
array[offset + i] = (byte)theByte;
}
}
/// <summary> Reverses all bits in the array.</summary>
public void reverse()
{
var newBits = new int[bits.Length];
// reverse all int's first
var len = ((size - 1) >> 5);
var oldBitsLen = len + 1;
for (var i = 0; i < oldBitsLen; i++)
{
var x = (long)bits[i];
x = ((x >> 1) & 0x55555555u) | ((x & 0x55555555u) << 1);
x = ((x >> 2) & 0x33333333u) | ((x & 0x33333333u) << 2);
x = ((x >> 4) & 0x0f0f0f0fu) | ((x & 0x0f0f0f0fu) << 4);
x = ((x >> 8) & 0x00ff00ffu) | ((x & 0x00ff00ffu) << 8);
x = ((x >> 16) & 0x0000ffffu) | ((x & 0x0000ffffu) << 16);
newBits[len - i] = (int)x;
}
// now correct the int's if the bit size isn't a multiple of 32
if (size != oldBitsLen*32)
{
var leftOffset = oldBitsLen*32 - size;
var currentInt = ((int) ((uint) newBits[0] >> leftOffset)); // (newBits[0] >>> leftOffset);
for (var i = 1; i < oldBitsLen; i++)
{
var nextInt = newBits[i];
currentInt |= nextInt << (32 - leftOffset);
newBits[i - 1] = currentInt;
currentInt = ((int) ((uint) nextInt >> leftOffset)); // (nextInt >>> leftOffset);
}
newBits[oldBitsLen - 1] = currentInt;
}
bits = newBits;
}
private static int[] makeArray(int size)
{
return new int[(size + 31) >> 5];
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="o">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(Object o)
{
var other = o as BitArray;
if (other == null)
return false;
if (size != other.size)
return false;
for (var index = 0; index < size; index++)
{
if (bits[index] != other.bits[index])
return false;
}
return true;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
var hash = size;
foreach (var bit in bits)
{
hash = 31 * hash + bit.GetHashCode();
}
return hash;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override String ToString()
{
var result = new System.Text.StringBuilder(size);
for (int i = 0; i < size; i++)
{
if ((i & 0x07) == 0)
{
result.Append(' ');
}
result.Append(this[i] ? 'X' : '.');
}
return result.ToString();
}
/// <summary>
/// Erstellt ein neues Objekt, das eine Kopie der aktuellen Instanz darstellt.
/// </summary>
/// <returns>
/// Ein neues Objekt, das eine Kopie dieser Instanz darstellt.
/// </returns>
public object Clone()
{
return new BitArray((int[])bits.Clone(), size);
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using DotNet;
using Collection = System.Collections.ICollection;
using EnumSet = System.Collections.IList;
using TextColor = System.Nullable<System.ConsoleColor>;
using System.Collections.Generic;
//TODO: JavaCompatability
using IllegalArgumentException = System.ArgumentException;
using boolean = System.Boolean;
namespace lanterna {
/**
* Represents a single character with additional metadata such as colors and modifiers. This class is immutable and
* cannot be modified after creation.
* @author Martin
*/
public class TextCharacter {
public static readonly TextCharacter DEFAULT_CHARACTER = new TextCharacter();
private char character;
private TextColor foregroundColor;
private TextColor backgroundColor;
/**
* Copies another {@code ScreenCharacter}
* @param character screenCharacter to copy from
*/
public TextCharacter(TextCharacter character)
: this(character.getCharacter(),
character.getForegroundColor(),
character.getBackgroundColor()) {
}
/**
* Creates a new {@code ScreenCharacter} based on a physical character, color information and a set of modifiers.
* @param character Physical character to refer to
* @param foregroundColor Foreground color the character has
* @param backgroundColor Background color the character has
* @param modifiers Set of modifiers to apply when drawing the character
*/
public TextCharacter(
char character = ' ',
TextColor foregroundColor = ConsoleColor.White,
TextColor backgroundColor = ConsoleColor.Black
) {
this.character = character;
this.foregroundColor = foregroundColor;
this.backgroundColor = backgroundColor;
//
}
/**
* The actual character this TextCharacter represents
* @return character of the TextCharacter
*/
public char getCharacter() {
return character;
}
/**
* Foreground color specified for this TextCharacter
* @return Foreground color of this TextCharacter
*/
public TextColor getForegroundColor() {
return foregroundColor;
}
/**
* Background color specified for this TextCharacter
* @return Background color of this TextCharacter
*/
public TextColor getBackgroundColor() {
return backgroundColor;
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/**
* Returns a new TextCharacter with the same colors and modifiers but a different underlying character
* @param character Character the copy should have
* @return Copy of this TextCharacter with different underlying character
*/
//@SuppressWarnings("SameParameterValue")
public TextCharacter withCharacter(char character) {
if (this.character == character) {
return this;
}
return new TextCharacter(character, foregroundColor, backgroundColor);
}
/**
* Returns a copy of this TextCharacter with a specified foreground color
* @param foregroundColor Foreground color the copy should have
* @return Copy of the TextCharacter with a different foreground color
*/
public TextCharacter withForegroundColor(TextColor foregroundColor) {
if (this.foregroundColor == foregroundColor) {
return this;
}
return new TextCharacter(character, foregroundColor, backgroundColor);
}
/**
* Returns a copy of this TextCharacter with a specified background color
* @param backgroundColor Background color the copy should have
* @return Copy of the TextCharacter with a different background color
*/
public TextCharacter withBackgroundColor(TextColor backgroundColor) {
if (this.backgroundColor == backgroundColor) {
return this;
}
return new TextCharacter(character, foregroundColor, backgroundColor);
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//@SuppressWarnings("SimplifiableIfStatement")
//@Override
public override boolean Equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
TextCharacter other = (TextCharacter)obj;
return this.getCharacter() == other.getCharacter()
&& this.getForegroundColor() == other.getForegroundColor()
&& this.getBackgroundColor() == other.getBackgroundColor();
}
//@Override
public override int GetHashCode() {
int hash = 7;
hash = 37 * hash + (int)this.getCharacter();
hash = 37 * hash + this.getForegroundColor().GetHashCode();
hash = 37 * hash + this.getBackgroundColor().GetHashCode();
return hash;
}
//@Override
public override String ToString() {
return "TextCharacter{" + "character=" + getCharacter() + ", foregroundColor=" + getForegroundColor() + ", backgroundColor=" + getBackgroundColor() + "}";
}
}
}
| |
// -------------------------------------
// Domain : IBT / Realtime.co
// Author : Nicholas Ventimiglia
// Product : Messaging and Storage
// Published : 2014
// -------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace Realtime.LITJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
public static bool IgnoreNullWrites = true;
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
UnityExtensions.AddExtensions();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
if (reader.Token == JsonToken.Null) {
if (! inst_type.IsClass)
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
return null;
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (inst_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
custom_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
inst_type)) {
ImporterFunc importer =
base_importers_table[json_type][inst_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (inst_type.IsEnum)
return Enum.ToObject (inst_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (inst_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (inst_type);
ObjectMetadata t_data = object_metadata[inst_type];
instance = Activator.CreateInstance (inst_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary) {
if (! reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate { return new JsonMockWrapper (); }, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
var value = ((FieldInfo)p_data.Info).GetValue(obj);
if (IgnoreNullWrites && value == null)
continue;
writer.WritePropertyName (p_data.Info.Name);
WriteValue (value,writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead)
{
var value = p_info.GetValue(obj, null);
if(IgnoreNullWrites && value == null)
continue;
writer.WritePropertyName (p_data.Info.Name);
WriteValue(value,writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
/// NV ADDITION
public static object ToObject(string json, Type t)
{
JsonReader reader = new JsonReader(json);
return ReadValue(t, reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Text.Tagging;
using Moq;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging
{
public class AsynchronousTaggerTests : TestBase
{
/// <summary>
/// This hits a special codepath in the product that is optimized for more than 100 spans.
/// I'm leaving this test here because it covers that code path (as shown by code coverage)
/// </summary>
[WpfFact]
[WorkItem(530368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530368")]
public async Task LargeNumberOfSpans()
{
using (var workspace = await TestWorkspace.CreateCSharpAsync(@"class Program
{
void M()
{
int z = 0;
z = z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z;
}
}"))
{
Callback tagProducer = (span, cancellationToken) =>
{
return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) };
};
var asyncListener = new TaggerOperationListener();
WpfTestCase.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(LargeNumberOfSpans)} creates asynchronous taggers");
var notificationService = workspace.GetService<IForegroundNotificationService>();
var eventSource = CreateEventSource();
var taggerProvider = new TestTaggerProvider(
tagProducer,
eventSource,
workspace,
asyncListener,
notificationService);
var document = workspace.Documents.First();
var textBuffer = document.TextBuffer;
var snapshot = textBuffer.CurrentSnapshot;
var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer);
using (IDisposable disposable = (IDisposable)tagger)
{
var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1));
var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans);
eventSource.SendUpdateEvent();
await asyncListener.CreateWaitTask();
var tags = tagger.GetTags(snapshotSpans);
Assert.Equal(1, tags.Count());
}
}
}
[WpfFact]
public async Task TestSynchronousOutlining()
{
using (var workspace = await TestWorkspace.CreateCSharpAsync("class Program {\r\n\r\n}"))
{
WpfTestCase.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestSynchronousOutlining)} creates asynchronous taggers");
var tagProvider = new OutliningTaggerProvider(
workspace.GetService<IForegroundNotificationService>(),
workspace.GetService<ITextEditorFactoryService>(),
workspace.GetService<IEditorOptionsFactoryService>(),
workspace.GetService<IProjectionBufferFactoryService>(),
workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
var document = workspace.Documents.First();
var textBuffer = document.TextBuffer;
var tagger = tagProvider.CreateTagger<IOutliningRegionTag>(textBuffer);
using (var disposable = (IDisposable)tagger)
{
// The very first all to get tags should return the single outlining span.
var tags = tagger.GetAllTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()), CancellationToken.None);
Assert.Equal(1, tags.Count());
}
}
}
private static TestTaggerEventSource CreateEventSource()
{
return new TestTaggerEventSource();
}
private static Mock<IOptionService> CreateFeatureOptionsMock()
{
var featureOptions = new Mock<IOptionService>(MockBehavior.Strict);
featureOptions.Setup(s => s.GetOption(EditorComponentOnOffOptions.Tagger)).Returns(true);
return featureOptions;
}
private sealed class TaggerOperationListener : AsynchronousOperationListener
{
}
private sealed class TestTag : TextMarkerTag
{
public TestTag() :
base("Test")
{
}
}
private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken);
private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag>
{
private readonly Callback _callback;
private readonly ITaggerEventSource _eventSource;
private readonly Workspace _workspace;
private readonly bool _disableCancellation;
public TestTaggerProvider(
Callback callback,
ITaggerEventSource eventSource,
Workspace workspace,
IAsynchronousOperationListener asyncListener,
IForegroundNotificationService notificationService,
bool disableCancellation = false)
: base(asyncListener, notificationService)
{
_callback = callback;
_eventSource = eventSource;
_workspace = workspace;
_disableCancellation = disableCancellation;
}
protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return _eventSource;
}
protected override Task ProduceTagsAsync(TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition)
{
var tags = _callback(snapshotSpan.SnapshotSpan, context.CancellationToken);
if (tags != null)
{
foreach (var tag in tags)
{
context.AddTag(tag);
}
}
return SpecializedTasks.EmptyTask;
}
}
private sealed class TestTaggerEventSource : AbstractTaggerEventSource
{
public TestTaggerEventSource() :
base(delay: TaggerDelay.NearImmediate)
{
}
public void SendUpdateEvent()
{
this.RaiseChanged();
}
public override void Connect()
{
}
public override void Disconnect()
{
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.ChangeControlBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlClassInfo))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlDeprecatedClassInfo))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlInstance))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlInstanceInfo))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlClassTransactionInfo))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlInstanceVariable))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonTimeStamp))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementChangeControlModuleInfo))]
public partial class ManagementChangeControl : iControlInterface {
public ManagementChangeControl() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// delete_instance
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
public void delete_instance(
string [] instance_names
) {
this.Invoke("delete_instance", new object [] {
instance_names});
}
public System.IAsyncResult Begindelete_instance(string [] instance_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_instance", new object[] {
instance_names}, callback, asyncState);
}
public void Enddelete_instance(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_class_info
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementChangeControlClassInfo [] get_class_info(
string filter
) {
object [] results = this.Invoke("get_class_info", new object [] {
filter});
return ((ManagementChangeControlClassInfo [])(results[0]));
}
public System.IAsyncResult Beginget_class_info(string filter, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_class_info", new object[] {
filter}, callback, asyncState);
}
public ManagementChangeControlClassInfo [] Endget_class_info(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementChangeControlClassInfo [])(results[0]));
}
//-----------------------------------------------------------------------
// get_deprecated_class_info
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementChangeControlDeprecatedClassInfo [] get_deprecated_class_info(
string filter
) {
object [] results = this.Invoke("get_deprecated_class_info", new object [] {
filter});
return ((ManagementChangeControlDeprecatedClassInfo [])(results[0]));
}
public System.IAsyncResult Beginget_deprecated_class_info(string filter, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_deprecated_class_info", new object[] {
filter}, callback, asyncState);
}
public ManagementChangeControlDeprecatedClassInfo [] Endget_deprecated_class_info(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementChangeControlDeprecatedClassInfo [])(results[0]));
}
//-----------------------------------------------------------------------
// get_instance
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementChangeControlInstance [] get_instance(
string [] instance_names,
ManagementChangeControlInstanceFormatType instance_format
) {
object [] results = this.Invoke("get_instance", new object [] {
instance_names,
instance_format});
return ((ManagementChangeControlInstance [])(results[0]));
}
public System.IAsyncResult Beginget_instance(string [] instance_names,ManagementChangeControlInstanceFormatType instance_format, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_instance", new object[] {
instance_names,
instance_format}, callback, asyncState);
}
public ManagementChangeControlInstance [] Endget_instance(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementChangeControlInstance [])(results[0]));
}
//-----------------------------------------------------------------------
// get_instance_dependency
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_instance_dependency(
string [] instance_names,
long depth
) {
object [] results = this.Invoke("get_instance_dependency", new object [] {
instance_names,
depth});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_instance_dependency(string [] instance_names,long depth, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_instance_dependency", new object[] {
instance_names,
depth}, callback, asyncState);
}
public string [] [] Endget_instance_dependency(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_instance_info
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementChangeControlInstanceInfo [] [] get_instance_info(
ManagementChangeControlClassTransactionInfo [] classes
) {
object [] results = this.Invoke("get_instance_info", new object [] {
classes});
return ((ManagementChangeControlInstanceInfo [] [])(results[0]));
}
public System.IAsyncResult Beginget_instance_info(ManagementChangeControlClassTransactionInfo [] classes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_instance_info", new object[] {
classes}, callback, asyncState);
}
public ManagementChangeControlInstanceInfo [] [] Endget_instance_info(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementChangeControlInstanceInfo [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_instance_variable
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementChangeControlInstanceVariable [] [] get_instance_variable(
string [] instance_names,
ManagementChangeControlInstanceVariableType instance_variable
) {
object [] results = this.Invoke("get_instance_variable", new object [] {
instance_names,
instance_variable});
return ((ManagementChangeControlInstanceVariable [] [])(results[0]));
}
public System.IAsyncResult Beginget_instance_variable(string [] instance_names,ManagementChangeControlInstanceVariableType instance_variable, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_instance_variable", new object[] {
instance_names,
instance_variable}, callback, asyncState);
}
public ManagementChangeControlInstanceVariable [] [] Endget_instance_variable(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementChangeControlInstanceVariable [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_last_load_time
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonTimeStamp get_last_load_time(
) {
object [] results = this.Invoke("get_last_load_time", new object [0]);
return ((CommonTimeStamp)(results[0]));
}
public System.IAsyncResult Beginget_last_load_time(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_last_load_time", new object[0], callback, asyncState);
}
public CommonTimeStamp Endget_last_load_time(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonTimeStamp)(results[0]));
}
//-----------------------------------------------------------------------
// get_module_info
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementChangeControlModuleInfo [] get_module_info(
string filter
) {
object [] results = this.Invoke("get_module_info", new object [] {
filter});
return ((ManagementChangeControlModuleInfo [])(results[0]));
}
public System.IAsyncResult Beginget_module_info(string filter, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_module_info", new object[] {
filter}, callback, asyncState);
}
public ManagementChangeControlModuleInfo [] Endget_module_info(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementChangeControlModuleInfo [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// put_config
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
public void put_config(
ManagementChangeControlInstanceFormatType instance_format,
string data
) {
this.Invoke("put_config", new object [] {
instance_format,
data});
}
public System.IAsyncResult Beginput_config(ManagementChangeControlInstanceFormatType instance_format,string data, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("put_config", new object[] {
instance_format,
data}, callback, asyncState);
}
public void Endput_config(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// put_instance
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
public void put_instance(
ManagementChangeControlInstance [] instances
) {
this.Invoke("put_instance", new object [] {
instances});
}
public System.IAsyncResult Beginput_instance(ManagementChangeControlInstance [] instances, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("put_instance", new object[] {
instances}, callback, asyncState);
}
public void Endput_instance(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// verify_config
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
public void verify_config(
ManagementChangeControlInstanceFormatType instance_format,
string data
) {
this.Invoke("verify_config", new object [] {
instance_format,
data});
}
public System.IAsyncResult Beginverify_config(ManagementChangeControlInstanceFormatType instance_format,string data, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("verify_config", new object[] {
instance_format,
data}, callback, asyncState);
}
public void Endverify_config(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// verify_instance
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/ChangeControl",
RequestNamespace="urn:iControl:Management/ChangeControl", ResponseNamespace="urn:iControl:Management/ChangeControl")]
public void verify_instance(
ManagementChangeControlInstance [] instances
) {
this.Invoke("verify_instance", new object [] {
instances});
}
public System.IAsyncResult Beginverify_instance(ManagementChangeControlInstance [] instances, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("verify_instance", new object[] {
instances}, callback, asyncState);
}
public void Endverify_instance(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.InstanceFormatType", Namespace = "urn:iControl")]
public enum ManagementChangeControlInstanceFormatType
{
FORMAT_SHELL,
FORMAT_XML,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.InstanceVariableType", Namespace = "urn:iControl")]
public enum ManagementChangeControlInstanceVariableType
{
TYPE_DEVICE,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.ClassInfo", Namespace = "urn:iControl")]
public partial class ManagementChangeControlClassInfo
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private long transaction_idField;
public long transaction_id
{
get { return this.transaction_idField; }
set { this.transaction_idField = value; }
}
private long delete_transaction_idField;
public long delete_transaction_id
{
get { return this.delete_transaction_idField; }
set { this.delete_transaction_idField = value; }
}
private bool supports_deleteField;
public bool supports_delete
{
get { return this.supports_deleteField; }
set { this.supports_deleteField = value; }
}
private bool supports_transaction_idField;
public bool supports_transaction_id
{
get { return this.supports_transaction_idField; }
set { this.supports_transaction_idField = value; }
}
private bool supports_verifyField;
public bool supports_verify
{
get { return this.supports_verifyField; }
set { this.supports_verifyField = value; }
}
private bool is_singletonField;
public bool is_singleton
{
get { return this.is_singletonField; }
set { this.is_singletonField = value; }
}
private bool header_needs_instance_nameField;
public bool header_needs_instance_name
{
get { return this.header_needs_instance_nameField; }
set { this.header_needs_instance_nameField = value; }
}
private bool is_partitionedField;
public bool is_partitioned
{
get { return this.is_partitionedField; }
set { this.is_partitionedField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.ClassTransactionInfo", Namespace = "urn:iControl")]
public partial class ManagementChangeControlClassTransactionInfo
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private long transaction_idField;
public long transaction_id
{
get { return this.transaction_idField; }
set { this.transaction_idField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.DeprecatedClassInfo", Namespace = "urn:iControl")]
public partial class ManagementChangeControlDeprecatedClassInfo
{
private string old_nameField;
public string old_name
{
get { return this.old_nameField; }
set { this.old_nameField = value; }
}
private string new_nameField;
public string new_name
{
get { return this.new_nameField; }
set { this.new_nameField = value; }
}
private string transition_versionField;
public string transition_version
{
get { return this.transition_versionField; }
set { this.transition_versionField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.Instance", Namespace = "urn:iControl")]
public partial class ManagementChangeControlInstance
{
private ManagementChangeControlInstanceInfo infoField;
public ManagementChangeControlInstanceInfo info
{
get { return this.infoField; }
set { this.infoField = value; }
}
private ManagementChangeControlInstanceFormatType formatField;
public ManagementChangeControlInstanceFormatType format
{
get { return this.formatField; }
set { this.formatField = value; }
}
private string dataField;
public string data
{
get { return this.dataField; }
set { this.dataField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.InstanceInfo", Namespace = "urn:iControl")]
public partial class ManagementChangeControlInstanceInfo
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private long transaction_idField;
public long transaction_id
{
get { return this.transaction_idField; }
set { this.transaction_idField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.InstanceVariable", Namespace = "urn:iControl")]
public partial class ManagementChangeControlInstanceVariable
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private string display_nameField;
public string display_name
{
get { return this.display_nameField; }
set { this.display_nameField = value; }
}
private string valueField;
public string value
{
get { return this.valueField; }
set { this.valueField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Management.ChangeControl.ModuleInfo", Namespace = "urn:iControl")]
public partial class ManagementChangeControlModuleInfo
{
private string nameField;
public string name
{
get { return this.nameField; }
set { this.nameField = value; }
}
private long transaction_idField;
public long transaction_id
{
get { return this.transaction_idField; }
set { this.transaction_idField = value; }
}
private long delete_transaction_idField;
public long delete_transaction_id
{
get { return this.delete_transaction_idField; }
set { this.delete_transaction_idField = value; }
}
private bool supports_transaction_idField;
public bool supports_transaction_id
{
get { return this.supports_transaction_idField; }
set { this.supports_transaction_idField = value; }
}
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
/// <summary>
/// Specifies the target CPU architecture.
/// </summary>
public enum TargetArchitecture
{
Unknown,
ARM,
ARMEL,
ARM64,
X64,
X86,
}
/// <summary>
/// Specifies the target ABI.
/// </summary>
public enum TargetOS
{
Unknown,
Windows,
Linux,
OSX,
FreeBSD,
NetBSD,
}
public enum TargetAbi
{
Unknown,
/// <summary>
/// Cross-platform console model
/// </summary>
CoreRT,
/// <summary>
/// Windows-specific UWP model
/// </summary>
ProjectN,
/// <summary>
/// Jit runtime ABI
/// </summary>
Jit
}
/// <summary>
/// Represents various details about the compilation target that affect
/// layout, padding, allocations, or ABI.
/// </summary>
public partial class TargetDetails
{
/// <summary>
/// Gets the target CPU architecture.
/// </summary>
public TargetArchitecture Architecture
{
get;
}
/// <summary>
/// Gets the target ABI.
/// </summary>
public TargetOS OperatingSystem
{
get;
}
public TargetAbi Abi
{
get;
}
/// <summary>
/// Gets the size of a pointer for the target of the compilation.
/// </summary>
public int PointerSize
{
get
{
switch (Architecture)
{
case TargetArchitecture.ARM64:
case TargetArchitecture.X64:
return 8;
case TargetArchitecture.ARM:
case TargetArchitecture.ARMEL:
case TargetArchitecture.X86:
return 4;
default:
throw new NotSupportedException();
}
}
}
/// <summary>
/// Gets the maximum alignment to which something can be aligned
/// </summary>
public static int MaximumAlignment
{
get
{
return 8;
}
}
public LayoutInt LayoutPointerSize => new LayoutInt(PointerSize);
/// <summary>
/// Gets the default field packing size.
/// </summary>
public int DefaultPackingSize
{
get
{
// We use default packing size of 8 irrespective of the platform.
return 8;
}
}
/// <summary>
/// Gets the minimum required method alignment.
/// </summary>
public int MinimumFunctionAlignment
{
get
{
// We use a minimum alignment of 4 irrespective of the platform.
return 4;
}
}
public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi)
{
Architecture = architecture;
OperatingSystem = targetOS;
Abi = abi;
}
/// <summary>
/// Retrieves the size of a well known type.
/// </summary>
public LayoutInt GetWellKnownTypeSize(DefType type)
{
switch (type.Category)
{
case TypeFlags.Void:
return new LayoutInt(PointerSize);
case TypeFlags.Boolean:
return new LayoutInt(1);
case TypeFlags.Char:
return new LayoutInt(2);
case TypeFlags.Byte:
case TypeFlags.SByte:
return new LayoutInt(1);
case TypeFlags.UInt16:
case TypeFlags.Int16:
return new LayoutInt(2);
case TypeFlags.UInt32:
case TypeFlags.Int32:
return new LayoutInt(4);
case TypeFlags.UInt64:
case TypeFlags.Int64:
return new LayoutInt(8);
case TypeFlags.Single:
return new LayoutInt(4);
case TypeFlags.Double:
return new LayoutInt(8);
case TypeFlags.UIntPtr:
case TypeFlags.IntPtr:
return new LayoutInt(PointerSize);
}
// Add new well known types if necessary
throw new InvalidOperationException();
}
/// <summary>
/// Retrieves the alignment required by a well known type.
/// </summary>
public LayoutInt GetWellKnownTypeAlignment(DefType type)
{
// Size == Alignment for all platforms.
return GetWellKnownTypeSize(type);
}
/// <summary>
/// Given an alignment of the fields of a type, determine the alignment that is necessary for allocating the object on the GC heap
/// </summary>
/// <returns></returns>
public LayoutInt GetObjectAlignment(LayoutInt fieldAlignment)
{
switch (Architecture)
{
case TargetArchitecture.ARM:
case TargetArchitecture.ARMEL:
// ARM supports two alignments for objects on the GC heap (4 byte and 8 byte)
if (fieldAlignment.IsIndeterminate)
return LayoutInt.Indeterminate;
if (fieldAlignment.AsInt <= 4)
return new LayoutInt(4);
else
return new LayoutInt(8);
case TargetArchitecture.X64:
return new LayoutInt(8);
case TargetArchitecture.X86:
return new LayoutInt(4);
default:
throw new NotSupportedException();
}
}
/// <summary>
/// Returns True if compiling for Windows
/// </summary>
public bool IsWindows
{
get
{
return OperatingSystem == TargetOS.Windows;
}
}
/// <summary>
/// Maximum number of elements in a HFA type.
/// </summary>
public int MaximumHfaElementCount
{
get
{
// There is a hard limit of 4 elements on an HFA type, see
// http://blogs.msdn.com/b/vcblog/archive/2013/07/12/introducing-vector-calling-convention.aspx
Debug.Assert(Architecture == TargetArchitecture.ARM ||
Architecture == TargetArchitecture.ARMEL ||
Architecture == TargetArchitecture.ARM64 ||
Architecture == TargetArchitecture.X64 ||
Architecture == TargetArchitecture.X86);
return 4;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class AppleCrypto
{
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509ImportCertificate(
byte[] pbKeyBlob,
int cbKeyBlob,
X509ContentType contentType,
SafeCreateHandle cfPfxPassphrase,
SafeKeychainHandle tmpKeychain,
int exportable,
out SafeSecCertificateHandle pCertOut,
out SafeSecIdentityHandle pPrivateKeyOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509ImportCollection(
byte[] pbKeyBlob,
int cbKeyBlob,
X509ContentType contentType,
SafeCreateHandle cfPfxPassphrase,
SafeKeychainHandle tmpKeychain,
int exportable,
out SafeCFArrayHandle pCollectionOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509GetRawData(
SafeSecCertificateHandle cert,
out SafeCFDataHandle cfDataOut,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509GetPublicKey(SafeSecCertificateHandle cert, out SafeSecKeyRefHandle publicKey, out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_X509GetContentType")]
internal static extern X509ContentType X509GetContentType(byte[] pbData, int cbData);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509CopyCertFromIdentity(
SafeSecIdentityHandle identity,
out SafeSecCertificateHandle cert);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509CopyPrivateKeyFromIdentity(
SafeSecIdentityHandle identity,
out SafeSecKeyRefHandle key);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509DemuxAndRetainHandle(
IntPtr handle,
out SafeSecCertificateHandle certHandle,
out SafeSecIdentityHandle identityHandle);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_X509ExportData(
SafeCreateHandle data,
X509ContentType type,
SafeCreateHandle cfExportPassphrase,
out SafeCFDataHandle pExportOut,
out int pOSStatus);
internal static byte[] X509GetRawData(SafeSecCertificateHandle cert)
{
int osStatus;
SafeCFDataHandle data;
int ret = AppleCryptoNative_X509GetRawData(
cert,
out data,
out osStatus);
if (ret == 1)
{
return CoreFoundation.CFGetData(data);
}
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
internal static SafeSecCertificateHandle X509ImportCertificate(
byte[] bytes,
X509ContentType contentType,
SafePasswordHandle importPassword,
SafeKeychainHandle keychain,
bool exportable,
out SafeSecIdentityHandle identityHandle)
{
SafeSecCertificateHandle certHandle;
int osStatus;
int ret;
SafeCreateHandle cfPassphrase = s_nullExportString;
bool releasePassword = false;
try
{
if (!importPassword.IsInvalid)
{
importPassword.DangerousAddRef(ref releasePassword);
IntPtr passwordHandle = importPassword.DangerousGetHandle();
if (passwordHandle != IntPtr.Zero)
{
cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle);
}
}
ret = AppleCryptoNative_X509ImportCertificate(
bytes,
bytes.Length,
contentType,
cfPassphrase,
keychain,
exportable ? 1 : 0,
out certHandle,
out identityHandle,
out osStatus);
SafeTemporaryKeychainHandle.TrackItem(certHandle);
SafeTemporaryKeychainHandle.TrackItem(identityHandle);
}
finally
{
if (releasePassword)
{
importPassword.DangerousRelease();
}
if (cfPassphrase != s_nullExportString)
{
cfPassphrase.Dispose();
}
}
if (ret == 1)
{
return certHandle;
}
certHandle.Dispose();
identityHandle.Dispose();
const int SeeOSStatus = 0;
const int ImportReturnedEmpty = -2;
const int ImportReturnedNull = -3;
switch (ret)
{
case SeeOSStatus:
throw CreateExceptionForOSStatus(osStatus);
case ImportReturnedNull:
case ImportReturnedEmpty:
throw new CryptographicException();
default:
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
}
internal static SafeCFArrayHandle X509ImportCollection(
byte[] bytes,
X509ContentType contentType,
SafePasswordHandle importPassword,
SafeKeychainHandle keychain,
bool exportable)
{
SafeCreateHandle cfPassphrase = s_nullExportString;
bool releasePassword = false;
int ret;
SafeCFArrayHandle collectionHandle;
int osStatus;
try
{
if (!importPassword.IsInvalid)
{
importPassword.DangerousAddRef(ref releasePassword);
IntPtr passwordHandle = importPassword.DangerousGetHandle();
if (passwordHandle != IntPtr.Zero)
{
cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle);
}
}
ret = AppleCryptoNative_X509ImportCollection(
bytes,
bytes.Length,
contentType,
cfPassphrase,
keychain,
exportable ? 1 : 0,
out collectionHandle,
out osStatus);
if (ret == 1)
{
return collectionHandle;
}
}
finally
{
if (releasePassword)
{
importPassword.DangerousRelease();
}
if (cfPassphrase != s_nullExportString)
{
cfPassphrase.Dispose();
}
}
collectionHandle.Dispose();
const int SeeOSStatus = 0;
const int ImportReturnedEmpty = -2;
const int ImportReturnedNull = -3;
switch (ret)
{
case SeeOSStatus:
throw CreateExceptionForOSStatus(osStatus);
case ImportReturnedNull:
case ImportReturnedEmpty:
throw new CryptographicException();
default:
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
}
internal static SafeSecCertificateHandle X509GetCertFromIdentity(SafeSecIdentityHandle identity)
{
SafeSecCertificateHandle cert;
int osStatus = AppleCryptoNative_X509CopyCertFromIdentity(identity, out cert);
SafeTemporaryKeychainHandle.TrackItem(cert);
if (osStatus != 0)
{
cert.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
if (cert.IsInvalid)
{
cert.Dispose();
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
return cert;
}
internal static SafeSecKeyRefHandle X509GetPrivateKeyFromIdentity(SafeSecIdentityHandle identity)
{
SafeSecKeyRefHandle key;
int osStatus = AppleCryptoNative_X509CopyPrivateKeyFromIdentity(identity, out key);
SafeTemporaryKeychainHandle.TrackItem(key);
if (osStatus != 0)
{
key.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
if (key.IsInvalid)
{
key.Dispose();
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
return key;
}
internal static SafeSecKeyRefHandle X509GetPublicKey(SafeSecCertificateHandle cert)
{
SafeSecKeyRefHandle publicKey;
int osStatus;
int ret = AppleCryptoNative_X509GetPublicKey(cert, out publicKey, out osStatus);
SafeTemporaryKeychainHandle.TrackItem(publicKey);
if (ret == 1)
{
return publicKey;
}
publicKey.Dispose();
if (ret == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"Unexpected return value {ret}");
throw new CryptographicException();
}
internal static bool X509DemuxAndRetainHandle(
IntPtr handle,
out SafeSecCertificateHandle certHandle,
out SafeSecIdentityHandle identityHandle)
{
int result = AppleCryptoNative_X509DemuxAndRetainHandle(handle, out certHandle, out identityHandle);
SafeTemporaryKeychainHandle.TrackItem(certHandle);
SafeTemporaryKeychainHandle.TrackItem(identityHandle);
switch (result)
{
case 1:
return true;
case 0:
return false;
default:
Debug.Fail($"AppleCryptoNative_X509DemuxAndRetainHandle returned {result}");
throw new CryptographicException();
}
}
private static byte[] X509Export(X509ContentType contentType, SafeCreateHandle cfPassphrase, IntPtr[] certHandles)
{
Debug.Assert(contentType == X509ContentType.Pkcs7 || contentType == X509ContentType.Pkcs12);
using (SafeCreateHandle handlesArray = CoreFoundation.CFArrayCreate(certHandles, (UIntPtr)certHandles.Length))
{
SafeCFDataHandle exportData;
int osStatus;
int result = AppleCryptoNative_X509ExportData(
handlesArray,
contentType,
cfPassphrase,
out exportData,
out osStatus);
using (exportData)
{
if (result != 1)
{
if (result == 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
Debug.Fail($"Unexpected result from AppleCryptoNative_X509ExportData: {result}");
throw new CryptographicException();
}
Debug.Assert(!exportData.IsInvalid, "Successful export yielded no data");
return CoreFoundation.CFGetData(exportData);
}
}
}
internal static byte[] X509ExportPkcs7(IntPtr[] certHandles)
{
return X509Export(X509ContentType.Pkcs7, s_nullExportString, certHandles);
}
internal static byte[] X509ExportPfx(IntPtr[] certHandles, SafePasswordHandle exportPassword)
{
SafeCreateHandle cfPassphrase = s_emptyExportString;
bool releasePassword = false;
try
{
if (!exportPassword.IsInvalid)
{
exportPassword.DangerousAddRef(ref releasePassword);
IntPtr passwordHandle = exportPassword.DangerousGetHandle();
if (passwordHandle != IntPtr.Zero)
{
cfPassphrase = CoreFoundation.CFStringCreateWithCString(passwordHandle);
}
}
return X509Export(X509ContentType.Pkcs12, cfPassphrase, certHandles);
}
finally
{
if (releasePassword)
{
exportPassword.DangerousRelease();
}
if (cfPassphrase != s_emptyExportString)
{
cfPassphrase.Dispose();
}
}
}
}
}
namespace System.Security.Cryptography.X509Certificates
{
internal sealed class SafeSecIdentityHandle : SafeKeychainItemHandle
{
public SafeSecIdentityHandle()
{
}
}
internal sealed class SafeSecCertificateHandle : SafeKeychainItemHandle
{
public SafeSecCertificateHandle()
{
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.PythonTools.Editor;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Language;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools;
using IServiceProvider = System.IServiceProvider;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.PythonTools.Navigation {
class CodeWindowManager : IVsCodeWindowManager, IVsCodeWindowEvents {
private readonly IServiceProvider _serviceProvider;
private readonly IVsCodeWindow _window;
private IWpfTextView _curView;
private readonly PythonToolsService _pyService;
private uint _cookieVsCodeWindowEvents;
private DropDownBarClient _client;
private int _viewCount;
private IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService;
public CodeWindowManager(IServiceProvider serviceProvider, IVsCodeWindow codeWindow) {
_serviceProvider = serviceProvider;
_window = codeWindow;
_pyService = _serviceProvider.GetPythonToolsService();
}
#region IVsCodeWindowManager Members
public int AddAdornments() {
IVsTextView textView;
if (ErrorHandler.Succeeded(_window.GetPrimaryView(out textView))) {
((IVsCodeWindowEvents)this).OnNewView(textView);
}
if (ErrorHandler.Succeeded(_window.GetSecondaryView(out textView))) {
((IVsCodeWindowEvents)this).OnNewView(textView);
}
AddDropDownBarAsync(_pyService).SilenceException<OperationCanceledException>().DoNotWait();
return VSConstants.S_OK;
}
private async Task AddDropDownBarAsync(PythonToolsService service) {
var prefs = await _pyService.GetLangPrefsAsync();
if (prefs.NavigationBar) {
AddDropDownBar(false);
}
}
private bool TryGetTextView(IVsTextView vsTextView, out IWpfTextView view) {
if (vsTextView == null) {
view = null;
return false;
}
view = VsEditorAdaptersFactoryService.GetWpfTextView(vsTextView);
if (view == null) {
return false;
}
if (view.TextBuffer.ContentType.IsOfType(CodeRemoteContentDefinition.CodeRemoteContentTypeName)) {
// This is not really our text view
view = null;
return false;
}
return true;
}
private int AddDropDownBar(bool refresh) {
var cpc = (IConnectionPointContainer)_window;
if (cpc != null) {
IConnectionPoint cp;
cpc.FindConnectionPoint(typeof(IVsCodeWindowEvents).GUID, out cp);
if (cp != null) {
cp.Advise(this, out _cookieVsCodeWindowEvents);
}
}
IVsTextView vsTextView;
if (!ErrorHandler.Succeeded(_window.GetLastActiveView(out vsTextView)) ||
!TryGetTextView(vsTextView, out var view)) {
return VSConstants.E_FAIL;
}
_client = new DropDownBarClient(_serviceProvider, view);
var result = _client.Register((IVsDropdownBarManager)_window);
if (refresh) {
var entry = view.TryGetAnalysisEntry(_serviceProvider);
if (entry != null && entry.IsAnalyzed) {
_client.RefreshNavigationsFromAnalysisEntry(entry)
.HandleAllExceptions(_serviceProvider, GetType())
.DoNotWait();
}
}
return result;
}
private int RemoveDropDownBar() {
var cpc = (IConnectionPointContainer)_window;
if (cpc != null) {
IConnectionPoint cp;
cpc.FindConnectionPoint(typeof(IVsCodeWindowEvents).GUID, out cp);
if (cp != null) {
cp.Unadvise(_cookieVsCodeWindowEvents);
}
}
if (_client != null) {
return _client.Unregister((IVsDropdownBarManager)_window);
}
return VSConstants.S_OK;
}
public int OnNewView(IVsTextView pView) {
// NO-OP We use IVsCodeWindowEvents to track text view lifetime
return VSConstants.S_OK;
}
public int RemoveAdornments() {
IVsTextView textView;
if (ErrorHandler.Succeeded(_window.GetPrimaryView(out textView))) {
((IVsCodeWindowEvents)this).OnCloseView(textView);
}
if (ErrorHandler.Succeeded(_window.GetSecondaryView(out textView))) {
((IVsCodeWindowEvents)this).OnCloseView(textView);
}
return RemoveDropDownBar();
}
public int ToggleNavigationBar(bool fEnable) {
return fEnable ? AddDropDownBar(true) : RemoveDropDownBar();
}
#endregion
#region IVsCodeWindowEvents Members
int IVsCodeWindowEvents.OnNewView(IVsTextView vsTextView) {
_viewCount++;
if (TryGetTextView(vsTextView, out var wpfTextView)) {
var services = ComponentModel.GetService<PythonEditorServices>();
EditFilter.GetOrCreate(services, vsTextView);
new TextViewFilter(services, vsTextView);
wpfTextView.GotAggregateFocus += OnTextViewGotAggregateFocus;
wpfTextView.LostAggregateFocus += OnTextViewLostAggregateFocus;
}
return VSConstants.S_OK;
}
int IVsCodeWindowEvents.OnCloseView(IVsTextView vsTextView) {
_viewCount--;
if (_viewCount == 0) {
_pyService.CodeWindowClosed(_window);
}
_pyService.OnIdle -= OnIdle;
if (TryGetTextView(vsTextView, out var wpfTextView)) {
wpfTextView.GotAggregateFocus -= OnTextViewGotAggregateFocus;
wpfTextView.LostAggregateFocus -= OnTextViewLostAggregateFocus;
}
return VSConstants.S_OK;
}
private void OnTextViewGotAggregateFocus(object sender, EventArgs e) {
var wpfTextView = sender as IWpfTextView;
if (wpfTextView != null) {
_curView = wpfTextView;
if (_client != null) {
_client.UpdateView(wpfTextView);
}
_pyService.OnIdle += OnIdle;
}
}
private void OnTextViewLostAggregateFocus(object sender, EventArgs e) {
var wpfTextView = sender as IWpfTextView;
if (wpfTextView != null) {
_curView = null;
_pyService.OnIdle -= OnIdle;
}
}
private IComponentModel ComponentModel {
get {
return (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
}
}
private IVsEditorAdaptersFactoryService VsEditorAdaptersFactoryService {
get {
if (_vsEditorAdaptersFactoryService == null) {
_vsEditorAdaptersFactoryService = ComponentModel.GetService<IVsEditorAdaptersFactoryService>();
}
return _vsEditorAdaptersFactoryService;
}
}
#endregion
private void OnIdle(object sender, ComponentManagerEventArgs eventArgs) {
if (_curView!= null) {
EditFilter editFilter;
if (_curView.Properties.TryGetProperty(typeof(EditFilter), out editFilter) && editFilter != null) {
editFilter.DoIdle((IOleComponentManager)_serviceProvider.GetService(typeof(SOleComponentManager)));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using IrcDotNet.Properties;
#if !SILVERLIGHT
using System.Net.Security;
#endif
namespace IrcDotNet
{
/// <inheritdoc />
public class StandardIrcClient : IrcClient
{
// Minimum duration of time to wait between sending successive raw messages.
private const long minimumSendWaitTime = 50;
// Size of buffer for data received by socket, in bytes.
private const int socketReceiveBufferSize = 0xFFFF;
private Stream dataStream;
private SafeLineReader dataStreamLineReader;
private StreamReader dataStreamReader;
private AutoResetEvent disconnectedEvent;
// Queue of pending messages and their tokens to be sent when ready.
private readonly Queue<Tuple<string, object>> messageSendQueue;
private CircularBufferStream receiveStream;
private Timer sendTimer;
// Network (TCP) I/O.
private Socket socket;
public StandardIrcClient()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sendTimer = new Timer(WritePendingMessages, null,
Timeout.Infinite, Timeout.Infinite);
disconnectedEvent = new AutoResetEvent(false);
messageSendQueue = new Queue<Tuple<string, object>>();
}
public override bool IsConnected
{
get
{
CheckDisposed();
return socket != null && socket.Connected;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (socket != null)
{
socket.Dispose();
socket = null;
HandleClientDisconnected();
}
if (receiveStream != null)
{
receiveStream.Dispose();
receiveStream = null;
}
if (dataStream != null)
{
dataStream.Dispose();
dataStream = null;
}
if (dataStreamReader != null)
{
dataStreamReader.Dispose();
dataStreamReader = null;
}
if (sendTimer != null)
{
sendTimer.Dispose();
sendTimer = null;
}
if (disconnectedEvent != null)
{
disconnectedEvent.Dispose();
disconnectedEvent = null;
}
}
}
protected override void WriteMessage(string line, object token)
{
// Add message line to send queue.
messageSendQueue.Enqueue(Tuple.Create(line + Environment.NewLine, token));
}
/// <inheritdoc cref="Connect(string, int, bool, IrcRegistrationInfo)" />
/// <summary>
/// Connects to a server using the specified URL and user information.
/// </summary>
public void Connect(Uri url, IrcRegistrationInfo registrationInfo)
{
CheckDisposed();
if (registrationInfo == null)
throw new ArgumentNullException("registrationInfo");
// Check URL scheme and decide whether to use SSL.
bool useSsl;
if (url.Scheme == "irc")
useSsl = false;
else if (url.Scheme == "ircs")
useSsl = true;
else
throw new ArgumentException(string.Format(Resources.MessageInvalidUrlScheme,
url.Scheme), "url");
Connect(url.Host, url.Port == -1 ? DefaultPort : url.Port, useSsl, registrationInfo);
}
/// <inheritdoc cref="Connect(string, int, bool, IrcRegistrationInfo)" />
public void Connect(string hostName, bool useSsl, IrcRegistrationInfo registrationInfo)
{
CheckDisposed();
if (registrationInfo == null)
throw new ArgumentNullException("registrationInfo");
Connect(hostName, DefaultPort, useSsl, registrationInfo);
}
/// <inheritdoc cref="Connect(EndPoint, bool, IrcRegistrationInfo)" />
/// <param name="hostName">The name of the remote host.</param>
/// <param name="port">The port number of the remote host.</param>
public void Connect(string hostName, int port, bool useSsl, IrcRegistrationInfo registrationInfo)
{
CheckDisposed();
if (registrationInfo == null)
throw new ArgumentNullException("registrationInfo");
#if NETSTANDARD1_5
var dnsTask = Dns.GetHostAddressesAsync(hostName);
var addresses = dnsTask.Result;
Connect(new IPEndPoint(addresses[0], port), useSsl, registrationInfo);
#else
Connect(new DnsEndPoint(hostName, port), useSsl, registrationInfo);
#endif
}
/// <inheritdoc cref="Connect(IPAddress, int, bool, IrcRegistrationInfo)" />
public void Connect(IPAddress address, bool useSsl, IrcRegistrationInfo registrationInfo)
{
CheckDisposed();
if (registrationInfo == null)
throw new ArgumentNullException("registrationInfo");
Connect(address, DefaultPort, useSsl, registrationInfo);
}
/// <inheritdoc cref="Connect(EndPoint, bool, IrcRegistrationInfo)" />
/// <param name="address">An IP addresses that designates the remote host.</param>
/// <param name="port">The port number of the remote host.</param>
public void Connect(IPAddress address, int port, bool useSsl, IrcRegistrationInfo registrationInfo)
{
CheckDisposed();
if (registrationInfo == null)
throw new ArgumentNullException("registrationInfo");
Connect(new IPEndPoint(address, port), useSsl, registrationInfo);
}
/// <summary>
/// Connects asynchronously to the specified server.
/// </summary>
/// <param name="remoteEndPoint">
/// The network endpoint (IP address and port) of the server to which to connect.
/// </param>
/// <param name="useSsl">
/// <see langword="true" /> to connect to the server via SSL; <see langword="false" />,
/// otherwise
/// </param>
/// <param name="registrationInfo">
/// The information used for registering the client.
/// The type of the object may be either <see cref="IrcUserRegistrationInfo" /> or
/// <see cref="IrcServiceRegistrationInfo" />.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="registrationInfo" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="registrationInfo" /> does not specify valid registration
/// information.
/// </exception>
/// <exception cref="ObjectDisposedException">The current instance has already been disposed.</exception>
public virtual void Connect(EndPoint remoteEndPoint, bool useSsl, IrcRegistrationInfo registrationInfo)
{
Connect(registrationInfo);
// Connect socket to remote host.
ConnectAsync(remoteEndPoint, Tuple.Create(useSsl, string.Empty, registrationInfo));
HandleClientConnecting();
}
public override void Quit(int timeout, string comment)
{
base.Quit(timeout, comment);
if (!disconnectedEvent.WaitOne(timeout))
Disconnect();
}
protected override void ResetState()
{
base.ResetState();
// Reset network I/O objects.
if (receiveStream != null)
receiveStream.Dispose();
if (dataStream != null)
dataStream.Dispose();
if (dataStreamReader != null)
dataStreamReader = null;
}
private void WritePendingMessages(object state)
{
try
{
// Send pending messages in queue until flood preventer indicates to stop.
long sendDelay = 0;
while (messageSendQueue.Count > 0)
{
Debug.Assert(messageSendQueue.Count < 100);
// Check that flood preventer currently permits sending of messages.
if (FloodPreventer != null)
{
sendDelay = FloodPreventer.GetSendDelay();
if (sendDelay > 0)
break;
}
// Send next message in queue.
var message = messageSendQueue.Dequeue();
var line = message.Item1;
var token = message.Item2;
var lineBuffer = TextEncoding.GetBytes(line);
SendAsync(lineBuffer, token);
// Tell flood preventer mechanism that message has just been sent.
if (FloodPreventer != null)
FloodPreventer.HandleMessageSent();
}
// Make timer fire when next message in send queue should be written.
sendTimer.Change((int)Math.Max(sendDelay, minimumSendWaitTime), Timeout.Infinite);
}
catch (SocketException exSocket)
{
HandleSocketError(exSocket);
}
catch (ObjectDisposedException)
{
// Ignore.
}
#if !DEBUG
catch (Exception ex)
{
OnError(new IrcErrorEventArgs(ex));
}
#endif
finally
{
}
}
public override void Disconnect()
{
base.Disconnect();
DisconnectAsync();
}
private void SendAsync(byte[] buffer, object token = null)
{
SendAsync(buffer, 0, buffer.Length, token);
}
private void SendAsync(byte[] buffer, int offset, int count, object token = null)
{
// Write data from buffer to socket asynchronously.
var sendEventArgs = new SocketAsyncEventArgs();
sendEventArgs.SetBuffer(buffer, offset, count);
sendEventArgs.UserToken = token;
sendEventArgs.Completed += SendCompleted;
if (!socket.SendAsync(sendEventArgs))
SendCompleted(socket, sendEventArgs);
}
private void SendCompleted(object sender, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError != SocketError.Success)
{
HandleSocketError(e.SocketError);
return;
}
// Handle sent IRC message.
Debug.Assert(e.UserToken != null);
var messageSentEventArgs = (IrcRawMessageEventArgs) e.UserToken;
OnRawMessageSent(messageSentEventArgs);
#if DEBUG
DebugUtilities.WriteIrcRawLine(this, "<<< " + messageSentEventArgs.RawContent);
#endif
}
catch (ObjectDisposedException)
{
// Ignore.
}
#if !DEBUG
catch (Exception ex)
{
OnError(new IrcErrorEventArgs(ex));
}
#endif
finally
{
e.Dispose();
}
}
private void ReceiveAsync()
{
// Read data received from socket to buffer asynchronously.
var receiveEventArgs = new SocketAsyncEventArgs();
Debug.Assert(receiveStream.Buffer.Length - (int) receiveStream.WritePosition > 0);
receiveEventArgs.SetBuffer(receiveStream.Buffer, (int) receiveStream.WritePosition,
receiveStream.Buffer.Length - (int) receiveStream.WritePosition);
receiveEventArgs.Completed += ReceiveCompleted;
if (!socket.ReceiveAsync(receiveEventArgs))
ReceiveCompleted(socket, receiveEventArgs);
}
private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError != SocketError.Success)
{
HandleSocketError(e.SocketError);
return;
}
// Check if remote host has closed connection.
if (e.BytesTransferred == 0)
{
Disconnect();
return;
}
// Indicate that block of data has been read into receive buffer.
receiveStream.WritePosition += e.BytesTransferred;
dataStreamReader.DiscardBufferedData();
// Read each terminated line of characters from data stream.
while (true)
{
// Read next line from data stream.
var line = dataStreamLineReader.ReadLine();
if (line == null)
break;
if (line.Length == 0)
continue;
ParseMessage(line);
}
// Continue reading data from socket.
ReceiveAsync();
}
catch (SocketException exSocket)
{
HandleSocketError(exSocket);
}
catch (ObjectDisposedException)
{
// Ignore.
}
#if !DEBUG
catch (Exception ex)
{
OnError(new IrcErrorEventArgs(ex));
}
#endif
finally
{
e.Dispose();
}
}
private void ConnectAsync(EndPoint remoteEndPoint, object token = null)
{
// Connect socket to remote endpoint asynchronously.
var connectEventArgs = new SocketAsyncEventArgs();
connectEventArgs.RemoteEndPoint = remoteEndPoint;
connectEventArgs.UserToken = token;
connectEventArgs.Completed += ConnectCompleted;
if (!socket.ConnectAsync(connectEventArgs))
ConnectCompleted(socket, connectEventArgs);
}
private void ConnectCompleted(object sender, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError != SocketError.Success)
{
HandleSocketError(e.SocketError);
return;
}
Debug.Assert(e.UserToken != null);
var token = (Tuple<bool, string, IrcRegistrationInfo>) e.UserToken;
// Create stream for received data. Use SSL stream on top of network stream, if specified.
receiveStream = new CircularBufferStream(socketReceiveBufferSize);
#if SILVERLIGHT
this.dataStream = this.receiveStream;
#else
dataStream = GetDataStream(token.Item1, token.Item2);
#endif
dataStreamReader = new StreamReader(dataStream, TextEncoding);
dataStreamLineReader = new SafeLineReader(dataStreamReader);
// Start sending and receiving data to/from server.
sendTimer.Change(0, Timeout.Infinite);
ReceiveAsync();
HandleClientConnected(token.Item3);
}
catch (SocketException exSocket)
{
HandleSocketError(exSocket);
}
catch (ObjectDisposedException)
{
// Ignore.
}
#if !DEBUG
catch (Exception ex)
{
OnConnectFailed(new IrcErrorEventArgs(ex));
}
#endif
finally
{
e.Dispose();
}
}
private void DisconnectAsync()
{
// Connect socket to remote endpoint asynchronously.
var disconnectEventArgs = new SocketAsyncEventArgs();
disconnectEventArgs.Completed += DisconnectCompleted;
#if SILVERLIGHT || NETSTANDARD1_5
this.socket.Shutdown(SocketShutdown.Both);
disconnectEventArgs.SocketError = SocketError.Success;
DisconnectCompleted(socket, disconnectEventArgs);
#else
disconnectEventArgs.DisconnectReuseSocket = true;
if (!socket.DisconnectAsync(disconnectEventArgs))
DisconnectCompleted(socket, disconnectEventArgs);
#endif
}
private void DisconnectCompleted(object sender, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError != SocketError.Success)
{
HandleSocketError(e.SocketError);
return;
}
HandleClientDisconnected();
}
catch (SocketException exSocket)
{
HandleSocketError(exSocket);
}
catch (ObjectDisposedException)
{
// Ignore.
}
#if !DEBUG
catch (Exception ex)
{
OnError(new IrcErrorEventArgs(ex));
}
#endif
finally
{
e.Dispose();
}
}
protected override void HandleClientConnected(IrcRegistrationInfo regInfo)
{
DebugUtilities.WriteEvent(string.Format("Connected to server at '{0}'.",
((IPEndPoint) socket.RemoteEndPoint).Address));
base.HandleClientConnected(regInfo);
}
protected override void HandleClientDisconnected()
{
// Ensure that client has not already handled disconnection.
if (disconnectedEvent.WaitOne(0))
return;
DebugUtilities.WriteEvent("Disconnected from server.");
// Stop sending messages immediately.
sendTimer.Change(Timeout.Infinite, Timeout.Infinite);
// Set that client has disconnected.
disconnectedEvent.Set();
base.HandleClientDisconnected();
}
private void HandleSocketError(SocketError error)
{
HandleSocketError(new SocketException((int) error));
}
private void HandleSocketError(SocketException exception)
{
switch (exception.SocketErrorCode)
{
case SocketError.NotConnected:
case SocketError.ConnectionReset:
HandleClientDisconnected();
return;
default:
OnError(new IrcErrorEventArgs(exception));
return;
}
}
/// <summary>
/// Returns a string representation of this instance.
/// </summary>
/// <returns>A string that represents this instance.</returns>
public override string ToString()
{
if (!IsDisposed && IsConnected)
return string.Format("{0}@{1}", LocalUser.UserName,
ServerName ?? socket.RemoteEndPoint.ToString());
return "(Not connected)";
}
#if !SILVERLIGHT
private Stream GetDataStream(bool useSsl, string targetHost)
{
if (useSsl)
{
// Create SSL stream over network stream to use for data transmission.
var sslStream = new SslStream(receiveStream, true,
SslUserCertificateValidationCallback);
#if NETSTANDARD1_5
var authTask = sslStream.AuthenticateAsClientAsync(targetHost);
authTask.Wait();
#else
sslStream.AuthenticateAsClient(targetHost);
#endif
Debug.Assert(sslStream.IsAuthenticated);
return sslStream;
}
// Use network stream directly for data transmission.
return receiveStream;
}
private bool SslUserCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// Raise an event to decide whether the certificate is valid.
var eventArgs = new IrcValidateSslCertificateEventArgs(certificate, chain, sslPolicyErrors);
eventArgs.IsValid = true;
OnValidateSslCertificate(eventArgs);
return eventArgs.IsValid;
}
#endif
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Runtime.Remoting.Messaging.MethodResponse.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Runtime.Remoting.Messaging
{
public partial class MethodResponse : IMethodReturnMessage, IMethodMessage, IMessage, System.Runtime.Serialization.ISerializable, ISerializationRootObject, IInternalMessage
{
#region Methods and constructors
public Object GetArg(int argNum)
{
return default(Object);
}
public string GetArgName(int index)
{
return default(string);
}
public virtual new void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
}
public Object GetOutArg(int argNum)
{
return default(Object);
}
public string GetOutArgName(int index)
{
return default(string);
}
public virtual new Object HeaderHandler(Header[] h)
{
return default(Object);
}
public MethodResponse(Header[] h1, IMethodCallMessage mcm)
{
}
public void RootSetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext ctx)
{
}
bool System.Runtime.Remoting.Messaging.IInternalMessage.HasProperties()
{
return default(bool);
}
void System.Runtime.Remoting.Messaging.IInternalMessage.SetCallContext(LogicalCallContext newCallContext)
{
}
void System.Runtime.Remoting.Messaging.IInternalMessage.SetURI(string val)
{
}
#endregion
#region Properties and indexers
public int ArgCount
{
get
{
return default(int);
}
}
public Object[] Args
{
get
{
return default(Object[]);
}
}
public Exception Exception
{
get
{
return default(Exception);
}
}
public bool HasVarArgs
{
get
{
return default(bool);
}
}
public LogicalCallContext LogicalCallContext
{
get
{
return default(LogicalCallContext);
}
}
public System.Reflection.MethodBase MethodBase
{
get
{
return default(System.Reflection.MethodBase);
}
}
public string MethodName
{
get
{
return default(string);
}
}
public Object MethodSignature
{
get
{
return default(Object);
}
}
public int OutArgCount
{
get
{
return default(int);
}
}
public Object[] OutArgs
{
get
{
return default(Object[]);
}
}
public virtual new System.Collections.IDictionary Properties
{
get
{
return default(System.Collections.IDictionary);
}
}
public Object ReturnValue
{
get
{
return default(Object);
}
}
public string TypeName
{
get
{
return default(string);
}
}
public string Uri
{
get
{
return default(string);
}
set
{
}
}
#endregion
#region Fields
protected System.Collections.IDictionary ExternalProperties;
protected System.Collections.IDictionary InternalProperties;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// String.SubString(Int32)
/// Retrieves a substring from this instance. The substring starts at a specified character position.
/// </summary>
public class StringSubString1
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringSubString1 sss = new StringSubString1();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.SubString(Int32)");
if(sss.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Start index is valid random value.";
const string c_TEST_ID = "P001";
string strSrc;
int startIndex;
bool condition = false;
bool expectedValue = true;
bool actualValue = false;
//Initialize the parameters
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = TestLibrary.Generator.GetInt32(-55) % (strSrc.Length);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string subStr = strSrc.Substring(startIndex);
condition = true;
for (int i = 0; i < subStr.Length; i++)
{
condition = (subStr[i] == strSrc[i + startIndex]) && condition;
}
actualValue = condition;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, startIndex);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: startIndex equals the length of this instance.";
const string c_TEST_ID = "P002";
string strSrc;
int startIndex;
bool condition = false;
bool expectedValue = true;
bool actualValue = false;
//Initialize the parameters
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = strSrc.Length;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string subStr = strSrc.Substring(startIndex);
condition = (0 == String.CompareOrdinal(string.Empty, subStr));
actualValue = condition;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, startIndex);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex));
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenarios
//ArgumentOutOfRangeException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Start index is negative";
const string c_TEST_ID = "N001";
string strSrc;
int startIndex;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Substring(startIndex);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{}
catch(Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: Start index is greater than string length";
const string c_TEST_ID = "N002";
string strSrc;
int startIndex;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
startIndex = GetInt32(strSrc.Length + 1, Int32.MaxValue);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Substring(startIndex);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected." + GetDataString(strSrc, startIndex));
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, startIndex));
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
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;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
private string GetDataString(string strSrc, int startIndex)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Start index]\n{0}", startIndex);
return str;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export(typeof(MiscellaneousFilesWorkspace))]
internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
{
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsTextManager _textManager;
private readonly RoslynDocumentProvider _documentProvider;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
private readonly HashSet<DocumentKey> _filesInProjects = new HashSet<DocumentKey>();
private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();
private readonly ImmutableArray<MetadataReference> _metadataReferences;
private uint _runningDocumentTableEventsCookie;
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
[ImportingConstructor]
public MiscellaneousFilesWorkspace(
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
SaveEventsService saveEventsService,
VisualStudioWorkspace visualStudioWorkspace,
SVsServiceProvider serviceProvider) :
base(visualStudioWorkspace.Services.HostServices, "MiscellaneousFiles")
{
_editorAdaptersFactoryService = editorAdaptersFactoryService;
_fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
_runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);
_metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
_documentProvider = new RoslynDocumentProvider(this, serviceProvider);
saveEventsService.StartSendingSaveEvents();
}
public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension, ParseOptions parseOptions)
{
_languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension, parseOptions));
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
private LanguageInformation TryGetLanguageInformation(string filename)
{
Guid fileLanguageGuid;
LanguageInformation languageInformation = null;
if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out fileLanguageGuid)))
{
_languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
}
return languageInformation;
}
private IEnumerable<MetadataReference> CreateMetadataReferences()
{
var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var searchPaths = ReferencePathUtilities.GetReferencePaths();
return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
where fullPath != null
select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
}
internal void OnFileIncludedInProject(IVisualStudioHostDocument document)
{
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.FilePath, out docCookie))
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, document.FilePath);
}
_filesInProjects.Add(document.Key);
}
internal void OnFileRemovedFromProject(IVisualStudioHostDocument document)
{
// Remove the document key from the filesInProjects map first because adding documents
// to the misc files workspace requires that they not appear in this map.
_filesInProjects.Remove(document.Key);
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.Key.Moniker, out docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, document.Key.Moniker);
}
}
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
{
return VSConstants.S_OK;
}
public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
// Did we rename?
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
// We want to consider this file to be added in one of two situations:
//
// 1) the old file already was a misc file, at which point we might just be doing a rename from
// one name to another with the same extension
// 2) the old file was a different extension that we weren't tracking, which may have now changed
if (TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
{
// Add the new one, if appropriate.
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, pszMkDocumentNew);
}
}
// When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
// OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
// add misc files, so we'll do the same.
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, moniker);
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterSave(uint docCookie)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
private void AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(uint docCookie, string moniker)
{
var languageInformation = TryGetLanguageInformation(moniker);
if (languageInformation != null &&
!_filesInProjects.Any(d => StringComparer.OrdinalIgnoreCase.Equals(d.Moniker, moniker)) &&
!_docCookiesToHostProject.ContainsKey(docCookie))
{
// See if we should push to this to the metadata-to-source workspace instead.
if (_runningDocumentTable.IsDocumentInitialized(docCookie))
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
{
// We already added it, so we will keep it excluded from the misc files workspace
return;
}
}
var parseOptions = languageInformation.ParseOptions;
if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
{
parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
}
// First, create the project
var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);
// Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
var document = _documentProvider.TryGetDocumentForFile(hostProject, (uint)VSConstants.VSITEMID.Nil, moniker, parseOptions.Kind, t => true);
// If the buffer has not yet been initialized, we won't get a document.
if (document == null)
{
return;
}
// Since we have a document, we can do the rest of the project setup.
_hostProjects.Add(hostProject.Id, hostProject);
OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());
OnDocumentAdded(document.GetInitialState());
hostProject.Document = document;
// Notify the document provider, so it knows the document is now open and a part of
// the project
_documentProvider.NotifyDocumentRegisteredToProject(document);
Contract.ThrowIfFalse(document.IsOpen);
var buffer = document.GetOpenTextBuffer();
OnDocumentOpened(document.Id, document.GetOpenTextContainer());
_docCookiesToHostProject.Add(docCookie, hostProject);
}
}
private bool TryRemoveDocumentFromMiscellaneousWorkspace(uint docCookie, string moniker)
{
HostProject hostProject;
if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
{
return true;
}
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
var document = hostProject.Document;
OnDocumentClosed(document.Id, document.Loader);
OnDocumentRemoved(document.Id);
OnProjectRemoved(hostProject.Id);
_hostProjects.Remove(hostProject.Id);
_docCookiesToHostProject.Remove(docCookie);
return true;
}
return false;
}
protected override void Dispose(bool finalize)
{
StopSolutionCrawler();
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
_runningDocumentTableEventsCookie = 0;
base.Dispose(finalize);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
var hostDocument = this.GetDocument(documentId);
hostDocument.UpdateText(newText);
}
private HostProject GetHostProject(ProjectId id)
{
HostProject project;
_hostProjects.TryGetValue(id, out project);
return project;
}
internal IVisualStudioHostDocument GetDocument(DocumentId id)
{
var project = GetHostProject(id.ProjectId);
if (project != null && project.Document.Id == id)
{
return project.Document;
}
return null;
}
IEnumerable<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
{
return _hostProjects.Values;
}
private class LanguageInformation
{
public LanguageInformation(string languageName, string scriptExtension, ParseOptions parseOptions)
{
this.LanguageName = languageName;
this.ScriptExtension = scriptExtension;
this.ParseOptions = parseOptions;
}
public string LanguageName { get; private set; }
public string ScriptExtension { get; private set; }
public ParseOptions ParseOptions { get; private set; }
}
}
}
| |
using System;
using System.Web.Mvc;
using System.Diagnostics.Contracts;
using System.Web;
using HyperSlackers.Bootstrap.Core;
using System.Collections.Generic;
using HyperSlackers.Bootstrap.Extensions;
namespace HyperSlackers.Bootstrap.Controls
{
public class RadioButtonTrueFalseControl<TModel> : ControlListBase<RadioButtonTrueFalseControl<TModel>, TModel>
{
internal object inputTrueValue = true;
internal object inputFalseValue = false;
internal string labelTrueText = "Yes";
internal string labelFalseText = "No";
internal bool? selectedValue;
internal IDictionary<string, object> htmlAttributesInputTrue = new Dictionary<string, object>();
internal IDictionary<string, object> htmlAttributesInputFalse = new Dictionary<string, object>();
internal IDictionary<string, object> htmlAttributesLabelTrue = new Dictionary<string, object>();
internal IDictionary<string, object> htmlAttributesLabelFalse = new Dictionary<string, object>();
public RadioButtonTrueFalseControl(HtmlHelper<TModel> html, string htmlFieldName, ModelMetadata metadata)
: base(html, htmlFieldName, metadata)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace());
Contract.Requires<ArgumentNullException>(metadata != null, "metadata");
}
public RadioButtonTrueFalseControl<TModel> HelpText()
{
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
helpText = new HelpTextControl<TModel>(html, GetHelpTextText());
return this;
}
public RadioButtonTrueFalseControl<TModel> HelpText(string text)
{
Contract.Requires<ArgumentNullException>(text != null, "text");
Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
helpText = new HelpTextControl<TModel>(html, text);
return this;
}
public RadioButtonTrueFalseControl<TModel> HelpText(IHtmlString html)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
helpText = new HelpTextControl<TModel>(this.html, html.ToHtmlString());
return this;
}
public override RadioButtonTrueFalseControl<TModel> Disabled(bool isDisabled = true)
{
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
if (isDisabled)
{
htmlAttributesInputTrue.AddOrReplaceHtmlAttribute("disabled", "disabled");
htmlAttributesInputFalse.AddOrReplaceHtmlAttribute("disabled", "disabled");
}
else
{
htmlAttributesInputTrue.Remove("disabled");
htmlAttributesInputFalse.Remove("disabled");
}
return this;
}
public RadioButtonTrueFalseControl<TModel> HtmlAttributesInputFalse(object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
htmlAttributesInputFalse = htmlAttributes.ToDictionary();
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> HtmlAttributesInputTrue(object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
htmlAttributesInputTrue = htmlAttributes.ToDictionary();
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> HtmlAttributesLabelFalse(object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
htmlAttributesLabelFalse = htmlAttributes.ToDictionary();
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> HtmlAttributesLabelTrue(object htmlAttributes)
{
Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
htmlAttributesLabelTrue = htmlAttributes.ToDictionary();
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> ControlLabelText(string trueText, string falseText)
{
Contract.Requires<ArgumentException>(!trueText.IsNullOrWhiteSpace());
Contract.Requires<ArgumentException>(!falseText.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
labelTrueText = trueText;
labelFalseText = falseText;
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> ControlValues(object trueValue, object falseValue)
{
Contract.Requires<ArgumentNullException>(trueValue != null, "trueValue");
Contract.Requires<ArgumentNullException>(falseValue != null, "falseValue");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
inputTrueValue = trueValue;
inputFalseValue = falseValue;
return (RadioButtonTrueFalseControl<TModel>)this;
}
public override RadioButtonTrueFalseControl<TModel> Readonly(bool isReadonly = true)
{
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
if (isReadonly)
{
htmlAttributesInputTrue.AddOrReplaceHtmlAttribute("readonly", "readonly");
htmlAttributesInputFalse.AddOrReplaceHtmlAttribute("readonly", "readonly");
}
else
{
htmlAttributesInputTrue.Remove("readonly");
htmlAttributesInputFalse.Remove("readonly");
}
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> Tooltip()
{
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
SetDefaultTooltip();
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> Tooltip(Tooltip tooltip)
{
Contract.Requires<ArgumentNullException>(tooltip != null, "tooltip");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
this.tooltip = tooltip;
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> Tooltip(string text)
{
Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
tooltip = new Tooltip(text);
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> Tooltip(IHtmlString html)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
tooltip = new Tooltip(html);
return (RadioButtonTrueFalseControl<TModel>)this;
}
public RadioButtonTrueFalseControl<TModel> SelectedValue(bool? value)
{
Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null);
selectedValue = value;
return (RadioButtonTrueFalseControl<TModel>)this;
}
protected override string RenderControl()
{
Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace());
bool showValidationMessageInline = html.BootstrapDefaults().DefaultShowValidationMessageInline ?? false;
bool showValidationMessageBeforeInput = html.BootstrapDefaults().DefaultShowValidationMessageBeforeInput ?? false;
string formatString = showValidationMessageBeforeInput ? "{2}{0}{1}" : "{0}{1}{2}";
TagBuilder tagBuilder = new TagBuilder("div");
tagBuilder.AddCssClass("container-radio-true-false"); // TODO: is this a bootstrap thing?
tagBuilder.AddCssStyle("display", "inline-block");
SetDefaultTooltip();
if (tooltip != null)
{
tagBuilder.MergeHtmlAttributes(tooltip.ToDictionary());
}
string fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
bool isTrue = false;
bool isFalse = false;
if (metadata.Model != null)
{
isTrue = inputTrueValue.ToString() == metadata.Model.ToString();
isFalse = inputTrueValue.ToString() != metadata.Model.ToString();
}
RadioButtonControl<TModel> trueRadioButton = new RadioButtonControl<TModel>(html, htmlFieldName, inputTrueValue, metadata);
trueRadioButton.IsChecked(isTrue);
trueRadioButton.ControlHtmlAttributes(htmlAttributesInputTrue.AddOrReplaceHtmlAttribute("id", string.Concat(fullHtmlFieldName.FormatForMvcInputId(), "_t")));
trueRadioButton.Label(labelTrueText);
trueRadioButton.ShowRequiredStar(false);
trueRadioButton.LabelHtmlAttributes(htmlAttributesLabelTrue);
RadioButtonControl<TModel> falseRadioButton = new RadioButtonControl<TModel>(html, htmlFieldName, inputFalseValue, metadata);
falseRadioButton.IsChecked(isFalse);
falseRadioButton.ControlHtmlAttributes(htmlAttributesInputFalse.AddOrReplaceHtmlAttribute("id", string.Concat(fullHtmlFieldName.FormatForMvcInputId(), "_f")));
falseRadioButton.Label(labelFalseText);
falseRadioButton.ShowRequiredStar(false);
falseRadioButton.LabelHtmlAttributes(htmlAttributesLabelFalse);
string labelHtmlTrue = trueRadioButton.ToHtmlString();
string labelHtmlFalse = falseRadioButton.ToHtmlString();
string helpHtml = (helpText != null ? helpText.ToHtmlString() : string.Empty);
string validationHtml = (showValidationMessageInline ? string.Empty : RenderValidationMessage());
tagBuilder.InnerHtml = labelHtmlTrue + labelHtmlFalse;
return string.Format(formatString, tagBuilder, helpHtml, validationHtml);
}
}
}
| |
//
// DatabaseTrackInfo.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using Hyena;
using Hyena.Data;
using Hyena.Data.Sqlite;
using Hyena.Query;
using Banshee.Base;
using Banshee.Configuration.Schema;
using Banshee.Database;
using Banshee.Metadata;
using Banshee.Preferences;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Library;
using Banshee.ServiceStack;
using Banshee.Streaming;
// Disabling "is never used" warnings here because there are a lot
// of properties/fields that are set via reflection at the database
// layer - that is, they really are used, but the compiler doesn't
// think so.
#pragma warning disable 0169
namespace Banshee.Collection.Database
{
public class DatabaseTrackInfo : TrackInfo
{
private static DatabaseTrackModelProvider<DatabaseTrackInfo> provider;
public static DatabaseTrackModelProvider<DatabaseTrackInfo> Provider {
get { return provider ?? (provider = new DatabaseTrackModelProvider<DatabaseTrackInfo> (ServiceManager.DbConnection)); }
}
private bool artist_changed = false, album_changed = false;
public DatabaseTrackInfo () : base ()
{
}
public DatabaseTrackInfo (DatabaseTrackInfo original) : base ()
{
Provider.Copy (original, this);
}
// Changing these fields shouldn't change DateUpdated (which triggers file save)
private static readonly HashSet<QueryField> transient_fields;
static DatabaseTrackInfo ()
{
transient_fields = new HashSet<QueryField> () {
BansheeQuery.ScoreField,
BansheeQuery.SkipCountField,
BansheeQuery.LastSkippedField,
BansheeQuery.LastPlayedField,
BansheeQuery.PlaybackErrorField,
BansheeQuery.PlayCountField,
BansheeQuery.RatingField
};
Action<Root> handler = delegate {
if (SaveTrackMetadataService.WriteRatingsEnabled.Value) {
transient_fields.Remove (BansheeQuery.RatingField);
} else {
transient_fields.Add (BansheeQuery.RatingField);
}
if (SaveTrackMetadataService.WritePlayCountsEnabled.Value) {
transient_fields.Remove (BansheeQuery.PlayCountField);
} else {
transient_fields.Add (BansheeQuery.PlayCountField);
}
};
SaveTrackMetadataService.WritePlayCountsEnabled.ValueChanged += handler;
SaveTrackMetadataService.WriteRatingsEnabled.ValueChanged += handler;
handler (null);
}
public override void OnPlaybackFinished (double percentCompleted)
{
if (ProviderRefresh()) {
base.OnPlaybackFinished (percentCompleted);
Save (true, BansheeQuery.ScoreField, BansheeQuery.SkipCountField, BansheeQuery.LastSkippedField,
BansheeQuery.PlayCountField, BansheeQuery.LastPlayedField);
}
}
public override bool TrackEqual (TrackInfo track)
{
if (PrimarySource != null && PrimarySource.TrackEqualHandler != null) {
return PrimarySource.TrackEqualHandler (this, track);
}
DatabaseTrackInfo db_track = track as DatabaseTrackInfo;
if (db_track == null) {
return base.TrackEqual (track);
}
return TrackEqual (this, db_track);
}
public override string ArtworkId {
get {
if (PrimarySource != null && PrimarySource.TrackArtworkIdHandler != null) {
return PrimarySource.TrackArtworkIdHandler (this);
}
return base.ArtworkId;
}
}
public override bool IsPlaying {
get {
if (PrimarySource != null && PrimarySource.TrackIsPlayingHandler != null) {
return PrimarySource.TrackIsPlayingHandler (this);
}
return base.IsPlaying;
}
}
public static bool TrackEqual (DatabaseTrackInfo a, DatabaseTrackInfo b)
{
return a != null && b != null && a.TrackId == b.TrackId;
}
public DatabaseArtistInfo Artist {
get { return DatabaseArtistInfo.FindOrCreate (ArtistName, ArtistNameSort, ArtistMusicBrainzId); }
}
public DatabaseAlbumInfo Album {
get { return DatabaseAlbumInfo.FindOrCreate (
DatabaseArtistInfo.FindOrCreate (AlbumArtist, AlbumArtistSort, ArtistMusicBrainzId),
AlbumTitle, AlbumTitleSort, IsCompilation, AlbumMusicBrainzId); }
}
private static bool notify_saved = true;
public static bool NotifySaved {
get { return notify_saved; }
set { notify_saved = value; }
}
public override void Save ()
{
Save (NotifySaved);
}
public override void Update ()
{
if (PrimarySource != null) {
PrimarySource.UpdateMetadata (this);
}
base.Update ();
}
public override void UpdateLastPlayed ()
{
Refresh ();
base.UpdateLastPlayed ();
Save (NotifySaved, BansheeQuery.LastPlayedField);
}
public void Save (bool notify, params QueryField [] fields_changed)
{
// If either the artist or album changed,
if (ArtistId == 0 || AlbumId == 0 || artist_changed == true || album_changed == true) {
DatabaseArtistInfo artist = Artist;
ArtistId = artist.DbId;
DatabaseAlbumInfo album = Album;
AlbumId = album.DbId;
// TODO get rid of unused artists/albums
}
// If PlayCountField is not transient we still want to update the file only if it's from the music library
var transient = transient_fields;
if (!transient.Contains (BansheeQuery.PlayCountField) &&
!ServiceManager.SourceManager.MusicLibrary.Equals (PrimarySource)) {
transient = new HashSet<QueryField> (transient_fields);
transient.Add (BansheeQuery.PlayCountField);
}
if (fields_changed.Length == 0 || !transient.IsSupersetOf (fields_changed)) {
DateUpdated = DateTime.Now;
}
bool is_new = (TrackId == 0);
if (is_new) {
LastSyncedStamp = DateAdded = DateUpdated = DateTime.Now;
}
ProviderSave ();
if (notify && PrimarySource != null) {
if (is_new) {
PrimarySource.NotifyTracksAdded ();
} else {
PrimarySource.NotifyTracksChanged (fields_changed);
}
}
}
protected virtual void ProviderSave ()
{
Provider.Save (this);
}
public void Refresh ()
{
ProviderRefresh ();
}
protected virtual bool ProviderRefresh ()
{
return Provider.Refresh (this);
}
private int track_id;
[DatabaseColumn ("TrackID", Constraints = DatabaseColumnConstraints.PrimaryKey)]
public int TrackId {
get { return track_id; }
protected set { track_id = value; }
}
private int primary_source_id;
[DatabaseColumn ("PrimarySourceID")]
public int PrimarySourceId {
get { return primary_source_id; }
set { primary_source_id = value; }
}
public PrimarySource PrimarySource {
get { return PrimarySource.GetById (primary_source_id); }
set { PrimarySourceId = value.DbId; }
}
private int artist_id;
[DatabaseColumn ("ArtistID")]
public int ArtistId {
get { return artist_id; }
set { artist_id = value; }
}
private int album_id;
[DatabaseColumn ("AlbumID")]
public int AlbumId {
get { return album_id; }
set { album_id = value; }
}
[VirtualDatabaseColumn ("Name", "CoreArtists", "ArtistID", "ArtistID")]
protected string ArtistNameField {
get { return ArtistName; }
set { base.ArtistName = value; }
}
public override string ArtistName {
get { return base.ArtistName; }
set {
value = CleanseString (value, ArtistName);
if (value == null)
return;
base.ArtistName = value;
artist_changed = true;
}
}
[VirtualDatabaseColumn ("NameSort", "CoreArtists", "ArtistID", "ArtistID")]
protected string ArtistNameSortField {
get { return ArtistNameSort; }
set { base.ArtistNameSort = value; }
}
public override string ArtistNameSort {
get { return base.ArtistNameSort; }
set {
value = CleanseString (value, ArtistNameSort);
if (value == null)
return;
base.ArtistNameSort = value;
artist_changed = true;
}
}
[VirtualDatabaseColumn ("Title", "CoreAlbums", "AlbumID", "AlbumID")]
protected string AlbumTitleField {
get { return AlbumTitle; }
set { base.AlbumTitle = value; }
}
public override string AlbumTitle {
get { return base.AlbumTitle; }
set {
value = CleanseString (value, AlbumTitle);
if (value == null)
return;
base.AlbumTitle = value;
album_changed = true;
}
}
[VirtualDatabaseColumn ("TitleSort", "CoreAlbums", "AlbumID", "AlbumID")]
protected string AlbumTitleSortField {
get { return AlbumTitleSort; }
set { base.AlbumTitleSort = value; }
}
public override string AlbumTitleSort {
get { return base.AlbumTitleSort; }
set {
value = CleanseString (value, AlbumTitleSort);
if (value == null)
return;
base.AlbumTitleSort = value;
album_changed = true;
}
}
[VirtualDatabaseColumn ("ArtistName", "CoreAlbums", "AlbumID", "AlbumID")]
protected string AlbumArtistField {
get { return AlbumArtist; }
set { base.AlbumArtist = value; }
}
public override string AlbumArtist {
get { return base.AlbumArtist; }
set {
value = CleanseString (value, AlbumArtist);
if (value == null)
return;
base.AlbumArtist = value;
album_changed = true;
}
}
[VirtualDatabaseColumn ("ArtistNameSort", "CoreAlbums", "AlbumID", "AlbumID")]
protected string AlbumArtistSortField {
get { return AlbumArtistSort; }
set { base.AlbumArtistSort = value; }
}
public override string AlbumArtistSort {
get { return base.AlbumArtistSort; }
set {
value = CleanseString (value, AlbumArtistSort);
if (value == null)
return;
base.AlbumArtistSort = value;
album_changed = true;
}
}
[VirtualDatabaseColumn ("IsCompilation", "CoreAlbums", "AlbumID", "AlbumID")]
protected bool IsCompilationField {
get { return IsCompilation; }
set { base.IsCompilation = value; }
}
public override bool IsCompilation {
get { return base.IsCompilation; }
set {
base.IsCompilation = value;
album_changed = true;
}
}
private static string CleanseString (string input, string old_val)
{
if (input == old_val)
return null;
if (input != null)
input = input.Trim ();
if (input == old_val)
return null;
return input;
}
private int tag_set_id;
[DatabaseColumn]
public int TagSetID {
get { return tag_set_id; }
set { tag_set_id = value; }
}
[DatabaseColumn ("MusicBrainzID")]
public override string MusicBrainzId {
get { return base.MusicBrainzId; }
set { base.MusicBrainzId = value; }
}
[VirtualDatabaseColumn ("MusicBrainzID", "CoreAlbums", "AlbumID", "AlbumID")]
protected string AlbumMusicBrainzIdField {
get { return base.AlbumMusicBrainzId; }
set { base.AlbumMusicBrainzId = value; }
}
public override string AlbumMusicBrainzId {
get { return base.AlbumMusicBrainzId; }
set {
value = CleanseString (value, AlbumMusicBrainzId);
if (value == null)
return;
base.AlbumMusicBrainzId = value;
album_changed = true;
}
}
[VirtualDatabaseColumn ("MusicBrainzID", "CoreArtists", "ArtistID", "ArtistID")]
protected string ArtistMusicBrainzIdField {
get { return base.ArtistMusicBrainzId; }
set { base.ArtistMusicBrainzId = value; }
}
public override string ArtistMusicBrainzId {
get { return base.ArtistMusicBrainzId; }
set {
value = CleanseString (value, ArtistMusicBrainzId);
if (value == null)
return;
base.ArtistMusicBrainzId = value;
artist_changed = true;
}
}
[DatabaseColumn ("Uri")]
protected string UriField {
get { return Uri == null ? null : Uri.AbsoluteUri; }
set { Uri = value == null ? null : new SafeUri (value); }
}
[DatabaseColumn]
public override string MimeType {
get { return base.MimeType; }
set { base.MimeType = value; }
}
[DatabaseColumn]
public override long FileSize {
get { return base.FileSize; }
set { base.FileSize = value; }
}
[DatabaseColumn]
public override long FileModifiedStamp {
get { return base.FileModifiedStamp; }
set { base.FileModifiedStamp = value; }
}
[DatabaseColumn]
public override DateTime LastSyncedStamp {
get { return base.LastSyncedStamp; }
set { base.LastSyncedStamp = value; }
}
[DatabaseColumn ("Attributes")]
public override TrackMediaAttributes MediaAttributes {
get { return base.MediaAttributes; }
set { base.MediaAttributes = value; }
}
[DatabaseColumn ("Title")]
public override string TrackTitle {
get { return base.TrackTitle; }
set { base.TrackTitle = value; }
}
[DatabaseColumn ("TitleSort")]
public override string TrackTitleSort {
get { return base.TrackTitleSort; }
set { base.TrackTitleSort = value; }
}
[DatabaseColumn("TitleSortKey", Select = false)]
internal byte[] TrackTitleSortKey {
get { return Hyena.StringUtil.SortKey (TrackTitleSort ?? DisplayTrackTitle); }
}
[DatabaseColumn(Select = false)]
internal string TitleLowered {
get { return Hyena.StringUtil.SearchKey (DisplayTrackTitle); }
}
[DatabaseColumn(Select = false)]
public override string MetadataHash {
get { return base.MetadataHash; }
}
[DatabaseColumn]
public override int TrackNumber {
get { return base.TrackNumber; }
set { base.TrackNumber = value; }
}
[DatabaseColumn]
public override int TrackCount {
get { return base.TrackCount; }
set { base.TrackCount = value; }
}
[DatabaseColumn ("Disc")]
public override int DiscNumber {
get { return base.DiscNumber; }
set { base.DiscNumber = value; }
}
[DatabaseColumn]
public override int DiscCount {
get { return base.DiscCount; }
set { base.DiscCount = value; }
}
[DatabaseColumn]
public override TimeSpan Duration {
get { return base.Duration; }
set { base.Duration = value; }
}
[DatabaseColumn]
public override int Year {
get { return base.Year; }
set { base.Year = value; }
}
[DatabaseColumn]
public override string Genre {
get { return base.Genre; }
set { base.Genre = value; }
}
[DatabaseColumn]
public override string Composer {
get { return base.Composer; }
set { base.Composer = value; }
}
[DatabaseColumn]
public override string Conductor {
get { return base.Conductor; }
set { base.Conductor = value; }
}
[DatabaseColumn]
public override string Grouping {
get { return base.Grouping; }
set { base.Grouping = value; }
}
[DatabaseColumn]
public override string Copyright {
get { return base.Copyright; }
set { base.Copyright = value; }
}
[DatabaseColumn]
public override string LicenseUri {
get { return base.LicenseUri; }
set { base.LicenseUri = value; }
}
[DatabaseColumn]
public override string Comment {
get { return base.Comment; }
set { base.Comment = value; }
}
[DatabaseColumn("BPM")]
public override int Bpm {
get { return base.Bpm; }
set { base.Bpm = value; }
}
[DatabaseColumn]
public override int BitRate {
get { return base.BitRate; }
set { base.BitRate = value; }
}
[DatabaseColumn]
public override int SampleRate {
get { return base.SampleRate; }
set { base.SampleRate = value; }
}
[DatabaseColumn]
public override int BitsPerSample {
get { return base.BitsPerSample; }
set { base.BitsPerSample = value; }
}
[DatabaseColumn("Rating")]
protected int rating;
public override int Rating {
get { return rating; }
set { rating = value; }
}
[DatabaseColumn]
public override int Score {
get { return base.Score; }
set { base.Score = value; }
}
public int SavedRating {
get { return rating; }
set {
if (rating != value) {
rating = value;
Save (true, BansheeQuery.RatingField);
if (TrackEqual (ServiceManager.PlayerEngine.CurrentTrack)) {
ServiceManager.PlayerEngine.CurrentTrack.Rating = value;
ServiceManager.PlayerEngine.TrackInfoUpdated ();
}
}
}
}
[DatabaseColumn]
public override int PlayCount {
get { return base.PlayCount; }
set { base.PlayCount = value; }
}
[DatabaseColumn]
public override int SkipCount {
get { return base.SkipCount; }
set { base.SkipCount = value; }
}
private long external_id;
[DatabaseColumn ("ExternalID")]
public long ExternalId {
get { return external_id; }
set { external_id = value; }
}
private object external_object;
public override object ExternalObject {
get {
if (external_id > 0 && external_object == null && PrimarySource != null && PrimarySource.TrackExternalObjectHandler != null) {
external_object = PrimarySource.TrackExternalObjectHandler (this);
}
return external_object;
}
}
[DatabaseColumn ("LastPlayedStamp")]
public override DateTime LastPlayed {
get { return base.LastPlayed; }
set { base.LastPlayed = value; }
}
[DatabaseColumn ("LastSkippedStamp")]
public override DateTime LastSkipped {
get { return base.LastSkipped; }
set { base.LastSkipped = value; }
}
[DatabaseColumn ("DateAddedStamp")]
public override DateTime DateAdded {
get { return base.DateAdded; }
set { base.DateAdded = value; }
}
private DateTime date_updated;
[DatabaseColumn ("DateUpdatedStamp")]
public DateTime DateUpdated {
get { return date_updated; }
set { date_updated = value; }
}
[DatabaseColumn ("LastStreamError")]
protected StreamPlaybackError playback_error;
public override StreamPlaybackError PlaybackError {
get { return playback_error; }
set {
if (playback_error == value) {
return;
}
playback_error = value;
}
}
public PathPattern PathPattern {
get {
var src = PrimarySource;
var pattern = src == null ? null : src.PathPattern;
return pattern ?? MusicLibrarySource.MusicFileNamePattern;
}
}
public bool CopyToLibraryIfAppropriate (bool force_copy)
{
bool copy_success = true;
LibrarySource library_source = PrimarySource as LibrarySource;
if (library_source == null) {
// Get out, not a local Library
return false;
}
SafeUri old_uri = this.Uri;
if (old_uri == null) {
// Get out quick, no URI set yet.
return copy_success;
}
bool in_library = old_uri.IsLocalPath ? old_uri.AbsolutePath.StartsWith (PrimarySource.BaseDirectoryWithSeparator) : false;
if (!in_library && ((library_source.HasCopyOnImport && library_source.CopyOnImport) || force_copy)) {
string new_filename = PathPattern.BuildFull (PrimarySource.BaseDirectory, this, Path.GetExtension (old_uri.ToString ()));
SafeUri new_uri = new SafeUri (new_filename);
try {
if (Banshee.IO.File.Exists (new_uri)) {
if (Banshee.IO.File.GetSize (old_uri) == Banshee.IO.File.GetSize (new_uri)) {
Hyena.Log.DebugFormat ("Not copying {0} to library because there is already a file of same size at {1}", old_uri, new_uri);
copy_success = false;
return copy_success;
} else {
string extension = Path.GetExtension (new_filename);
string filename_no_ext = new_filename.Remove (new_filename.Length - extension.Length);
int duplicate_index = 1;
while (Banshee.IO.File.Exists (new_uri)) {
new_filename = String.Format ("{0} ({1}){2}", filename_no_ext, duplicate_index, extension);
new_uri = new SafeUri (new_filename);
duplicate_index++;
}
}
}
Banshee.IO.File.Copy (old_uri, new_uri, false);
Uri = new_uri;
} catch (Exception e) {
Log.ErrorFormat ("Exception copying into library: {0}", e);
}
}
return copy_success;
}
private static string get_track_id_by_uri =
"SELECT TrackID FROM CoreTracks WHERE {0} {1} = ? LIMIT 1";
private static HyenaSqliteCommand get_track_id_by_uri_primarysources = new HyenaSqliteCommand (String.Format (
get_track_id_by_uri, "PrimarySourceId IN (?) AND", BansheeQuery.UriField.Column
));
private static HyenaSqliteCommand get_track_id_by_uri_plain = new HyenaSqliteCommand (String.Format (
get_track_id_by_uri, string.Empty, BansheeQuery.UriField.Column
));
private static string get_track_by_metadata_hash =
"SELECT {0} FROM {1} WHERE {2} AND PrimarySourceId IN (?) AND MetadataHash = ? LIMIT 1";
private static HyenaSqliteCommand get_track_count_by_metadata_hash = new HyenaSqliteCommand (
"SELECT COUNT('x') FROM CoreTracks WHERE PrimarySourceId IN (?) AND MetadataHash = ?"
);
public static int GetTrackIdForUri (string uri)
{
return GetTrackIdForUri (new SafeUri (uri));
}
public static int GetTrackIdForUri (SafeUri uri, params int [] primary_sources)
{
return GetTrackIdForUri (uri.AbsoluteUri, primary_sources);
}
public static int GetTrackIdForUri (string absoluteUri, params int [] primary_sources)
{
if (primary_sources == null || primary_sources.Length == 0) {
return ServiceManager.DbConnection.Query<int> (get_track_id_by_uri_plain, absoluteUri);
}
return ServiceManager.DbConnection.Query<int> (
get_track_id_by_uri_primarysources, primary_sources, absoluteUri
);
}
private static IDataReader FindTrackByMetadataHash (string metadata_hash, int [] primary_sources)
{
var command = new HyenaSqliteCommand (String.Format (
get_track_by_metadata_hash,
provider.Select, provider.From, provider.Where));
return ServiceManager.DbConnection.Query (command,
primary_sources, metadata_hash);
}
public static bool ContainsUri (SafeUri uri, int [] primary_sources)
{
return GetTrackIdForUri (uri, primary_sources) > 0;
}
internal static DatabaseTrackInfo GetTrackForMetadataHash (string metadata_hash, int [] primary_sources)
{
using (IDataReader reader = FindTrackByMetadataHash (metadata_hash, primary_sources)) {
if (reader.Read ()) {
return provider.Load (reader);
}
return null;
}
}
internal static int MetadataHashCount (string metadata_hash, int [] primary_sources)
{
return ServiceManager.DbConnection.Query<int> (get_track_count_by_metadata_hash,
primary_sources, metadata_hash);
}
public static void UpdateMetadataHash (string albumTitle, string artistName, string condition)
{
// Keep this field set/order in sync with MetadataHash in TrackInfo.cs
ServiceManager.DbConnection.Execute (String.Format (
@"UPDATE CoreTracks SET MetadataHash = HYENA_MD5 (6, ?, ?, Genre, Title, TrackNumber, Year)
WHERE {0}",
condition), albumTitle, artistName
);
}
}
}
#pragma warning restore 0169
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Audio.Track;
using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics.Textures;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.Database;
using osu.Game.Extensions;
using osu.Game.IO;
using osu.Game.IO.Archives;
using osu.Game.Models;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Skinning;
using Realms;
#nullable enable
namespace osu.Game.Stores
{
/// <summary>
/// Handles the storage and retrieval of Beatmaps/WorkingBeatmaps.
/// </summary>
[ExcludeFromDynamicCompile]
public class BeatmapImporter : RealmArchiveModelImporter<RealmBeatmapSet>, IDisposable
{
public override IEnumerable<string> HandledExtensions => new[] { ".osz" };
protected override string[] HashableFileTypes => new[] { ".osu" };
// protected override bool CheckLocalAvailability(RealmBeatmapSet model, System.Linq.IQueryable<RealmBeatmapSet> items)
// => base.CheckLocalAvailability(model, items) || (model.OnlineID > -1));
private readonly BeatmapOnlineLookupQueue? onlineLookupQueue;
public BeatmapImporter(RealmContextFactory contextFactory, Storage storage, BeatmapOnlineLookupQueue? onlineLookupQueue = null)
: base(storage, contextFactory)
{
this.onlineLookupQueue = onlineLookupQueue;
}
protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path).ToLowerInvariant() == ".osz";
protected override Task Populate(RealmBeatmapSet beatmapSet, ArchiveReader? archive, Realm realm, CancellationToken cancellationToken = default)
{
if (archive != null)
beatmapSet.Beatmaps.AddRange(createBeatmapDifficulties(beatmapSet.Files, realm));
foreach (RealmBeatmap b in beatmapSet.Beatmaps)
b.BeatmapSet = beatmapSet;
validateOnlineIds(beatmapSet, realm);
bool hadOnlineIDs = beatmapSet.Beatmaps.Any(b => b.OnlineID > 0);
if (onlineLookupQueue != null)
{
// TODO: this required `BeatmapOnlineLookupQueue` to somehow support new types.
// await onlineLookupQueue.UpdateAsync(beatmapSet, cancellationToken).ConfigureAwait(false);
}
// ensure at least one beatmap was able to retrieve or keep an online ID, else drop the set ID.
if (hadOnlineIDs && !beatmapSet.Beatmaps.Any(b => b.OnlineID > 0))
{
if (beatmapSet.OnlineID > 0)
{
beatmapSet.OnlineID = -1;
LogForModel(beatmapSet, "Disassociating beatmap set ID due to loss of all beatmap IDs");
}
}
return Task.CompletedTask;
}
protected override void PreImport(RealmBeatmapSet beatmapSet, Realm realm)
{
// We are about to import a new beatmap. Before doing so, ensure that no other set shares the online IDs used by the new one.
// Note that this means if the previous beatmap is restored by the user, it will no longer be linked to its online IDs.
// If this is ever an issue, we can consider marking as pending delete but not resetting the IDs (but care will be required for
// beatmaps, which don't have their own `DeletePending` state).
if (beatmapSet.OnlineID > 0)
{
var existingSetWithSameOnlineID = realm.All<RealmBeatmapSet>().SingleOrDefault(b => b.OnlineID == beatmapSet.OnlineID);
if (existingSetWithSameOnlineID != null)
{
existingSetWithSameOnlineID.DeletePending = true;
existingSetWithSameOnlineID.OnlineID = -1;
foreach (var b in existingSetWithSameOnlineID.Beatmaps)
b.OnlineID = -1;
LogForModel(beatmapSet, $"Found existing beatmap set with same OnlineID ({beatmapSet.OnlineID}). It will be deleted.");
}
}
}
private void validateOnlineIds(RealmBeatmapSet beatmapSet, Realm realm)
{
var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineID > 0).Select(b => b.OnlineID).ToList();
// ensure all IDs are unique
if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1))
{
LogForModel(beatmapSet, "Found non-unique IDs, resetting...");
resetIds();
return;
}
// find any existing beatmaps in the database that have matching online ids
List<RealmBeatmap> existingBeatmaps = new List<RealmBeatmap>();
foreach (int id in beatmapIds)
existingBeatmaps.AddRange(realm.All<RealmBeatmap>().Where(b => b.OnlineID == id));
if (existingBeatmaps.Any())
{
// reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set.
// we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted.
var existing = CheckForExisting(beatmapSet, realm);
if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b)))
{
LogForModel(beatmapSet, "Found existing import with online IDs already, resetting...");
resetIds();
}
}
void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineID = -1);
}
protected override bool CanSkipImport(RealmBeatmapSet existing, RealmBeatmapSet import)
{
if (!base.CanSkipImport(existing, import))
return false;
return existing.Beatmaps.Any(b => b.OnlineID > 0);
}
protected override bool CanReuseExisting(RealmBeatmapSet existing, RealmBeatmapSet import)
{
if (!base.CanReuseExisting(existing, import))
return false;
var existingIds = existing.Beatmaps.Select(b => b.OnlineID).OrderBy(i => i);
var importIds = import.Beatmaps.Select(b => b.OnlineID).OrderBy(i => i);
// force re-import if we are not in a sane state.
return existing.OnlineID == import.OnlineID && existingIds.SequenceEqual(importIds);
}
public override string HumanisedModelName => "beatmap";
protected override RealmBeatmapSet? CreateModel(ArchiveReader reader)
{
// let's make sure there are actually .osu files to import.
string? mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu", StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrEmpty(mapName))
{
Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database);
return null;
}
Beatmap beatmap;
using (var stream = new LineBufferedReader(reader.GetStream(mapName)))
beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream);
return new RealmBeatmapSet
{
OnlineID = beatmap.BeatmapInfo.BeatmapSet?.OnlineID ?? -1,
// Metadata = beatmap.Metadata,
DateAdded = DateTimeOffset.UtcNow
};
}
/// <summary>
/// Create all required <see cref="RealmBeatmap"/>s for the provided archive.
/// </summary>
private List<RealmBeatmap> createBeatmapDifficulties(IList<RealmNamedFileUsage> files, Realm realm)
{
var beatmaps = new List<RealmBeatmap>();
foreach (var file in files.Where(f => f.Filename.EndsWith(".osu", StringComparison.OrdinalIgnoreCase)))
{
using (var memoryStream = new MemoryStream(Files.Store.Get(file.File.GetStoragePath()))) // we need a memory stream so we can seek
{
IBeatmap decoded;
using (var lineReader = new LineBufferedReader(memoryStream, true))
decoded = Decoder.GetDecoder<Beatmap>(lineReader).Decode(lineReader);
string hash = memoryStream.ComputeSHA2Hash();
if (beatmaps.Any(b => b.Hash == hash))
{
Logger.Log($"Skipping import of {file.Filename} due to duplicate file content.", LoggingTarget.Database);
continue;
}
var decodedInfo = decoded.BeatmapInfo;
var decodedDifficulty = decodedInfo.BaseDifficulty;
var ruleset = realm.All<RealmRuleset>().FirstOrDefault(r => r.OnlineID == decodedInfo.RulesetID);
if (ruleset?.Available != true)
{
Logger.Log($"Skipping import of {file.Filename} due to missing local ruleset {decodedInfo.RulesetID}.", LoggingTarget.Database);
continue;
}
var difficulty = new RealmBeatmapDifficulty
{
DrainRate = decodedDifficulty.DrainRate,
CircleSize = decodedDifficulty.CircleSize,
OverallDifficulty = decodedDifficulty.OverallDifficulty,
ApproachRate = decodedDifficulty.ApproachRate,
SliderMultiplier = decodedDifficulty.SliderMultiplier,
SliderTickRate = decodedDifficulty.SliderTickRate,
};
var metadata = new RealmBeatmapMetadata
{
Title = decoded.Metadata.Title,
TitleUnicode = decoded.Metadata.TitleUnicode,
Artist = decoded.Metadata.Artist,
ArtistUnicode = decoded.Metadata.ArtistUnicode,
Author =
{
OnlineID = decoded.Metadata.Author.Id,
Username = decoded.Metadata.Author.Username
},
Source = decoded.Metadata.Source,
Tags = decoded.Metadata.Tags,
PreviewTime = decoded.Metadata.PreviewTime,
AudioFile = decoded.Metadata.AudioFile,
BackgroundFile = decoded.Metadata.BackgroundFile,
};
var beatmap = new RealmBeatmap(ruleset, difficulty, metadata)
{
Hash = hash,
DifficultyName = decodedInfo.DifficultyName,
OnlineID = decodedInfo.OnlineID ?? -1,
AudioLeadIn = decodedInfo.AudioLeadIn,
StackLeniency = decodedInfo.StackLeniency,
SpecialStyle = decodedInfo.SpecialStyle,
LetterboxInBreaks = decodedInfo.LetterboxInBreaks,
WidescreenStoryboard = decodedInfo.WidescreenStoryboard,
EpilepsyWarning = decodedInfo.EpilepsyWarning,
SamplesMatchPlaybackRate = decodedInfo.SamplesMatchPlaybackRate,
DistanceSpacing = decodedInfo.DistanceSpacing,
BeatDivisor = decodedInfo.BeatDivisor,
GridSize = decodedInfo.GridSize,
TimelineZoom = decodedInfo.TimelineZoom,
MD5Hash = memoryStream.ComputeMD5Hash(),
};
updateBeatmapStatistics(beatmap, decoded);
beatmaps.Add(beatmap);
}
}
return beatmaps;
}
private void updateBeatmapStatistics(RealmBeatmap beatmap, IBeatmap decoded)
{
var rulesetInstance = ((IRulesetInfo)beatmap.Ruleset).CreateInstance();
decoded.BeatmapInfo.Ruleset = rulesetInstance.RulesetInfo;
// TODO: this should be done in a better place once we actually need to dynamically update it.
beatmap.StarRating = rulesetInstance.CreateDifficultyCalculator(new DummyConversionBeatmap(decoded)).Calculate().StarRating;
beatmap.Length = calculateLength(decoded);
beatmap.BPM = 60000 / decoded.GetMostCommonBeatLength();
}
private double calculateLength(IBeatmap b)
{
if (!b.HitObjects.Any())
return 0;
var lastObject = b.HitObjects.Last();
//TODO: this isn't always correct (consider mania where a non-last object may last for longer than the last in the list).
double endTime = lastObject.GetEndTime();
double startTime = b.HitObjects.First().StartTime;
return endTime - startTime;
}
public void Dispose()
{
onlineLookupQueue?.Dispose();
}
/// <summary>
/// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation.
/// </summary>
private class DummyConversionBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
public DummyConversionBeatmap(IBeatmap beatmap)
: base(beatmap.BeatmapInfo, null)
{
this.beatmap = beatmap;
}
protected override IBeatmap GetBeatmap() => beatmap;
protected override Texture? GetBackground() => null;
protected override Track? GetBeatmapTrack() => null;
protected internal override ISkin? GetSkin() => null;
public override Stream? GetStream(string storagePath) => null;
}
}
}
| |
// 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>CustomerCustomizer</c> resource.</summary>
public sealed partial class CustomerCustomizerName : gax::IResourceName, sys::IEquatable<CustomerCustomizerName>
{
/// <summary>The possible contents of <see cref="CustomerCustomizerName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>
/// .
/// </summary>
CustomerCustomizerAttribute = 1,
}
private static gax::PathTemplate s_customerCustomizerAttribute = new gax::PathTemplate("customers/{customer_id}/customerCustomizers/{customizer_attribute_id}");
/// <summary>Creates a <see cref="CustomerCustomizerName"/> 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="CustomerCustomizerName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerCustomizerName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerCustomizerName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerCustomizerName"/> with the pattern
/// <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</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="CustomerCustomizerName"/> constructed from the provided ids.</returns>
public static CustomerCustomizerName FromCustomerCustomizerAttribute(string customerId, string customizerAttributeId) =>
new CustomerCustomizerName(ResourceNameType.CustomerCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerCustomizerName"/> with pattern
/// <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</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="CustomerCustomizerName"/> with pattern
/// <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>.
/// </returns>
public static string Format(string customerId, string customizerAttributeId) =>
FormatCustomerCustomizerAttribute(customerId, customizerAttributeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerCustomizerName"/> with pattern
/// <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</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="CustomerCustomizerName"/> with pattern
/// <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>.
/// </returns>
public static string FormatCustomerCustomizerAttribute(string customerId, string customizerAttributeId) =>
s_customerCustomizerAttribute.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerCustomizerName"/> 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}/customerCustomizers/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerCustomizerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomerCustomizerName"/> if successful.</returns>
public static CustomerCustomizerName Parse(string customerCustomizerName) => Parse(customerCustomizerName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerCustomizerName"/> 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}/customerCustomizers/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerCustomizerName">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="CustomerCustomizerName"/> if successful.</returns>
public static CustomerCustomizerName Parse(string customerCustomizerName, bool allowUnparsed) =>
TryParse(customerCustomizerName, allowUnparsed, out CustomerCustomizerName 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="CustomerCustomizerName"/> 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}/customerCustomizers/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerCustomizerName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerCustomizerName"/>, 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 customerCustomizerName, out CustomerCustomizerName result) =>
TryParse(customerCustomizerName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerCustomizerName"/> 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}/customerCustomizers/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerCustomizerName">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="CustomerCustomizerName"/>, 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 customerCustomizerName, bool allowUnparsed, out CustomerCustomizerName result)
{
gax::GaxPreconditions.CheckNotNull(customerCustomizerName, nameof(customerCustomizerName));
gax::TemplatedResourceName resourceName;
if (s_customerCustomizerAttribute.TryParseName(customerCustomizerName, out resourceName))
{
result = FromCustomerCustomizerAttribute(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerCustomizerName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomerCustomizerName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string customizerAttributeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
CustomizerAttributeId = customizerAttributeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerCustomizerName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/customerCustomizers/{customizer_attribute_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</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 CustomerCustomizerName(string customerId, string customizerAttributeId) : this(ResourceNameType.CustomerCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), 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>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.CustomerCustomizerAttribute: return s_customerCustomizerAttribute.Expand(CustomerId, 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 CustomerCustomizerName);
/// <inheritdoc/>
public bool Equals(CustomerCustomizerName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerCustomizerName a, CustomerCustomizerName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerCustomizerName a, CustomerCustomizerName b) => !(a == b);
}
public partial class CustomerCustomizer
{
/// <summary>
/// <see cref="CustomerCustomizerName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CustomerCustomizerName ResourceNameAsCustomerCustomizerName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerCustomizerName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = 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() ?? "";
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using i16 = System.Int16;
using u8 = System.Byte;
using u16 = System.UInt16;
namespace System.Data.SQLite
{
using sqlite3_value = Sqlite3.Mem;
internal partial class Sqlite3
{
/*
** 2005 May 23
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the encoding enc of name zName, length nName.
*/
static void callCollNeeded(sqlite3 db, int enc, string zName)
{
Debug.Assert(db.xCollNeeded == null || db.xCollNeeded16 == null);
if (db.xCollNeeded != null)
{
string zExternal = zName;// sqlite3DbStrDup(db, zName);
if (zExternal == null)
return;
db.xCollNeeded(db.pCollNeededArg, db, enc, zExternal);
sqlite3DbFree(db, ref zExternal);
}
#if !SQLITE_OMIT_UTF16
if( db.xCollNeeded16!=null ){
string zExternal;
sqlite3_value pTmp = sqlite3ValueNew(db);
sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
if( zExternal!="" ){
db.xCollNeeded16( db.pCollNeededArg, db, db.aDbStatic[0].pSchema.enc, zExternal );//(int)ENC(db), zExternal);
}
sqlite3ValueFree(ref pTmp);
}
#endif
}
/*
** This routine is called if the collation factory fails to deliver a
** collation function in the best encoding but there may be other versions
** of this collation function (for other text encodings) available. Use one
** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if
** possible.
*/
static int synthCollSeq(sqlite3 db, CollSeq pColl)
{
CollSeq pColl2;
string z = pColl.zName;
int i;
byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
for (i = 0; i < 3; i++)
{
pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
if (pColl2.xCmp != null)
{
pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq));
pColl.xDel = null; /* Do not copy the destructor */
return SQLITE_OK;
}
}
return SQLITE_ERROR;
}
/*
** This function is responsible for invoking the collation factory callback
** or substituting a collation sequence of a different encoding when the
** requested collation sequence is not available in the desired encoding.
**
** If it is not NULL, then pColl must point to the database native encoding
** collation sequence with name zName, length nName.
**
** The return value is either the collation sequence to be used in database
** db for collation type name zName, length nName, or NULL, if no collation
** sequence can be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
*/
static CollSeq sqlite3GetCollSeq(
sqlite3 db, /* The database connection */
u8 enc, /* The desired encoding for the collating sequence */
CollSeq pColl, /* Collating sequence with native encoding, or NULL */
string zName /* Collating sequence name */
)
{
CollSeq p;
p = pColl;
if (p == null)
{
p = sqlite3FindCollSeq(db, enc, zName, 0);
}
if (p == null || p.xCmp == null)
{
/* No collation sequence of this type for this encoding is registered.
** Call the collation factory to see if it can supply us with one.
*/
callCollNeeded(db, enc, zName);
p = sqlite3FindCollSeq(db, enc, zName, 0);
}
if (p != null && p.xCmp == null && synthCollSeq(db, p) != 0)
{
p = null;
}
Debug.Assert(p == null || p.xCmp != null);
return p;
}
/*
** This routine is called on a collation sequence before it is used to
** check that it is defined. An undefined collation sequence exists when
** a database is loaded that contains references to collation sequences
** that have not been defined by sqlite3_create_collation() etc.
**
** If required, this routine calls the 'collation needed' callback to
** request a definition of the collating sequence. If this doesn't work,
** an equivalent collating sequence that uses a text encoding different
** from the main database is substituted, if one is available.
*/
static int sqlite3CheckCollSeq(Parse pParse, CollSeq pColl)
{
if (pColl != null)
{
string zName = pColl.zName;
sqlite3 db = pParse.db;
CollSeq p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
if (null == p)
{
sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
pParse.nErr++;
return SQLITE_ERROR;
}
//
//Debug.Assert(p == pColl);
if (p != pColl) // Had to lookup appropriate sequence
{
pColl.enc = p.enc;
pColl.pUser = p.pUser;
pColl.type = p.type;
pColl.xCmp = p.xCmp;
pColl.xDel = p.xDel;
}
}
return SQLITE_OK;
}
/*
** Locate and return an entry from the db.aCollSeq hash table. If the entry
** specified by zName and nName is not found and parameter 'create' is
** true, then create a new entry. Otherwise return NULL.
**
** Each pointer stored in the sqlite3.aCollSeq hash table contains an
** array of three CollSeq structures. The first is the collation sequence
** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
**
** Stored immediately after the three collation sequences is a copy of
** the collation sequence name. A pointer to this string is stored in
** each collation sequence structure.
*/
static CollSeq[] findCollSeqEntry(
sqlite3 db, /* Database connection */
string zName, /* Name of the collating sequence */
int create /* Create a new entry if true */
)
{
CollSeq[] pColl;
int nName = sqlite3Strlen30(zName);
pColl = sqlite3HashFind(db.aCollSeq, zName, nName, (CollSeq[])null);
if ((null == pColl) && create != 0)
{
pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
if (pColl != null)
{
CollSeq pDel = null;
pColl[0] = new CollSeq();
pColl[0].zName = zName;
pColl[0].enc = SQLITE_UTF8;
pColl[1] = new CollSeq();
pColl[1].zName = zName;
pColl[1].enc = SQLITE_UTF16LE;
pColl[2] = new CollSeq();
pColl[2].zName = zName;
pColl[2].enc = SQLITE_UTF16BE;
//memcpy(pColl[0].zName, zName, nName);
//pColl[0].zName[nName] = 0;
CollSeq[] pDelArray = sqlite3HashInsert(ref db.aCollSeq, pColl[0].zName, nName, pColl);
if (pDelArray != null)
pDel = pDelArray[0];
/* If a malloc() failure occurred in sqlite3HashInsert(), it will
** return the pColl pointer to be deleted (because it wasn't added
** to the hash table).
*/
Debug.Assert(pDel == null || pDel == pColl[0]);
if (pDel != null)
{
//// db.mallocFailed = 1;
pDel = null; //was sqlite3DbFree(db,ref pDel);
pColl = null;
}
}
}
return pColl;
}
/*
** Parameter zName points to a UTF-8 encoded string nName bytes long.
** Return the CollSeq* pointer for the collation sequence named zName
** for the encoding 'enc' from the database 'db'.
**
** If the entry specified is not found and 'create' is true, then create a
** new entry. Otherwise return NULL.
**
** A separate function sqlite3LocateCollSeq() is a wrapper around
** this routine. sqlite3LocateCollSeq() invokes the collation factory
** if necessary and generates an error message if the collating sequence
** cannot be found.
**
** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
*/
static CollSeq sqlite3FindCollSeq(
sqlite3 db,
u8 enc,
string zName,
u8 create
)
{
CollSeq[] pColl;
if (zName != null)
{
pColl = findCollSeqEntry(db, zName, create);
}
else
{
pColl = new CollSeq[enc];
pColl[enc - 1] = db.pDfltColl;
}
Debug.Assert(SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3);
Debug.Assert(enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE);
if (pColl != null)
{
enc -= 1; // if (pColl != null) pColl += enc - 1;
return pColl[enc];
}
else
return null;
}
/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 0 and 6, as follows:
**
** 0: Not a match, or if nArg<0 and the function is has no implementation.
** 1: A variable arguments function that prefers UTF-8 when a UTF-16
** encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
** requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality(FuncDef p, int nArg, int enc)
{
int match = 0;
if (p.nArg == -1 || p.nArg == nArg
|| (nArg == -1 && (p.xFunc != null || p.xStep != null))
)
{
match = 1;
if (p.nArg == nArg || nArg == -1)
{
match = 4;
}
if (enc == p.iPrefEnc)
{
match += 2;
}
else if ((enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE) ||
(enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE))
{
match += 1;
}
}
return match;
}
/*
** Search a FuncDefHash for a function with the given name. Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef functionSearch(
FuncDefHash pHash, /* Hash table to search */
int h, /* Hash of the name */
string zFunc, /* Name of function */
int nFunc /* Number of bytes in zFunc */
)
{
FuncDef p;
for (p = pHash.a[h]; p != null; p = p.pHash)
{
if (p.zName.Length == nFunc && p.zName.StartsWith(zFunc, StringComparison.InvariantCultureIgnoreCase))
{
return p;
}
}
return null;
}
/*
** Insert a new FuncDef into a FuncDefHash hash table.
*/
static void sqlite3FuncDefInsert(
FuncDefHash pHash, /* The hash table into which to insert */
FuncDef pDef /* The function definition to insert */
)
{
FuncDef pOther;
int nName = sqlite3Strlen30(pDef.zName);
u8 c1 = (u8)pDef.zName[0];
int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash.a);
pOther = functionSearch(pHash, h, pDef.zName, nName);
if (pOther != null)
{
Debug.Assert(pOther != pDef && pOther.pNext != pDef);
pDef.pNext = pOther.pNext;
pOther.pNext = pDef;
}
else
{
pDef.pNext = null;
pDef.pHash = pHash.a[h];
pHash.a[h] = pDef;
}
}
/*
** Locate a user function given a name, a number of arguments and a flag
** indicating whether the function prefers UTF-16 over UTF-8. Return a
** pointer to the FuncDef structure that defines that function, or return
** NULL if the function does not exist.
**
** If the createFlag argument is true, then a new (blank) FuncDef
** structure is created and liked into the "db" structure if a
** no matching function previously existed. When createFlag is true
** and the nArg parameter is -1, then only a function that accepts
** any number of arguments will be returned.
**
** If createFlag is false and nArg is -1, then the first valid
** function found is returned. A function is valid if either xFunc
** or xStep is non-zero.
**
** If createFlag is false, then a function with the required name and
** number of arguments may be returned even if the eTextRep flag does not
** match that requested.
*/
static FuncDef sqlite3FindFunction(
sqlite3 db, /* An open database */
string zName, /* Name of the function. Not null-terminated */
int nName, /* Number of characters in the name */
int nArg, /* Number of arguments. -1 means any number */
u8 enc, /* Preferred text encoding */
u8 createFlag /* Create new entry if true and does not otherwise exist */
)
{
FuncDef p; /* Iterator variable */
FuncDef pBest = null; /* Best match found so far */
int bestScore = 0;
int h; /* Hash value */
Debug.Assert(enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE);
h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db.aFunc.a);
/* First search for a match amongst the application-defined functions.
*/
p = functionSearch(db.aFunc, h, zName, nName);
while (p != null)
{
int score = matchQuality(p, nArg, enc);
if (score > bestScore)
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
/* If no match is found, search the built-in functions.
**
** If the SQLITE_PreferBuiltin flag is set, then search the built-in
** functions even if a prior app-defined function was found. And give
** priority to built-in functions.
**
** Except, if createFlag is true, that means that we are trying to
** install a new function. Whatever FuncDef structure is returned it will
** have fields overwritten with new information appropriate for the
** new function. But the FuncDefs for built-in functions are read-only.
** So we must not search for built-ins when creating a new function.
*/
if (0 == createFlag && (pBest == null || (db.flags & SQLITE_PreferBuiltin) != 0))
{
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions );
#else
FuncDefHash pHash = sqlite3GlobalFunctions;
#endif
bestScore = 0;
p = functionSearch(pHash, h, zName, nName);
while (p != null)
{
int score = matchQuality(p, nArg, enc);
if (score > bestScore)
{
pBest = p;
bestScore = score;
}
p = p.pNext;
}
}
/* If the createFlag parameter is true and the search did not reveal an
** exact match for the name, number of arguments and encoding, then add a
** new entry to the hash table and return it.
*/
if (createFlag != 0 && (bestScore < 6 || pBest.nArg != nArg) &&
(pBest = new FuncDef()) != null)
{ //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
//pBest.zName = (char *)&pBest[1];
pBest.nArg = (i16)nArg;
pBest.iPrefEnc = enc;
pBest.zName = zName; //memcpy(pBest.zName, zName, nName);
//pBest.zName[nName] = 0;
sqlite3FuncDefInsert(db.aFunc, pBest);
}
if (pBest != null && (pBest.xStep != null || pBest.xFunc != null || createFlag != 0))
{
return pBest;
}
return null;
}
/*
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
** pointer itself, it just cleans up subsidiary resources (i.e. the contents
** of the schema hash tables).
**
** The Schema.cache_size variable is not cleared.
*/
static void sqlite3SchemaClear(Schema p)
{
Hash temp1;
Hash temp2;
HashElem pElem;
Schema pSchema = p;
temp1 = pSchema.tblHash;
temp2 = pSchema.trigHash;
sqlite3HashInit(pSchema.trigHash);
sqlite3HashClear(pSchema.idxHash);
for (pElem = sqliteHashFirst(temp2); pElem != null; pElem = sqliteHashNext(pElem))
{
Trigger pTrigger = (Trigger)sqliteHashData(pElem);
sqlite3DeleteTrigger(null, ref pTrigger);
}
sqlite3HashClear(temp2);
sqlite3HashInit(pSchema.trigHash);
for (pElem = temp1.first; pElem != null; pElem = pElem.next)//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem))
{
Table pTab = (Table)pElem.data; //sqliteHashData(pElem);
sqlite3DeleteTable(null, ref pTab);
}
sqlite3HashClear(temp1);
sqlite3HashClear(pSchema.fkeyHash);
pSchema.pSeqTab = null;
if ((pSchema.flags & DB_SchemaLoaded) != 0)
{
pSchema.iGeneration++;
pSchema.flags = (u16)(pSchema.flags & (~DB_SchemaLoaded));
}
p.Clear();
}
/*
** Find and return the schema associated with a BTree. Create
** a new one if necessary.
*/
static Schema sqlite3SchemaGet(sqlite3 db, Btree pBt)
{
Schema p;
if (pBt != null)
{
p = sqlite3BtreeSchema(pBt, -1, (dxFreeSchema)sqlite3SchemaClear);//Schema.Length, sqlite3SchemaFree);
}
else
{
p = new Schema(); // (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
}
if (p == null)
{
//// db.mallocFailed = 1;
}
else if (0 == p.file_format)
{
sqlite3HashInit(p.tblHash);
sqlite3HashInit(p.idxHash);
sqlite3HashInit(p.trigHash);
sqlite3HashInit(p.fkeyHash);
p.enc = SQLITE_UTF8;
}
return p;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Transactions;
namespace Orleans.CodeGeneration
{
internal static class GrainInterfaceUtils
{
private static readonly IEqualityComparer<MethodInfo> MethodComparer = new MethodInfoComparer();
[Serializable]
internal class RulesViolationException : ArgumentException
{
public RulesViolationException(string message, List<string> violations)
: base(message)
{
Violations = violations;
}
public List<string> Violations { get; private set; }
}
public static bool IsGrainInterface(Type t)
{
if (t.GetTypeInfo().IsClass)
return false;
if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension))
return false;
if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey)
|| t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey))
return false;
if (t == typeof (ISystemTarget))
return false;
return typeof (IAddressable).IsAssignableFrom(t);
}
public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true)
{
var methodInfos = new List<MethodInfo>();
GetMethodsImpl(grainType, grainType, methodInfos);
var flags = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance;
if (!bAllMethods)
flags |= BindingFlags.DeclaredOnly;
MethodInfo[] infos = grainType.GetMethods(flags);
foreach (var methodInfo in infos)
if (!methodInfos.Contains(methodInfo, MethodComparer))
methodInfos.Add(methodInfo);
return methodInfos.ToArray();
}
public static string GetParameterName(ParameterInfo info)
{
var n = info.Name;
return string.IsNullOrEmpty(n) ? "arg" + info.Position : n;
}
public static bool IsTaskType(Type t)
{
var typeInfo = t.GetTypeInfo();
return t == typeof (Task)
|| (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.Task`1");
}
/// <summary>
/// Whether method is read-only, i.e. does not modify grain state,
/// a method marked with [ReadOnly].
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static bool IsReadOnly(MethodInfo info)
{
return info.GetCustomAttributes(typeof (ReadOnlyAttribute), true).Any();
}
public static bool IsAlwaysInterleave(MethodInfo methodInfo)
{
return methodInfo.GetCustomAttributes(typeof (AlwaysInterleaveAttribute), true).Any();
}
public static bool IsUnordered(MethodInfo methodInfo)
{
var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo();
return declaringTypeInfo.GetCustomAttributes(typeof(UnorderedAttribute), true).Any()
|| (declaringTypeInfo.GetInterfaces().Any(
i => i.GetTypeInfo().GetCustomAttributes(typeof(UnorderedAttribute), true).Any()
&& declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo)))
|| IsStatelessWorker(methodInfo);
}
public static bool IsStatelessWorker(TypeInfo grainTypeInfo)
{
return grainTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() ||
grainTypeInfo.GetInterfaces()
.Any(i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any());
}
public static bool IsStatelessWorker(MethodInfo methodInfo)
{
var declaringTypeInfo = methodInfo.DeclaringType.GetTypeInfo();
return declaringTypeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() ||
(declaringTypeInfo.GetInterfaces().Any(
i => i.GetTypeInfo().GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any()
&& declaringTypeInfo.GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo)));
}
public static bool IsNewTransactionRequired(MethodInfo methodInfo)
{
TransactionAttribute transactionAttribute = methodInfo.GetCustomAttribute<TransactionAttribute>(true);
if (transactionAttribute != null)
{
return transactionAttribute.Requirement == TransactionOption.RequiresNew;
}
return false;
}
public static bool IsTransactionRequired(MethodInfo methodInfo)
{
TransactionAttribute transactionAttribute = methodInfo.GetCustomAttribute<TransactionAttribute>(true);
if (transactionAttribute != null)
{
return transactionAttribute.Requirement == TransactionOption.Required;
}
return false;
}
public static Dictionary<int, Type> GetRemoteInterfaces(Type type, bool checkIsGrainInterface = true)
{
var dict = new Dictionary<int, Type>();
if (IsGrainInterface(type))
dict.Add(GetGrainInterfaceId(type), type);
Type[] interfaces = type.GetInterfaces();
foreach (Type interfaceType in interfaces.Where(i => !checkIsGrainInterface || IsGrainInterface(i)))
dict.Add(GetGrainInterfaceId(interfaceType), interfaceType);
return dict;
}
public static int ComputeMethodId(MethodInfo methodInfo)
{
var attr = methodInfo.GetCustomAttribute<MethodIdAttribute>(true);
if (attr != null) return attr.MethodId;
var strMethodId = new StringBuilder(methodInfo.Name);
if (methodInfo.IsGenericMethodDefinition)
{
strMethodId.Append('<');
var first = true;
foreach (var arg in methodInfo.GetGenericArguments())
{
if (!first) strMethodId.Append(',');
else first = false;
strMethodId.Append(arg.Name);
}
strMethodId.Append('>');
}
strMethodId.Append('(');
ParameterInfo[] parameters = methodInfo.GetParameters();
bool bFirstTime = true;
foreach (ParameterInfo info in parameters)
{
if (!bFirstTime)
strMethodId.Append(',');
strMethodId.Append(info.ParameterType.Name);
var typeInfo = info.ParameterType.GetTypeInfo();
if (typeInfo.IsGenericType)
{
Type[] args = typeInfo.GetGenericArguments();
foreach (Type arg in args)
strMethodId.Append(arg.Name);
}
bFirstTime = false;
}
strMethodId.Append(')');
return Utils.CalculateIdHash(strMethodId.ToString());
}
public static int GetGrainInterfaceId(Type grainInterface)
{
return GetTypeCode(grainInterface);
}
public static ushort GetGrainInterfaceVersion(Type grainInterface)
{
if (typeof(IGrainExtension).IsAssignableFrom(grainInterface))
return 0;
var attr = grainInterface.GetTypeInfo().GetCustomAttribute<VersionAttribute>();
return attr?.Version ?? Constants.DefaultInterfaceVersion;
}
public static bool IsTaskBasedInterface(Type type)
{
var methods = type.GetMethods();
// An interface is task-based if it has at least one method that returns a Task or at least one parent that's task-based.
return methods.Any(m => IsTaskType(m.ReturnType)) || type.GetInterfaces().Any(IsTaskBasedInterface);
}
public static bool IsGrainType(Type grainType)
{
return typeof (IGrain).IsAssignableFrom(grainType);
}
public static int GetGrainClassTypeCode(Type grainClass)
{
return GetTypeCode(grainClass);
}
internal static bool TryValidateInterfaceRules(Type type, out List<string> violations)
{
violations = new List<string>();
bool success = ValidateInterfaceMethods(type, violations);
return success && ValidateInterfaceProperties(type, violations);
}
internal static void ValidateInterfaceRules(Type type)
{
List<string> violations;
if (!TryValidateInterfaceRules(type, out violations))
{
if (ConsoleText.IsConsoleAvailable)
{
foreach (var violation in violations)
ConsoleText.WriteLine("ERROR: " + violation);
}
throw new RulesViolationException(
string.Format("{0} does not conform to the grain interface rules.", type.FullName), violations);
}
}
internal static void ValidateInterface(Type type)
{
if (!IsGrainInterface(type))
throw new ArgumentException(String.Format("{0} is not a grain interface", type.FullName));
ValidateInterfaceRules(type);
}
private static bool ValidateInterfaceMethods(Type type, List<string> violations)
{
bool success = true;
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
if (method.IsSpecialName)
continue;
if (IsPureObserverInterface(method.DeclaringType))
{
if (method.ReturnType != typeof (void))
{
success = false;
violations.Add(String.Format("Method {0}.{1} must return void because it is defined within an observer interface.",
type.FullName, method.Name));
}
}
else if (!IsTaskType(method.ReturnType))
{
success = false;
violations.Add(String.Format("Method {0}.{1} must return Task or Task<T> because it is defined within a grain interface.",
type.FullName, method.Name));
}
ParameterInfo[] parameters = method.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
if (parameter.IsOut)
{
success = false;
violations.Add(String.Format("Argument {0} of method {1}.{2} is an output parameter. Output parameters are not allowed in grain interfaces.",
GetParameterName(parameter), type.FullName, method.Name));
}
if (parameter.ParameterType.GetTypeInfo().IsByRef)
{
success = false;
violations.Add(String.Format("Argument {0} of method {1}.{2} is an a reference parameter. Reference parameters are not allowed.",
GetParameterName(parameter), type.FullName, method.Name));
}
}
}
return success;
}
private static bool ValidateInterfaceProperties(Type type, List<string> violations)
{
bool success = true;
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
success = false;
violations.Add(String.Format("Properties are not allowed on grain interfaces: {0}.{1}.",
type.FullName, property.Name));
}
return success;
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
private static bool IsPureObserverInterface(Type t)
{
if (!typeof (IGrainObserver).IsAssignableFrom(t))
return false;
if (t == typeof (IGrainObserver))
return true;
if (t == typeof (IAddressable))
return false;
bool pure = false;
foreach (Type iface in t.GetInterfaces())
{
if (iface == typeof (IAddressable)) // skip IAddressable that will be in the list regardless
continue;
if (iface == typeof (IGrainExtension))
// Skip IGrainExtension, it's just a marker that can go on observer or grain interfaces
continue;
pure = IsPureObserverInterface(iface);
if (!pure)
return false;
}
return pure;
}
private class MethodInfoComparer : IEqualityComparer<MethodInfo>
{
#region IEqualityComparer<InterfaceInfo> Members
public bool Equals(MethodInfo x, MethodInfo y)
{
return string.Equals(GetSignature(x), GetSignature(y), StringComparison.Ordinal);
}
private static string GetSignature(MethodInfo method)
{
var result = new StringBuilder(method.Name);
if (method.IsGenericMethodDefinition)
{
foreach (var arg in method.GetGenericArguments())
{
result.Append(arg.Name);
}
}
var parms = method.GetParameters();
foreach (var info in parms)
{
var typeInfo = info.ParameterType.GetTypeInfo();
result.Append(typeInfo.Name);
if (typeInfo.IsGenericType)
{
var args = info.ParameterType.GetGenericArguments();
foreach (var arg in args)
{
result.Append(arg.Name);
}
}
}
return result.ToString();
}
public int GetHashCode(MethodInfo obj)
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
/// Recurses through interface graph accumulating methods
/// </summary>
/// <param name="grainType">Grain type</param>
/// <param name="serviceType">Service interface type</param>
/// <param name="methodInfos">Accumulated </param>
private static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos)
{
Type[] iTypes = GetRemoteInterfaces(serviceType, false).Values.ToArray();
IEqualityComparer<MethodInfo> methodComparer = new MethodInfoComparer();
var typeInfo = grainType.GetTypeInfo();
foreach (Type iType in iTypes)
{
var mapping = new InterfaceMapping();
if (typeInfo.IsClass)
mapping = typeInfo.GetRuntimeInterfaceMap(iType);
if (typeInfo.IsInterface || mapping.TargetType == grainType)
{
foreach (var methodInfo in iType.GetMethods())
{
if (typeInfo.IsClass)
{
var mi = methodInfo;
var match = mapping.TargetMethods.Any(info => methodComparer.Equals(mi, info) &&
info.DeclaringType == grainType);
if (match)
if (!methodInfos.Contains(mi, methodComparer))
methodInfos.Add(mi);
}
else if (!methodInfos.Contains(methodInfo, methodComparer))
{
methodInfos.Add(methodInfo);
}
}
}
}
}
private static int GetTypeCode(Type grainInterfaceOrClass)
{
var typeInfo = grainInterfaceOrClass.GetTypeInfo();
var attr = typeInfo.GetCustomAttributes<TypeCodeOverrideAttribute>(false).FirstOrDefault();
if (attr != null && attr.TypeCode > 0)
{
return attr.TypeCode;
}
var fullName = TypeUtils.GetTemplatedName(
TypeUtils.GetFullName(grainInterfaceOrClass),
grainInterfaceOrClass,
grainInterfaceOrClass.GetGenericArguments(),
t => false);
return Utils.CalculateIdHash(fullName);
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Management.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Management\Remove-WmiObject command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class RemoveWmiObject : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public RemoveWmiObject()
{
this.DisplayName = "Remove-WmiObject";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Management\\Remove-WmiObject"; } }
// Arguments
/// <summary>
/// Provides access to the InputObject parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.ManagementObject> InputObject { get; set; }
/// <summary>
/// Provides access to the Path parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Path { get; set; }
/// <summary>
/// Provides access to the Class parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Class { get; set; }
/// <summary>
/// Provides access to the AsJob parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> AsJob { get; set; }
/// <summary>
/// Provides access to the Impersonation parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.ImpersonationLevel> Impersonation { get; set; }
/// <summary>
/// Provides access to the Authentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.AuthenticationLevel> Authentication { get; set; }
/// <summary>
/// Provides access to the Locale parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Locale { get; set; }
/// <summary>
/// Provides access to the EnableAllPrivileges parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> EnableAllPrivileges { get; set; }
/// <summary>
/// Provides access to the Authority parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Authority { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the ThrottleLimit parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> ThrottleLimit { get; set; }
/// <summary>
/// Provides access to the ComputerName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ComputerName { get; set; }
/// <summary>
/// Provides access to the Namespace parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Namespace { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(InputObject.Expression != null)
{
targetCommand.AddParameter("InputObject", InputObject.Get(context));
}
if(Path.Expression != null)
{
targetCommand.AddParameter("Path", Path.Get(context));
}
if(Class.Expression != null)
{
targetCommand.AddParameter("Class", Class.Get(context));
}
if(AsJob.Expression != null)
{
targetCommand.AddParameter("AsJob", AsJob.Get(context));
}
if(Impersonation.Expression != null)
{
targetCommand.AddParameter("Impersonation", Impersonation.Get(context));
}
if(Authentication.Expression != null)
{
targetCommand.AddParameter("Authentication", Authentication.Get(context));
}
if(Locale.Expression != null)
{
targetCommand.AddParameter("Locale", Locale.Get(context));
}
if(EnableAllPrivileges.Expression != null)
{
targetCommand.AddParameter("EnableAllPrivileges", EnableAllPrivileges.Get(context));
}
if(Authority.Expression != null)
{
targetCommand.AddParameter("Authority", Authority.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(ThrottleLimit.Expression != null)
{
targetCommand.AddParameter("ThrottleLimit", ThrottleLimit.Get(context));
}
if(ComputerName.Expression != null)
{
targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
}
if(Namespace.Expression != null)
{
targetCommand.AddParameter("Namespace", Namespace.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
//
// 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.Linq;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// Parameters supplied to the Create Virtual Machine Image operation.
/// </summary>
public partial class VirtualMachineImageCreateParameters
{
private string _description;
/// <summary>
/// Optional. Specifies the description of the OS image.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private string _eula;
/// <summary>
/// Optional. Specifies the End User License Agreement that is
/// associated with the image. The value for this element is a string,
/// but it is recommended that the value be a URL that points to a
/// EULA.
/// </summary>
public string Eula
{
get { return this._eula; }
set { this._eula = value; }
}
private Uri _iconUri;
/// <summary>
/// Optional. Specifies the Uri to the icon that is displayed for the
/// image in the Management Portal.
/// </summary>
public Uri IconUri
{
get { return this._iconUri; }
set { this._iconUri = value; }
}
private string _imageFamily;
/// <summary>
/// Optional. Specifies a value that can be used to group OS images.
/// </summary>
public string ImageFamily
{
get { return this._imageFamily; }
set { this._imageFamily = value; }
}
private bool _isPremium;
/// <summary>
/// Indicates if the image contains software or associated services
/// that will incur charges above the core price for the virtual
/// machine.
/// </summary>
public bool IsPremium
{
get { return this._isPremium; }
set { this._isPremium = value; }
}
private string _label;
/// <summary>
/// Required. Specifies the friendly name of the image.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _language;
/// <summary>
/// Specifies the language of the image. The Language element is only
/// available using version 2013-03-01 or higher.
/// </summary>
public string Language
{
get { return this._language; }
set { this._language = value; }
}
private Uri _mediaLinkUri;
/// <summary>
/// Required. Specifies the location of the blob in Windows Azure
/// storage. The blob location must belong to a storage account in the
/// subscription specified by the SubscriptionId value in the
/// operation call. Example:
/// http://example.blob.core.windows.net/disks/mydisk.vhd
/// </summary>
public Uri MediaLinkUri
{
get { return this._mediaLinkUri; }
set { this._mediaLinkUri = value; }
}
private string _name;
/// <summary>
/// Required. Specifies a name that Windows Azure uses to identify the
/// image when creating one or more virtual machines.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _operatingSystemType;
/// <summary>
/// Required. The operating system type of the OS image. Possible
/// values are: Linux, Windows.
/// </summary>
public string OperatingSystemType
{
get { return this._operatingSystemType; }
set { this._operatingSystemType = value; }
}
private Uri _privacyUri;
/// <summary>
/// Optional. Specifies the URI that points to a document that contains
/// the privacy policy related to the OS image.
/// </summary>
public Uri PrivacyUri
{
get { return this._privacyUri; }
set { this._privacyUri = value; }
}
private System.DateTime? _publishedDate;
/// <summary>
/// Optional. Specifies the date when the OS image was added to the
/// image repository.
/// </summary>
public System.DateTime? PublishedDate
{
get { return this._publishedDate; }
set { this._publishedDate = value; }
}
private string _recommendedVMSize;
/// <summary>
/// Optional. Specifies the size to use for the virtual machine that is
/// created from the OS image.
/// </summary>
public string RecommendedVMSize
{
get { return this._recommendedVMSize; }
set { this._recommendedVMSize = value; }
}
private bool _showInGui;
/// <summary>
/// Specifies whether the image should appear in the image gallery.
/// </summary>
public bool ShowInGui
{
get { return this._showInGui; }
set { this._showInGui = value; }
}
private Uri _smallIconUri;
/// <summary>
/// Specifies the URI to the small icon that is displayed when the
/// image is presented in the Windows Azure Management Portal. The
/// SmallIconUri element is only available using version 2013-03-01 or
/// higher.
/// </summary>
public Uri SmallIconUri
{
get { return this._smallIconUri; }
set { this._smallIconUri = value; }
}
/// <summary>
/// Initializes a new instance of the
/// VirtualMachineImageCreateParameters class.
/// </summary>
public VirtualMachineImageCreateParameters()
{
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// NotaryJurisdiction
/// </summary>
[DataContract]
public partial class NotaryJurisdiction : IEquatable<NotaryJurisdiction>, IValidatableObject
{
public NotaryJurisdiction()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="NotaryJurisdiction" /> class.
/// </summary>
/// <param name="CommissionExpiration">CommissionExpiration.</param>
/// <param name="CommissionId">CommissionId.</param>
/// <param name="County">County.</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="Jurisdiction">Jurisdiction.</param>
/// <param name="RegisteredName">RegisteredName.</param>
/// <param name="SealType">SealType.</param>
public NotaryJurisdiction(string CommissionExpiration = default(string), string CommissionId = default(string), string County = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), Jurisdiction Jurisdiction = default(Jurisdiction), string RegisteredName = default(string), string SealType = default(string))
{
this.CommissionExpiration = CommissionExpiration;
this.CommissionId = CommissionId;
this.County = County;
this.ErrorDetails = ErrorDetails;
this.Jurisdiction = Jurisdiction;
this.RegisteredName = RegisteredName;
this.SealType = SealType;
}
/// <summary>
/// Gets or Sets CommissionExpiration
/// </summary>
[DataMember(Name="commissionExpiration", EmitDefaultValue=false)]
public string CommissionExpiration { get; set; }
/// <summary>
/// Gets or Sets CommissionId
/// </summary>
[DataMember(Name="commissionId", EmitDefaultValue=false)]
public string CommissionId { get; set; }
/// <summary>
/// Gets or Sets County
/// </summary>
[DataMember(Name="county", EmitDefaultValue=false)]
public string County { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// Gets or Sets Jurisdiction
/// </summary>
[DataMember(Name="jurisdiction", EmitDefaultValue=false)]
public Jurisdiction Jurisdiction { get; set; }
/// <summary>
/// Gets or Sets RegisteredName
/// </summary>
[DataMember(Name="registeredName", EmitDefaultValue=false)]
public string RegisteredName { get; set; }
/// <summary>
/// Gets or Sets SealType
/// </summary>
[DataMember(Name="sealType", EmitDefaultValue=false)]
public string SealType { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NotaryJurisdiction {\n");
sb.Append(" CommissionExpiration: ").Append(CommissionExpiration).Append("\n");
sb.Append(" CommissionId: ").Append(CommissionId).Append("\n");
sb.Append(" County: ").Append(County).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" Jurisdiction: ").Append(Jurisdiction).Append("\n");
sb.Append(" RegisteredName: ").Append(RegisteredName).Append("\n");
sb.Append(" SealType: ").Append(SealType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as NotaryJurisdiction);
}
/// <summary>
/// Returns true if NotaryJurisdiction instances are equal
/// </summary>
/// <param name="other">Instance of NotaryJurisdiction to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NotaryJurisdiction other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CommissionExpiration == other.CommissionExpiration ||
this.CommissionExpiration != null &&
this.CommissionExpiration.Equals(other.CommissionExpiration)
) &&
(
this.CommissionId == other.CommissionId ||
this.CommissionId != null &&
this.CommissionId.Equals(other.CommissionId)
) &&
(
this.County == other.County ||
this.County != null &&
this.County.Equals(other.County)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.Jurisdiction == other.Jurisdiction ||
this.Jurisdiction != null &&
this.Jurisdiction.Equals(other.Jurisdiction)
) &&
(
this.RegisteredName == other.RegisteredName ||
this.RegisteredName != null &&
this.RegisteredName.Equals(other.RegisteredName)
) &&
(
this.SealType == other.SealType ||
this.SealType != null &&
this.SealType.Equals(other.SealType)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CommissionExpiration != null)
hash = hash * 59 + this.CommissionExpiration.GetHashCode();
if (this.CommissionId != null)
hash = hash * 59 + this.CommissionId.GetHashCode();
if (this.County != null)
hash = hash * 59 + this.County.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.Jurisdiction != null)
hash = hash * 59 + this.Jurisdiction.GetHashCode();
if (this.RegisteredName != null)
hash = hash * 59 + this.RegisteredName.GetHashCode();
if (this.SealType != null)
hash = hash * 59 + this.SealType.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for PoolOperations.
/// </summary>
public static partial class PoolOperationsExtensions
{
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <remarks>
/// If you do not specify a $filter clause including a poolId, the response
/// includes all pools that existed in the account in the time range of the
/// returned aggregation intervals.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListUsageMetricsOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<PoolUsageMetrics> ListUsageMetrics(this IPoolOperations operations, PoolListUsageMetricsOptions poolListUsageMetricsOptions = default(PoolListUsageMetricsOptions))
{
return ((IPoolOperations)operations).ListUsageMetricsAsync(poolListUsageMetricsOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <remarks>
/// If you do not specify a $filter clause including a poolId, the response
/// includes all pools that existed in the account in the time range of the
/// returned aggregation intervals.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListUsageMetricsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<PoolUsageMetrics>> ListUsageMetricsAsync(this IPoolOperations operations, PoolListUsageMetricsOptions poolListUsageMetricsOptions = default(PoolListUsageMetricsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListUsageMetricsWithHttpMessagesAsync(poolListUsageMetricsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets lifetime summary statistics for all of the pools in the specified
/// account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all pools that have ever existed in the
/// account, from account creation to the last update time of the statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolStatistics GetAllLifetimeStatistics(this IPoolOperations operations, PoolGetAllLifetimeStatisticsOptions poolGetAllLifetimeStatisticsOptions = default(PoolGetAllLifetimeStatisticsOptions))
{
return ((IPoolOperations)operations).GetAllLifetimeStatisticsAsync(poolGetAllLifetimeStatisticsOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets lifetime summary statistics for all of the pools in the specified
/// account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all pools that have ever existed in the
/// account, from account creation to the last update time of the statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolStatistics> GetAllLifetimeStatisticsAsync(this IPoolOperations operations, PoolGetAllLifetimeStatisticsOptions poolGetAllLifetimeStatisticsOptions = default(PoolGetAllLifetimeStatisticsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetAllLifetimeStatisticsWithHttpMessagesAsync(poolGetAllLifetimeStatisticsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Adds a pool to the specified account.
/// </summary>
/// <remarks>
/// When naming pools, avoid including sensitive information such as user names
/// or secret project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pool'>
/// The pool to be added.
/// </param>
/// <param name='poolAddOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolAddHeaders Add(this IPoolOperations operations, PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions))
{
return ((IPoolOperations)operations).AddAsync(pool, poolAddOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Adds a pool to the specified account.
/// </summary>
/// <remarks>
/// When naming pools, avoid including sensitive information such as user names
/// or secret project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pool'>
/// The pool to be added.
/// </param>
/// <param name='poolAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolAddHeaders> AddAsync(this IPoolOperations operations, PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddWithHttpMessagesAsync(pool, poolAddOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudPool> List(this IPoolOperations operations, PoolListOptions poolListOptions = default(PoolListOptions))
{
return ((IPoolOperations)operations).ListAsync(poolListOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<CloudPool>> ListAsync(this IPoolOperations operations, PoolListOptions poolListOptions = default(PoolListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(poolListOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a pool from the specified account.
/// </summary>
/// <remarks>
/// When you request that a pool be deleted, the following actions occur: the
/// pool state is set to deleting; any ongoing resize operation on the pool are
/// stopped; the Batch service starts resizing the pool to zero nodes; any
/// tasks running on existing nodes are terminated and requeued (as if a resize
/// pool operation had been requested with the default requeue option);
/// finally, the pool is removed from the system. Because running tasks are
/// requeued, the user can rerun these tasks by updating their job to target a
/// different pool. The tasks can then run on the new pool. If you want to
/// override the requeue behavior, then you should call resize pool explicitly
/// to shrink the pool to zero size before deleting the pool. If you call an
/// Update, Patch or Delete API on a pool in the deleting state, it will fail
/// with HTTP status code 409 with error code PoolBeingDeleted.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to delete.
/// </param>
/// <param name='poolDeleteOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolDeleteHeaders Delete(this IPoolOperations operations, string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions))
{
return ((IPoolOperations)operations).DeleteAsync(poolId, poolDeleteOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pool from the specified account.
/// </summary>
/// <remarks>
/// When you request that a pool be deleted, the following actions occur: the
/// pool state is set to deleting; any ongoing resize operation on the pool are
/// stopped; the Batch service starts resizing the pool to zero nodes; any
/// tasks running on existing nodes are terminated and requeued (as if a resize
/// pool operation had been requested with the default requeue option);
/// finally, the pool is removed from the system. Because running tasks are
/// requeued, the user can rerun these tasks by updating their job to target a
/// different pool. The tasks can then run on the new pool. If you want to
/// override the requeue behavior, then you should call resize pool explicitly
/// to shrink the pool to zero size before deleting the pool. If you call an
/// Update, Patch or Delete API on a pool in the deleting state, it will fail
/// with HTTP status code 409 with error code PoolBeingDeleted.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to delete.
/// </param>
/// <param name='poolDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolDeleteHeaders> DeleteAsync(this IPoolOperations operations, string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(poolId, poolDeleteOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets basic properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to get.
/// </param>
/// <param name='poolExistsOptions'>
/// Additional parameters for the operation
/// </param>
public static bool Exists(this IPoolOperations operations, string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions))
{
return ((IPoolOperations)operations).ExistsAsync(poolId, poolExistsOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets basic properties of a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to get.
/// </param>
/// <param name='poolExistsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<bool> ExistsAsync(this IPoolOperations operations, string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ExistsWithHttpMessagesAsync(poolId, poolExistsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets information about the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to get.
/// </param>
/// <param name='poolGetOptions'>
/// Additional parameters for the operation
/// </param>
public static CloudPool Get(this IPoolOperations operations, string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions))
{
return ((IPoolOperations)operations).GetAsync(poolId, poolGetOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to get.
/// </param>
/// <param name='poolGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CloudPool> GetAsync(this IPoolOperations operations, string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(poolId, poolGetOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the properties of the specified pool.
/// </summary>
/// <remarks>
/// This only replaces the pool properties specified in the request. For
/// example, if the pool has a start task associated with it, and a request
/// does not specify a start task element, then the pool keeps the existing
/// start task.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to update.
/// </param>
/// <param name='poolPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolPatchOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolPatchHeaders Patch(this IPoolOperations operations, string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions))
{
return ((IPoolOperations)operations).PatchAsync(poolId, poolPatchParameter, poolPatchOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified pool.
/// </summary>
/// <remarks>
/// This only replaces the pool properties specified in the request. For
/// example, if the pool has a start task associated with it, and a request
/// does not specify a start task element, then the pool keeps the existing
/// start task.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to update.
/// </param>
/// <param name='poolPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolPatchHeaders> PatchAsync(this IPoolOperations operations, string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(poolId, poolPatchParameter, poolPatchOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Disables automatic scaling for a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool on which to disable automatic scaling.
/// </param>
/// <param name='poolDisableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolDisableAutoScaleHeaders DisableAutoScale(this IPoolOperations operations, string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions))
{
return ((IPoolOperations)operations).DisableAutoScaleAsync(poolId, poolDisableAutoScaleOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Disables automatic scaling for a pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool on which to disable automatic scaling.
/// </param>
/// <param name='poolDisableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolDisableAutoScaleHeaders> DisableAutoScaleAsync(this IPoolOperations operations, string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DisableAutoScaleWithHttpMessagesAsync(poolId, poolDisableAutoScaleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Enables automatic scaling for a pool.
/// </summary>
/// <remarks>
/// You cannot enable automatic scaling on a pool if a resize operation is in
/// progress on the pool. If automatic scaling of the pool is currently
/// disabled, you must specify a valid autoscale formula as part of the
/// request. If automatic scaling of the pool is already enabled, you may
/// specify a new autoscale formula and/or a new evaluation interval. You
/// cannot call this API for the same pool more than once every 30 seconds.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool on which to enable automatic scaling.
/// </param>
/// <param name='poolEnableAutoScaleParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolEnableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolEnableAutoScaleHeaders EnableAutoScale(this IPoolOperations operations, string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions))
{
return ((IPoolOperations)operations).EnableAutoScaleAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Enables automatic scaling for a pool.
/// </summary>
/// <remarks>
/// You cannot enable automatic scaling on a pool if a resize operation is in
/// progress on the pool. If automatic scaling of the pool is currently
/// disabled, you must specify a valid autoscale formula as part of the
/// request. If automatic scaling of the pool is already enabled, you may
/// specify a new autoscale formula and/or a new evaluation interval. You
/// cannot call this API for the same pool more than once every 30 seconds.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool on which to enable automatic scaling.
/// </param>
/// <param name='poolEnableAutoScaleParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolEnableAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolEnableAutoScaleHeaders> EnableAutoScaleAsync(this IPoolOperations operations, string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.EnableAutoScaleWithHttpMessagesAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets the result of evaluating an automatic scaling formula on the pool.
/// </summary>
/// <remarks>
/// This API is primarily for validating an autoscale formula, as it simply
/// returns the result without applying the formula to the pool.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool on which to evaluate the automatic scaling formula.
/// </param>
/// <param name='autoScaleFormula'>
/// The formula for the desired number of compute nodes in the pool. The
/// formula is validated and its results calculated, but it is not applied to
/// the pool. To apply the formula to the pool, 'Enable automatic scaling on a
/// pool'. For more information about specifying this formula, see
/// Automatically scale compute nodes in an Azure Batch pool
/// (https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling).
/// </param>
/// <param name='poolEvaluateAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
public static AutoScaleRun EvaluateAutoScale(this IPoolOperations operations, string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions))
{
return ((IPoolOperations)operations).EvaluateAutoScaleAsync(poolId, autoScaleFormula, poolEvaluateAutoScaleOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the result of evaluating an automatic scaling formula on the pool.
/// </summary>
/// <remarks>
/// This API is primarily for validating an autoscale formula, as it simply
/// returns the result without applying the formula to the pool.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool on which to evaluate the automatic scaling formula.
/// </param>
/// <param name='autoScaleFormula'>
/// The formula for the desired number of compute nodes in the pool. The
/// formula is validated and its results calculated, but it is not applied to
/// the pool. To apply the formula to the pool, 'Enable automatic scaling on a
/// pool'. For more information about specifying this formula, see
/// Automatically scale compute nodes in an Azure Batch pool
/// (https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling).
/// </param>
/// <param name='poolEvaluateAutoScaleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<AutoScaleRun> EvaluateAutoScaleAsync(this IPoolOperations operations, string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.EvaluateAutoScaleWithHttpMessagesAsync(poolId, autoScaleFormula, poolEvaluateAutoScaleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Changes the number of compute nodes that are assigned to a pool.
/// </summary>
/// <remarks>
/// You can only resize a pool when its allocation state is steady. If the pool
/// is already resizing, the request fails with status code 409. When you
/// resize a pool, the pool's allocation state changes from steady to resizing.
/// You cannot resize pools which are configured for automatic scaling. If you
/// try to do this, the Batch service returns an error 409. If you resize a
/// pool downwards, the Batch service chooses which nodes to remove. To remove
/// specific nodes, use the pool remove nodes API instead.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to resize.
/// </param>
/// <param name='poolResizeParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolResizeOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolResizeHeaders Resize(this IPoolOperations operations, string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions))
{
return ((IPoolOperations)operations).ResizeAsync(poolId, poolResizeParameter, poolResizeOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Changes the number of compute nodes that are assigned to a pool.
/// </summary>
/// <remarks>
/// You can only resize a pool when its allocation state is steady. If the pool
/// is already resizing, the request fails with status code 409. When you
/// resize a pool, the pool's allocation state changes from steady to resizing.
/// You cannot resize pools which are configured for automatic scaling. If you
/// try to do this, the Batch service returns an error 409. If you resize a
/// pool downwards, the Batch service chooses which nodes to remove. To remove
/// specific nodes, use the pool remove nodes API instead.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to resize.
/// </param>
/// <param name='poolResizeParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolResizeHeaders> ResizeAsync(this IPoolOperations operations, string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ResizeWithHttpMessagesAsync(poolId, poolResizeParameter, poolResizeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Stops an ongoing resize operation on the pool.
/// </summary>
/// <remarks>
/// This does not restore the pool to its previous state before the resize
/// operation: it only stops any further changes being made, and the pool
/// maintains its current state. A resize operation need not be an explicit
/// resize pool request; this API can also be used to halt the initial sizing
/// of the pool when it is created.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool whose resizing you want to stop.
/// </param>
/// <param name='poolStopResizeOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolStopResizeHeaders StopResize(this IPoolOperations operations, string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions))
{
return ((IPoolOperations)operations).StopResizeAsync(poolId, poolStopResizeOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Stops an ongoing resize operation on the pool.
/// </summary>
/// <remarks>
/// This does not restore the pool to its previous state before the resize
/// operation: it only stops any further changes being made, and the pool
/// maintains its current state. A resize operation need not be an explicit
/// resize pool request; this API can also be used to halt the initial sizing
/// of the pool when it is created.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool whose resizing you want to stop.
/// </param>
/// <param name='poolStopResizeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolStopResizeHeaders> StopResizeAsync(this IPoolOperations operations, string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.StopResizeWithHttpMessagesAsync(poolId, poolStopResizeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Updates the properties of the specified pool.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the pool. For example,
/// if the pool has a start task associated with it and if start task is not
/// specified with this request, then the Batch service will remove the
/// existing start task.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to update.
/// </param>
/// <param name='poolUpdatePropertiesParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolUpdatePropertiesOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolUpdatePropertiesHeaders UpdateProperties(this IPoolOperations operations, string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions))
{
return ((IPoolOperations)operations).UpdatePropertiesAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified pool.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the pool. For example,
/// if the pool has a start task associated with it and if start task is not
/// specified with this request, then the Batch service will remove the
/// existing start task.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to update.
/// </param>
/// <param name='poolUpdatePropertiesParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolUpdatePropertiesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolUpdatePropertiesHeaders> UpdatePropertiesAsync(this IPoolOperations operations, string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpdatePropertiesWithHttpMessagesAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Upgrades the operating system of the specified pool.
/// </summary>
/// <remarks>
/// During an upgrade, the Batch service upgrades each compute node in the
/// pool. When a compute node is chosen for upgrade, any tasks running on that
/// node are removed from the node and returned to the queue to be rerun later
/// (or on a different compute node). The node will be unavailable until the
/// upgrade is complete. This operation results in temporarily reduced pool
/// capacity as nodes are taken out of service to be upgraded. Although the
/// Batch service tries to avoid upgrading all compute nodes at the same time,
/// it does not guarantee to do this (particularly on small pools); therefore,
/// the pool may be temporarily unavailable to run tasks. When this operation
/// runs, the pool state changes to upgrading. When all compute nodes have
/// finished upgrading, the pool state returns to active.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to upgrade.
/// </param>
/// <param name='targetOSVersion'>
/// The Azure Guest OS version to be installed on the virtual machines in the
/// pool.
/// </param>
/// <param name='poolUpgradeOSOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolUpgradeOSHeaders UpgradeOS(this IPoolOperations operations, string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions))
{
return ((IPoolOperations)operations).UpgradeOSAsync(poolId, targetOSVersion, poolUpgradeOSOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Upgrades the operating system of the specified pool.
/// </summary>
/// <remarks>
/// During an upgrade, the Batch service upgrades each compute node in the
/// pool. When a compute node is chosen for upgrade, any tasks running on that
/// node are removed from the node and returned to the queue to be rerun later
/// (or on a different compute node). The node will be unavailable until the
/// upgrade is complete. This operation results in temporarily reduced pool
/// capacity as nodes are taken out of service to be upgraded. Although the
/// Batch service tries to avoid upgrading all compute nodes at the same time,
/// it does not guarantee to do this (particularly on small pools); therefore,
/// the pool may be temporarily unavailable to run tasks. When this operation
/// runs, the pool state changes to upgrading. When all compute nodes have
/// finished upgrading, the pool state returns to active.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool to upgrade.
/// </param>
/// <param name='targetOSVersion'>
/// The Azure Guest OS version to be installed on the virtual machines in the
/// pool.
/// </param>
/// <param name='poolUpgradeOSOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolUpgradeOSHeaders> UpgradeOSAsync(this IPoolOperations operations, string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpgradeOSWithHttpMessagesAsync(poolId, targetOSVersion, poolUpgradeOSOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Removes compute nodes from the specified pool.
/// </summary>
/// <remarks>
/// This operation can only run when the allocation state of the pool is
/// steady. When this operation runs, the allocation state changes from steady
/// to resizing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool from which you want to remove nodes.
/// </param>
/// <param name='nodeRemoveParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolRemoveNodesOptions'>
/// Additional parameters for the operation
/// </param>
public static PoolRemoveNodesHeaders RemoveNodes(this IPoolOperations operations, string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions))
{
return ((IPoolOperations)operations).RemoveNodesAsync(poolId, nodeRemoveParameter, poolRemoveNodesOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Removes compute nodes from the specified pool.
/// </summary>
/// <remarks>
/// This operation can only run when the allocation state of the pool is
/// steady. When this operation runs, the allocation state changes from steady
/// to resizing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The ID of the pool from which you want to remove nodes.
/// </param>
/// <param name='nodeRemoveParameter'>
/// The parameters for the request.
/// </param>
/// <param name='poolRemoveNodesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PoolRemoveNodesHeaders> RemoveNodesAsync(this IPoolOperations operations, string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.RemoveNodesWithHttpMessagesAsync(poolId, nodeRemoveParameter, poolRemoveNodesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <remarks>
/// If you do not specify a $filter clause including a poolId, the response
/// includes all pools that existed in the account in the time range of the
/// returned aggregation intervals.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListUsageMetricsNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<PoolUsageMetrics> ListUsageMetricsNext(this IPoolOperations operations, string nextPageLink, PoolListUsageMetricsNextOptions poolListUsageMetricsNextOptions = default(PoolListUsageMetricsNextOptions))
{
return ((IPoolOperations)operations).ListUsageMetricsNextAsync(nextPageLink, poolListUsageMetricsNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the usage metrics, aggregated by pool across individual time
/// intervals, for the specified account.
/// </summary>
/// <remarks>
/// If you do not specify a $filter clause including a poolId, the response
/// includes all pools that existed in the account in the time range of the
/// returned aggregation intervals.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListUsageMetricsNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<PoolUsageMetrics>> ListUsageMetricsNextAsync(this IPoolOperations operations, string nextPageLink, PoolListUsageMetricsNextOptions poolListUsageMetricsNextOptions = default(PoolListUsageMetricsNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListUsageMetricsNextWithHttpMessagesAsync(nextPageLink, poolListUsageMetricsNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudPool> ListNext(this IPoolOperations operations, string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions))
{
return ((IPoolOperations)operations).ListNextAsync(nextPageLink, poolListNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the pools in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='poolListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Microsoft.Rest.Azure.IPage<CloudPool>> ListNextAsync(this IPoolOperations operations, string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, poolListNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Resources;
using System.Globalization;
using System.Windows.Forms;
using Ripper.Core.Objects;
namespace Ripper
{
using Ripper.Core.Components;
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
#if (!PGRIPPERX)
this.trayIcon.Dispose();
#endif
if (components != null)
{
components.Dispose();
}
}
tmrPageUpdate.Enabled = false;
ThreadManager.GetInstance().DismantleAllThreads();
jobsList.Clear();
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.browsFolderBtn = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.DownloadFolder = new System.Windows.Forms.TextBox();
this.mIsIndexChk = new System.Windows.Forms.CheckBox();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.mStartDownloadBtn = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.listViewJobList = new System.Windows.Forms.ListView();
this.columnHeader8 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader9 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.deleteJob = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.lvCurJob = new System.Windows.Forms.ListView();
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.pauseCurrentThreads = new System.Windows.Forms.Button();
this.stopCurrentThreads = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.tmrPageUpdate = new System.Timers.Timer();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.afterDownloadsFinishedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.doNothingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeRipperToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showLastImageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.useCliboardMonitoringToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.accountsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.StatusLblImageC = new System.Windows.Forms.StatusStrip();
this.progressBar1 = new System.Windows.Forms.ToolStripProgressBar();
this.StatusLabelInfo = new System.Windows.Forms.ToolStripStatusLabel();
this.StatusLabelImageC = new System.Windows.Forms.ToolStripStatusLabel();
this.dfolderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.GetPostsWorker = new System.ComponentModel.BackgroundWorker();
this.GetIdxsWorker = new System.ComponentModel.BackgroundWorker();
this.saveRippingQueueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tmrPageUpdate)).BeginInit();
this.menuStrip.SuspendLayout();
this.StatusLblImageC.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.browsFolderBtn);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.DownloadFolder);
this.groupBox1.Controls.Add(this.mIsIndexChk);
this.groupBox1.Controls.Add(this.comboBox1);
this.groupBox1.Controls.Add(this.mStartDownloadBtn);
this.groupBox1.Controls.Add(this.textBox1);
this.groupBox1.Location = new System.Drawing.Point(12, 32);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(360, 144);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Download Options";
this.groupBox1.UseCompatibleTextRendering = true;
//
// browsFolderBtn
//
this.browsFolderBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.browsFolderBtn.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.browsFolderBtn.Location = new System.Drawing.Point(291, 50);
this.browsFolderBtn.MaximumSize = new System.Drawing.Size(56, 20);
this.browsFolderBtn.Name = "browsFolderBtn";
this.browsFolderBtn.Size = new System.Drawing.Size(56, 20);
this.browsFolderBtn.TabIndex = 3;
this.browsFolderBtn.Text = "Browse";
this.browsFolderBtn.UseCompatibleTextRendering = true;
this.browsFolderBtn.Click += new System.EventHandler(this.BrowsFolderBtnClick);
//
// label2
//
this.label2.Location = new System.Drawing.Point(9, 47);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(106, 24);
this.label2.TabIndex = 45;
this.label2.Text = "Download Folder :";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.label2.UseCompatibleTextRendering = true;
//
// DownloadFolder
//
this.DownloadFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.DownloadFolder.Location = new System.Drawing.Point(120, 50);
this.DownloadFolder.Name = "DownloadFolder";
this.DownloadFolder.Size = new System.Drawing.Size(162, 20);
this.DownloadFolder.TabIndex = 2;
this.DownloadFolder.TextChanged += new System.EventHandler(this.DownloadFolder_TextChanged);
//
// mIsIndexChk
//
this.mIsIndexChk.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.mIsIndexChk.Location = new System.Drawing.Point(120, 76);
this.mIsIndexChk.MaximumSize = new System.Drawing.Size(200, 16);
this.mIsIndexChk.Name = "mIsIndexChk";
this.mIsIndexChk.Size = new System.Drawing.Size(200, 16);
this.mIsIndexChk.TabIndex = 4;
this.mIsIndexChk.Text = "Babe Index or Website Index?";
this.mIsIndexChk.UseCompatibleTextRendering = true;
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.IntegralHeight = false;
this.comboBox1.ItemHeight = 13;
this.comboBox1.Items.AddRange(new object[] {
"Thread ID:",
"Post ID:",
"URL:"});
this.comboBox1.Location = new System.Drawing.Point(13, 23);
this.comboBox1.MaximumSize = new System.Drawing.Size(88, 0);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(88, 21);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.ComboBox1SelectedIndexChanged);
//
// mStartDownloadBtn
//
this.mStartDownloadBtn.Image = ((System.Drawing.Image)(resources.GetObject("mStartDownloadBtn.Image")));
this.mStartDownloadBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.mStartDownloadBtn.Location = new System.Drawing.Point(122, 98);
this.mStartDownloadBtn.Name = "mStartDownloadBtn";
this.mStartDownloadBtn.Size = new System.Drawing.Size(224, 34);
this.mStartDownloadBtn.TabIndex = 5;
this.mStartDownloadBtn.Text = "Start Download";
this.mStartDownloadBtn.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.mStartDownloadBtn.UseCompatibleTextRendering = true;
this.mStartDownloadBtn.Click += new System.EventHandler(this.MStartDownloadBtnClick);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(120, 24);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(226, 20);
this.textBox1.TabIndex = 1;
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TextBox1KeyPress);
//
// listViewJobList
//
this.listViewJobList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listViewJobList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader8,
this.columnHeader9,
this.columnHeader1});
this.listViewJobList.FullRowSelect = true;
this.listViewJobList.Location = new System.Drawing.Point(6, 19);
this.listViewJobList.Name = "listViewJobList";
this.listViewJobList.Size = new System.Drawing.Size(428, 509);
this.listViewJobList.TabIndex = 6;
this.listViewJobList.UseCompatibleStateImageBehavior = false;
this.listViewJobList.View = System.Windows.Forms.View.Details;
//
// columnHeader8
//
this.columnHeader8.Text = "Thread";
this.columnHeader8.Width = 205;
//
// columnHeader9
//
this.columnHeader9.Text = "Post";
this.columnHeader9.Width = 150;
//
// columnHeader1
//
this.columnHeader1.Text = "Pics";
//
// deleteJob
//
this.deleteJob.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.deleteJob.Image = ((System.Drawing.Image)(resources.GetObject("deleteJob.Image")));
this.deleteJob.Location = new System.Drawing.Point(440, 20);
this.deleteJob.MaximumSize = new System.Drawing.Size(24, 24);
this.deleteJob.MinimumSize = new System.Drawing.Size(24, 24);
this.deleteJob.Name = "deleteJob";
this.deleteJob.Size = new System.Drawing.Size(24, 24);
this.deleteJob.TabIndex = 7;
this.deleteJob.Click += new System.EventHandler(this.DeleteJobClick);
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.lvCurJob);
this.groupBox2.Controls.Add(this.pauseCurrentThreads);
this.groupBox2.Controls.Add(this.stopCurrentThreads);
this.groupBox2.Location = new System.Drawing.Point(12, 179);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(359, 158);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Currently,";
this.groupBox2.UseCompatibleTextRendering = true;
//
// lvCurJob
//
this.lvCurJob.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lvCurJob.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader2});
this.lvCurJob.FullRowSelect = true;
this.lvCurJob.HideSelection = false;
this.lvCurJob.Location = new System.Drawing.Point(13, 19);
this.lvCurJob.MultiSelect = false;
this.lvCurJob.Name = "lvCurJob";
this.lvCurJob.ShowGroups = false;
this.lvCurJob.Size = new System.Drawing.Size(333, 97);
this.lvCurJob.TabIndex = 11;
this.lvCurJob.UseCompatibleStateImageBehavior = false;
this.lvCurJob.View = System.Windows.Forms.View.Details;
//
// columnHeader2
//
this.columnHeader2.Text = " ";
this.columnHeader2.Width = 322;
//
// pauseCurrentThreads
//
this.pauseCurrentThreads.Image = ((System.Drawing.Image)(resources.GetObject("pauseCurrentThreads.Image")));
this.pauseCurrentThreads.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.pauseCurrentThreads.Location = new System.Drawing.Point(62, 128);
this.pauseCurrentThreads.MaximumSize = new System.Drawing.Size(129, 24);
this.pauseCurrentThreads.Name = "pauseCurrentThreads";
this.pauseCurrentThreads.Size = new System.Drawing.Size(129, 24);
this.pauseCurrentThreads.TabIndex = 8;
this.pauseCurrentThreads.Text = "Pause Download(s)";
this.pauseCurrentThreads.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.pauseCurrentThreads.UseCompatibleTextRendering = true;
this.pauseCurrentThreads.UseVisualStyleBackColor = true;
this.pauseCurrentThreads.Click += new System.EventHandler(this.PauseCurrentThreadsClick);
//
// stopCurrentThreads
//
this.stopCurrentThreads.Image = ((System.Drawing.Image)(resources.GetObject("stopCurrentThreads.Image")));
this.stopCurrentThreads.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.stopCurrentThreads.Location = new System.Drawing.Point(197, 128);
this.stopCurrentThreads.MaximumSize = new System.Drawing.Size(149, 24);
this.stopCurrentThreads.Name = "stopCurrentThreads";
this.stopCurrentThreads.Size = new System.Drawing.Size(149, 24);
this.stopCurrentThreads.TabIndex = 9;
this.stopCurrentThreads.Text = "Stop/Delete Job";
this.stopCurrentThreads.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.stopCurrentThreads.UseCompatibleTextRendering = true;
this.stopCurrentThreads.Click += new System.EventHandler(this.StopCurrentThreadsClick);
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.pictureBox1.Location = new System.Drawing.Point(6, 19);
this.pictureBox1.MinimumSize = new System.Drawing.Size(345, 189);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(348, 200);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
this.pictureBox1.DoubleClick += new System.EventHandler(this.PictureBox1DoubleClick);
//
// tmrPageUpdate
//
this.tmrPageUpdate.Interval = 310D;
this.tmrPageUpdate.SynchronizingObject = this;
this.tmrPageUpdate.Elapsed += new System.Timers.ElapsedEventHandler(this.TmrPageUpdateElapsed);
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.settingsToolStripMenuItem2,
this.accountsToolStripMenuItem,
this.settingsToolStripMenuItem});
this.menuStrip.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.menuStrip.Size = new System.Drawing.Size(857, 24);
this.menuStrip.TabIndex = 7;
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveRippingQueueToolStripMenuItem,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.exitToolStripMenuItem.Text = "&Exit";
this.exitToolStripMenuItem.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.exitToolStripMenuItem.TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage;
this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolStripMenuItemClick);
//
// settingsToolStripMenuItem2
//
this.settingsToolStripMenuItem2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.optionsToolStripMenuItem,
this.afterDownloadsFinishedToolStripMenuItem,
this.showLastImageToolStripMenuItem,
this.useCliboardMonitoringToolStripMenuItem});
this.settingsToolStripMenuItem2.Name = "settingsToolStripMenuItem2";
this.settingsToolStripMenuItem2.Size = new System.Drawing.Size(61, 20);
this.settingsToolStripMenuItem2.Text = "Settings";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(209, 22);
this.optionsToolStripMenuItem.Text = "Options";
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.SettingsToolStripMenuItem1Click);
//
// afterDownloadsFinishedToolStripMenuItem
//
this.afterDownloadsFinishedToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.doNothingToolStripMenuItem,
this.closeRipperToolStripMenuItem});
this.afterDownloadsFinishedToolStripMenuItem.Name = "afterDownloadsFinishedToolStripMenuItem";
this.afterDownloadsFinishedToolStripMenuItem.Size = new System.Drawing.Size(209, 22);
this.afterDownloadsFinishedToolStripMenuItem.Text = "After Downloads Finished";
//
// doNothingToolStripMenuItem
//
this.doNothingToolStripMenuItem.CheckOnClick = true;
this.doNothingToolStripMenuItem.Name = "doNothingToolStripMenuItem";
this.doNothingToolStripMenuItem.Size = new System.Drawing.Size(140, 22);
this.doNothingToolStripMenuItem.Text = "Do Nothing";
this.doNothingToolStripMenuItem.CheckedChanged += new System.EventHandler(this.DoNothingToolStripMenuItem_CheckedChanged);
//
// closeRipperToolStripMenuItem
//
this.closeRipperToolStripMenuItem.CheckOnClick = true;
this.closeRipperToolStripMenuItem.Name = "closeRipperToolStripMenuItem";
this.closeRipperToolStripMenuItem.Size = new System.Drawing.Size(140, 22);
this.closeRipperToolStripMenuItem.Text = "Close Ripper";
this.closeRipperToolStripMenuItem.CheckedChanged += new System.EventHandler(this.CloseRipperToolStripMenuItem_CheckedChanged);
//
// showLastImageToolStripMenuItem
//
this.showLastImageToolStripMenuItem.CheckOnClick = true;
this.showLastImageToolStripMenuItem.Name = "showLastImageToolStripMenuItem";
this.showLastImageToolStripMenuItem.Size = new System.Drawing.Size(209, 22);
this.showLastImageToolStripMenuItem.Text = "Show Last Image";
this.showLastImageToolStripMenuItem.CheckedChanged += new System.EventHandler(this.ShowLastImageToolStripMenuItem_CheckedChanged);
//
// useCliboardMonitoringToolStripMenuItem
//
this.useCliboardMonitoringToolStripMenuItem.Name = "useCliboardMonitoringToolStripMenuItem";
this.useCliboardMonitoringToolStripMenuItem.Size = new System.Drawing.Size(209, 22);
this.useCliboardMonitoringToolStripMenuItem.Text = "Use Cliboard Monitoring";
this.useCliboardMonitoringToolStripMenuItem.CheckedChanged += new System.EventHandler(this.UseCliboardMonitoringToolStripMenuItem_CheckedChanged);
//
// accountsToolStripMenuItem
//
this.accountsToolStripMenuItem.Name = "accountsToolStripMenuItem";
this.accountsToolStripMenuItem.Size = new System.Drawing.Size(69, 20);
this.accountsToolStripMenuItem.Text = "Accounts";
//
// settingsToolStripMenuItem
//
this.settingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.helpToolStripMenuItem});
this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem";
this.settingsToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.settingsToolStripMenuItem.Text = "&Help";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.helpToolStripMenuItem.Text = "&About";
this.helpToolStripMenuItem.Click += new System.EventHandler(this.HelpToolStripMenuItemClick);
//
// StatusLblImageC
//
this.StatusLblImageC.BackColor = System.Drawing.SystemColors.Control;
this.StatusLblImageC.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.progressBar1,
this.StatusLabelInfo,
this.StatusLabelImageC});
this.StatusLblImageC.Location = new System.Drawing.Point(0, 571);
this.StatusLblImageC.Name = "StatusLblImageC";
this.StatusLblImageC.Size = new System.Drawing.Size(857, 23);
this.StatusLblImageC.TabIndex = 8;
this.StatusLblImageC.Text = "statusStrip1";
//
// progressBar1
//
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(364, 17);
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
//
// StatusLabelInfo
//
this.StatusLabelInfo.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
this.StatusLabelInfo.ForeColor = System.Drawing.Color.Red;
this.StatusLabelInfo.Name = "StatusLabelInfo";
this.StatusLabelInfo.Size = new System.Drawing.Size(13, 18);
this.StatusLabelInfo.Text = " ";
//
// StatusLabelImageC
//
this.StatusLabelImageC.Name = "StatusLabelImageC";
this.StatusLabelImageC.Size = new System.Drawing.Size(13, 18);
this.StatusLabelImageC.Text = " ";
this.StatusLabelImageC.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// dfolderBrowserDialog
//
this.dfolderBrowserDialog.ShowNewFolderButton = false;
//
// groupBox4
//
this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox4.Controls.Add(this.pictureBox1);
this.groupBox4.Location = new System.Drawing.Point(12, 343);
this.groupBox4.MinimumSize = new System.Drawing.Size(357, 214);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(360, 225);
this.groupBox4.TabIndex = 11;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Last Picture Downloaded..";
//
// groupBox5
//
this.groupBox5.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox5.Controls.Add(this.listViewJobList);
this.groupBox5.Controls.Add(this.deleteJob);
this.groupBox5.Location = new System.Drawing.Point(378, 32);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(471, 536);
this.groupBox5.TabIndex = 12;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Ripping Queue:";
//
// GetPostsWorker
//
this.GetPostsWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.GetPostsWorkerDoWork);
this.GetPostsWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.GetPostsWorkerCompleted);
//
// GetIdxsWorker
//
this.GetIdxsWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.GetIdxsWorkerDoWork);
this.GetIdxsWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.GetIdxsWorkerCompleted);
//
// saveRippingQueueToolStripMenuItem
//
this.saveRippingQueueToolStripMenuItem.Name = "saveRippingQueueToolStripMenuItem";
this.saveRippingQueueToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.saveRippingQueueToolStripMenuItem.Text = "Save Ripping Queue";
this.saveRippingQueueToolStripMenuItem.Click += new System.EventHandler(this.SaveRippingQueueToolStripMenuItem_Click);
//
// MainForm
//
this.AccessibleDescription = "i";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(857, 594);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.StatusLblImageC);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip;
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(865, 622);
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "PG-Ripper 2.0.0 [Logged in as: \"\"]";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainFormFormClosing);
this.Load += new System.EventHandler(this.MainFormLoad);
this.Resize += new System.EventHandler(this.MainFormResize);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tmrPageUpdate)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.StatusLblImageC.ResumeLayout(false);
this.StatusLblImageC.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private string mInvalidDestinationMsg;
private string mIncorrectUrlMsg;
private string mNoThreadMsg;
private string mNoPostMsg;
private string mAlreadyQueuedMsg;
private string mTNumericMsg;
#if (PGRIPPER)
private NotifyIcon trayIcon;
private ContextMenu trayMenu;
#elif (PGRIPPERX)
#else
private NotifyIcon trayIcon;
private ContextMenu trayMenu;
#endif
private DateTime LastWorkingTime;
private GroupBox groupBox1;
private TextBox textBox1;
private Button deleteJob;
private GroupBox groupBox2;
private Button mStartDownloadBtn;
private List<JobInfo> jobsList = null;
private System.Timers.Timer tmrPageUpdate;
private JobInfo currentJob = null;
private List<ImageInfo> mImagesList = null;
private string sLastPic = string.Empty;
private CacheController mrefCC = null;
private ThreadManager mrefTM = null;
public bool cameThroughCorrectLogin = false;
private ComboBox comboBox1;
private Button stopCurrentThreads;
//private string g_sComposedURI = string.Empty;
private CheckBox mIsIndexChk;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem exitToolStripMenuItem;
private ToolStripMenuItem settingsToolStripMenuItem;
private ToolStripMenuItem helpToolStripMenuItem;
private ListView listViewJobList;
private ColumnHeader columnHeader8;
private ColumnHeader columnHeader9;
private StatusStrip StatusLblImageC;
private ToolStripProgressBar progressBar1;
private Button pauseCurrentThreads;
private ToolStripStatusLabel StatusLabelInfo;
private ColumnHeader columnHeader1;
private Button browsFolderBtn;
private Label label2;
private TextBox DownloadFolder;
private FolderBrowserDialog dfolderBrowserDialog;
private PictureBox pictureBox1;
private GroupBox groupBox4;
private GroupBox groupBox5;
private ToolStripStatusLabel StatusLabelImageC;
private ListView lvCurJob;
private ColumnHeader columnHeader2;
private System.ComponentModel.BackgroundWorker GetPostsWorker;
private System.ComponentModel.BackgroundWorker GetIdxsWorker;
private ToolStripMenuItem accountsToolStripMenuItem;
private ToolStripMenuItem settingsToolStripMenuItem2;
private ToolStripMenuItem optionsToolStripMenuItem;
private ToolStripMenuItem showLastImageToolStripMenuItem;
private ToolStripMenuItem useCliboardMonitoringToolStripMenuItem;
private ToolStripMenuItem afterDownloadsFinishedToolStripMenuItem;
private ToolStripMenuItem doNothingToolStripMenuItem;
private ToolStripMenuItem closeRipperToolStripMenuItem;
private ToolStripMenuItem saveRippingQueueToolStripMenuItem;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
/*
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
This is sample code and is freely distributable.
*/
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
namespace ImageManipulation
{
/// <summary>
/// Quantize using an Octree
/// </summary>
public unsafe class OctreeQuantizer : Quantizer
{
/// <summary>
/// Construct the octree quantizer
/// </summary>
/// <remarks>
/// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
/// the second pass quantizes a color based on the nodes in the tree
/// </remarks>
/// <param name="maxColors">The maximum number of colors to return</param>
/// <param name="maxColorBits">The number of significant bits</param>
public OctreeQuantizer(int maxColors, int maxColorBits) : base(false)
{
if (maxColors > 255)
throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256");
if ((maxColorBits < 1) | (maxColorBits > 8))
throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8");
// Construct the octree
_octree = new Octree(maxColorBits);
_maxColors = maxColors;
}
/// <summary>
/// Process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected override void InitialQuantizePixel(Color32* pixel)
{
// Add the color to the octree
_octree.AddColor(pixel);
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <returns>The quantized value</returns>
protected override byte QuantizePixel(Color32* pixel)
{
byte paletteIndex = (byte)_maxColors; // The color at [_maxColors] is set to transparent
// Get the palette index if this non-transparent
if (pixel->Alpha > 0)
paletteIndex = (byte)_octree.GetPaletteIndex(pixel);
return paletteIndex;
}
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <param name="original">Any old palette, this is overrwritten</param>
/// <returns>The new color palette</returns>
protected override ColorPalette GetPalette(ColorPalette original)
{
// First off convert the octree to _maxColors colors
ArrayList palette = _octree.Palletize(_maxColors - 1);
// Then convert the palette based on those colors
for (int index = 0; index < palette.Count; index++)
original.Entries[index] = (Color)palette[index];
// Add the transparent color
original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0);
return original;
}
/// <summary>
/// Stores the tree
/// </summary>
private Octree _octree;
/// <summary>
/// Maximum allowed color depth
/// </summary>
private int _maxColors;
/// <summary>
/// Class which does the actual quantization
/// </summary>
private class Octree
{
/// <summary>
/// Construct the octree
/// </summary>
/// <param name="maxColorBits">The maximum number of significant bits in the image</param>
public Octree(int maxColorBits)
{
_maxColorBits = maxColorBits;
_leafCount = 0;
_reducibleNodes = new OctreeNode[9];
_root = new OctreeNode(0, _maxColorBits, this);
_previousColor = 0;
_previousNode = null;
}
/// <summary>
/// Add a given color value to the octree
/// </summary>
/// <param name="pixel"></param>
public void AddColor(Color32* pixel)
{
// Check if this request is for the same color as the last
if (_previousColor == pixel->ARGB)
{
// If so, check if I have a previous node setup. This will only ocurr if the first color in the image
// happens to be black, with an alpha component of zero.
if (null == _previousNode)
{
_previousColor = pixel->ARGB;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
else
// Just update the previous node
_previousNode.Increment(pixel);
}
else
{
_previousColor = pixel->ARGB;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
}
/// <summary>
/// Reduce the depth of the tree
/// </summary>
public void Reduce()
{
int index;
// Find the deepest level containing at least one reducible node
for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--) ;
// Reduce the node most recently added to the list at level 'index'
OctreeNode node = _reducibleNodes[index];
_reducibleNodes[index] = node.NextReducible;
// Decrement the leaf count after reducing the node
_leafCount -= node.Reduce();
// And just in case I've reduced the last color to be added, and the next color to
// be added is the same, invalidate the previousNode...
_previousNode = null;
}
/// <summary>
/// Get/Set the number of leaves in the tree
/// </summary>
public int Leaves
{
get { return _leafCount; }
set { _leafCount = value; }
}
/// <summary>
/// Return the array of reducible nodes
/// </summary>
protected OctreeNode[] ReducibleNodes
{
get { return _reducibleNodes; }
}
/// <summary>
/// Keep track of the previous node that was quantized
/// </summary>
/// <param name="node">The node last quantized</param>
protected void TrackPrevious(OctreeNode node)
{
_previousNode = node;
}
/// <summary>
/// Convert the nodes in the octree to a palette with a maximum of colorCount colors
/// </summary>
/// <param name="colorCount">The maximum number of colors</param>
/// <returns>An arraylist with the palettized colors</returns>
public ArrayList Palletize(int colorCount)
{
while (Leaves > colorCount)
Reduce();
// Now palettize the nodes
ArrayList palette = new ArrayList(Leaves);
int paletteIndex = 0;
_root.ConstructPalette(palette, ref paletteIndex);
// And return the palette
return palette;
}
/// <summary>
/// Get the palette index for the passed color
/// </summary>
/// <param name="pixel"></param>
/// <returns></returns>
public int GetPaletteIndex(Color32* pixel)
{
return _root.GetPaletteIndex(pixel, 0);
}
/// <summary>
/// Mask used when getting the appropriate pixels for a given node
/// </summary>
private static int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
/// <summary>
/// The root of the octree
/// </summary>
private OctreeNode _root;
/// <summary>
/// Number of leaves in the tree
/// </summary>
private int _leafCount;
/// <summary>
/// Array of reducible nodes
/// </summary>
private OctreeNode[] _reducibleNodes;
/// <summary>
/// Maximum number of significant bits in the image
/// </summary>
private int _maxColorBits;
/// <summary>
/// Store the last node quantized
/// </summary>
private OctreeNode _previousNode;
/// <summary>
/// Cache the previous color quantized
/// </summary>
private int _previousColor;
/// <summary>
/// Class which encapsulates each node in the tree
/// </summary>
protected class OctreeNode
{
/// <summary>
/// Construct the node
/// </summary>
/// <param name="level">The level in the tree = 0 - 7</param>
/// <param name="colorBits">The number of significant color bits in the image</param>
/// <param name="octree">The tree to which this node belongs</param>
public OctreeNode(int level, int colorBits, Octree octree)
{
// Construct the new node
_leaf = (level == colorBits);
_red = _green = _blue = 0;
_pixelCount = 0;
// If a leaf, increment the leaf count
if (_leaf)
{
octree.Leaves++;
_nextReducible = null;
_children = null;
}
else
{
// Otherwise add this to the reducible nodes
_nextReducible = octree.ReducibleNodes[level];
octree.ReducibleNodes[level] = this;
_children = new OctreeNode[8];
}
}
/// <summary>
/// Add a color into the tree
/// </summary>
/// <param name="pixel">The color</param>
/// <param name="colorBits">The number of significant color bits</param>
/// <param name="level">The level in the tree</param>
/// <param name="octree">The tree to which this node belongs</param>
public void AddColor(Color32* pixel, int colorBits, int level, Octree octree)
{
// Update the color information if this is a leaf
if (_leaf)
{
Increment(pixel);
// Setup the previous node
octree.TrackPrevious(this);
}
else
{
// Go to the next level down in the tree
int shift = 7 - level;
int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
((pixel->Green & mask[level]) >> (shift - 1)) |
((pixel->Blue & mask[level]) >> (shift));
OctreeNode child = _children[index];
if (null == child)
{
// Create a new child node & store in the array
child = new OctreeNode(level + 1, colorBits, octree);
_children[index] = child;
}
// Add the color to the child node
child.AddColor(pixel, colorBits, level + 1, octree);
}
}
/// <summary>
/// Get/Set the next reducible node
/// </summary>
public OctreeNode NextReducible
{
get { return _nextReducible; }
set { _nextReducible = value; }
}
/// <summary>
/// Return the child nodes
/// </summary>
public OctreeNode[] Children
{
get { return _children; }
}
/// <summary>
/// Reduce this node by removing all of its children
/// </summary>
/// <returns>The number of leaves removed</returns>
public int Reduce()
{
_red = _green = _blue = 0;
int children = 0;
// Loop through all children and add their information to this node
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
{
_red += _children[index]._red;
_green += _children[index]._green;
_blue += _children[index]._blue;
_pixelCount += _children[index]._pixelCount;
++children;
_children[index] = null;
}
}
// Now change this to a leaf node
_leaf = true;
// Return the number of nodes to decrement the leaf count by
return (children - 1);
}
/// <summary>
/// Traverse the tree, building up the color palette
/// </summary>
/// <param name="palette">The palette</param>
/// <param name="paletteIndex">The current palette index</param>
public void ConstructPalette(ArrayList palette, ref int paletteIndex)
{
if (_leaf)
{
// Consume the next palette index
_paletteIndex = paletteIndex++;
// And set the color of the palette entry
palette.Add(Color.FromArgb(_red / _pixelCount, _green / _pixelCount, _blue / _pixelCount));
}
else
{
// Loop through children looking for leaves
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
_children[index].ConstructPalette(palette, ref paletteIndex);
}
}
}
/// <summary>
/// Return the palette index for the passed color
/// </summary>
public int GetPaletteIndex(Color32* pixel, int level)
{
int paletteIndex = _paletteIndex;
if (!_leaf)
{
int shift = 7 - level;
int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
((pixel->Green & mask[level]) >> (shift - 1)) |
((pixel->Blue & mask[level]) >> (shift));
if (null != _children[index])
paletteIndex = _children[index].GetPaletteIndex(pixel, level + 1);
else
throw new Exception("Didn't expect this!");
}
return paletteIndex;
}
/// <summary>
/// Increment the pixel count and add to the color information
/// </summary>
public void Increment(Color32* pixel)
{
_pixelCount++;
_red += pixel->Red;
_green += pixel->Green;
_blue += pixel->Blue;
}
/// <summary>
/// Flag indicating that this is a leaf node
/// </summary>
private bool _leaf;
/// <summary>
/// Number of pixels in this node
/// </summary>
private int _pixelCount;
/// <summary>
/// Red component
/// </summary>
private int _red;
/// <summary>
/// Green Component
/// </summary>
private int _green;
/// <summary>
/// Blue component
/// </summary>
private int _blue;
/// <summary>
/// Pointers to any child nodes
/// </summary>
private OctreeNode[] _children;
/// <summary>
/// Pointer to next reducible node
/// </summary>
private OctreeNode _nextReducible;
/// <summary>
/// The index of this node in the palette
/// </summary>
private int _paletteIndex;
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using C1.Win.C1Input;
using C1.Win.C1List;
using PCSComMaterials.Inventory.BO;
using PCSComMaterials.Inventory.DS;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSMaterials.Inventory
{
/// <summary>
/// Summary description for StockTakingPeriod.
/// </summary>
public class StockTakingPeriod : Form
{
private C1Combo cboCCN;
private Label lblCCN;
private Button btnAdd;
private Button btnSave;
private Button btnClose;
private Button btnHelp;
private C1DateEdit dtmToDate;
private Label lblToDate;
private C1DateEdit dtmFromDate;
private Label lblFromDate;
private TextBox txtStockTakingPeriod;
private Button btnStockTakingPeriod;
private Label lblStockTakingPeriod;
private Button btnDelete;
private Button btnEdit;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
const string THIS = "PCSMaterials.Inventory.StockTakingPeriod";
UtilsBO boUtil = new UtilsBO();
EnumAction formMode;
private Button btnUpdate;
private CheckBox chkClose;
private bool blnHasError = false;
private bool IsUpdateInventory = false;
private System.Windows.Forms.Button btnUpdateDiff;
private Button CloseStockButton;
private Button UpdateBeginButton;
Thread thrProcess = null;
public StockTakingPeriod()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StockTakingPeriod));
this.cboCCN = new C1.Win.C1List.C1Combo();
this.lblCCN = new System.Windows.Forms.Label();
this.dtmToDate = new C1.Win.C1Input.C1DateEdit();
this.lblToDate = new System.Windows.Forms.Label();
this.dtmFromDate = new C1.Win.C1Input.C1DateEdit();
this.lblFromDate = new System.Windows.Forms.Label();
this.txtStockTakingPeriod = new System.Windows.Forms.TextBox();
this.btnStockTakingPeriod = new System.Windows.Forms.Button();
this.lblStockTakingPeriod = new System.Windows.Forms.Label();
this.btnAdd = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnEdit = new System.Windows.Forms.Button();
this.btnUpdate = new System.Windows.Forms.Button();
this.chkClose = new System.Windows.Forms.CheckBox();
this.btnUpdateDiff = new System.Windows.Forms.Button();
this.CloseStockButton = new System.Windows.Forms.Button();
this.UpdateBeginButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmToDate)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromDate)).BeginInit();
this.SuspendLayout();
//
// cboCCN
//
this.cboCCN.AddItemSeparator = ';';
this.cboCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cboCCN.Caption = "";
this.cboCCN.CaptionHeight = 17;
this.cboCCN.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal;
this.cboCCN.ColumnCaptionHeight = 17;
this.cboCCN.ColumnFooterHeight = 17;
this.cboCCN.ComboStyle = C1.Win.C1List.ComboStyleEnum.DropdownList;
this.cboCCN.ContentHeight = 15;
this.cboCCN.DeadAreaBackColor = System.Drawing.Color.Empty;
this.cboCCN.EditorBackColor = System.Drawing.SystemColors.Window;
this.cboCCN.EditorFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboCCN.EditorForeColor = System.Drawing.SystemColors.WindowText;
this.cboCCN.EditorHeight = 15;
this.cboCCN.Images.Add(((System.Drawing.Image)(resources.GetObject("cboCCN.Images"))));
this.cboCCN.ItemHeight = 15;
this.cboCCN.Location = new System.Drawing.Point(378, 8);
this.cboCCN.MatchEntryTimeout = ((long)(2000));
this.cboCCN.MaxDropDownItems = ((short)(5));
this.cboCCN.MaxLength = 32767;
this.cboCCN.MouseCursor = System.Windows.Forms.Cursors.Default;
this.cboCCN.Name = "cboCCN";
this.cboCCN.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.cboCCN.Size = new System.Drawing.Size(80, 21);
this.cboCCN.TabIndex = 1;
this.cboCCN.PropBag = resources.GetString("cboCCN.PropBag");
//
// lblCCN
//
this.lblCCN.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblCCN.ForeColor = System.Drawing.Color.Maroon;
this.lblCCN.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCCN.Location = new System.Drawing.Point(346, 8);
this.lblCCN.Name = "lblCCN";
this.lblCCN.Size = new System.Drawing.Size(30, 20);
this.lblCCN.TabIndex = 0;
this.lblCCN.Text = "CCN";
this.lblCCN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// dtmToDate
//
//
//
//
this.dtmToDate.Calendar.DayNameLength = 1;
this.dtmToDate.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.dtmToDate.Calendar.MaxDate = new System.DateTime(2100, 12, 31, 0, 0, 0, 0);
this.dtmToDate.Calendar.ShowClearButton = false;
this.dtmToDate.CustomFormat = "dd-MM-yyyy HH:mm";
this.dtmToDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
this.dtmToDate.Location = new System.Drawing.Point(120, 56);
this.dtmToDate.Name = "dtmToDate";
this.dtmToDate.PostValidation.Intervals.AddRange(new C1.Win.C1Input.ValueInterval[] {
new C1.Win.C1Input.ValueInterval(new System.DateTime(1753, 1, 1, 0, 0, 0, 0), new System.DateTime(2100, 12, 31, 12, 0, 0, 0), true, true)});
this.dtmToDate.Size = new System.Drawing.Size(122, 20);
this.dtmToDate.TabIndex = 8;
this.dtmToDate.Tag = null;
this.dtmToDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmToDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
//
// lblToDate
//
this.lblToDate.ForeColor = System.Drawing.Color.Maroon;
this.lblToDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblToDate.Location = new System.Drawing.Point(8, 56);
this.lblToDate.Name = "lblToDate";
this.lblToDate.Size = new System.Drawing.Size(84, 20);
this.lblToDate.TabIndex = 7;
this.lblToDate.Text = "To date";
this.lblToDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// dtmFromDate
//
//
//
//
this.dtmFromDate.Calendar.DayNameLength = 1;
this.dtmFromDate.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.dtmFromDate.Calendar.MaxDate = new System.DateTime(2100, 12, 31, 0, 0, 0, 0);
this.dtmFromDate.Calendar.ShowClearButton = false;
this.dtmFromDate.CustomFormat = "dd-MM-yyyy HH:mm";
this.dtmFromDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
this.dtmFromDate.Location = new System.Drawing.Point(120, 32);
this.dtmFromDate.Name = "dtmFromDate";
this.dtmFromDate.PostValidation.Intervals.AddRange(new C1.Win.C1Input.ValueInterval[] {
new C1.Win.C1Input.ValueInterval(new System.DateTime(1753, 1, 1, 0, 0, 0, 0), new System.DateTime(2100, 12, 31, 12, 0, 0, 0), true, true)});
this.dtmFromDate.Size = new System.Drawing.Size(122, 20);
this.dtmFromDate.TabIndex = 6;
this.dtmFromDate.Tag = null;
this.dtmFromDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmFromDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
//
// lblFromDate
//
this.lblFromDate.ForeColor = System.Drawing.Color.Maroon;
this.lblFromDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblFromDate.Location = new System.Drawing.Point(8, 32);
this.lblFromDate.Name = "lblFromDate";
this.lblFromDate.Size = new System.Drawing.Size(84, 20);
this.lblFromDate.TabIndex = 5;
this.lblFromDate.Text = "From date";
this.lblFromDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txtStockTakingPeriod
//
this.txtStockTakingPeriod.Location = new System.Drawing.Point(120, 8);
this.txtStockTakingPeriod.Name = "txtStockTakingPeriod";
this.txtStockTakingPeriod.Size = new System.Drawing.Size(140, 20);
this.txtStockTakingPeriod.TabIndex = 3;
this.txtStockTakingPeriod.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtStockTakingPeriod_KeyDown);
this.txtStockTakingPeriod.Validating += new System.ComponentModel.CancelEventHandler(this.txtStockTakingPeriod_Validating);
//
// btnStockTakingPeriod
//
this.btnStockTakingPeriod.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnStockTakingPeriod.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnStockTakingPeriod.Location = new System.Drawing.Point(261, 8);
this.btnStockTakingPeriod.Name = "btnStockTakingPeriod";
this.btnStockTakingPeriod.Size = new System.Drawing.Size(22, 20);
this.btnStockTakingPeriod.TabIndex = 4;
this.btnStockTakingPeriod.Text = "...";
this.btnStockTakingPeriod.Click += new System.EventHandler(this.btnStockTakingPeriod_Click);
//
// lblStockTakingPeriod
//
this.lblStockTakingPeriod.ForeColor = System.Drawing.Color.Maroon;
this.lblStockTakingPeriod.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblStockTakingPeriod.Location = new System.Drawing.Point(8, 8);
this.lblStockTakingPeriod.Name = "lblStockTakingPeriod";
this.lblStockTakingPeriod.Size = new System.Drawing.Size(104, 20);
this.lblStockTakingPeriod.TabIndex = 2;
this.lblStockTakingPeriod.Text = "Stock taking period";
this.lblStockTakingPeriod.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnAdd
//
this.btnAdd.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnAdd.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnAdd.Location = new System.Drawing.Point(8, 120);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(60, 23);
this.btnAdd.TabIndex = 13;
this.btnAdd.Text = "&Add";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnSave
//
this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnSave.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSave.Location = new System.Drawing.Point(68, 120);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(60, 23);
this.btnSave.TabIndex = 14;
this.btnSave.Text = "&Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnClose
//
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(398, 120);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 23);
this.btnClose.TabIndex = 18;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnHelp
//
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(334, 120);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(60, 23);
this.btnHelp.TabIndex = 17;
this.btnHelp.Text = "&Help";
//
// btnDelete
//
this.btnDelete.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnDelete.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnDelete.Location = new System.Drawing.Point(188, 120);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(60, 23);
this.btnDelete.TabIndex = 16;
this.btnDelete.Text = "&Delete";
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnEdit
//
this.btnEdit.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnEdit.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnEdit.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnEdit.Location = new System.Drawing.Point(128, 120);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(60, 23);
this.btnEdit.TabIndex = 15;
this.btnEdit.Text = "&Edit";
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// btnUpdate
//
this.btnUpdate.Location = new System.Drawing.Point(8, 88);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Size = new System.Drawing.Size(120, 23);
this.btnUpdate.TabIndex = 10;
this.btnUpdate.Text = "&Update Inventory";
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
//
// chkClose
//
this.chkClose.Location = new System.Drawing.Point(264, 56);
this.chkClose.Name = "chkClose";
this.chkClose.Size = new System.Drawing.Size(56, 16);
this.chkClose.TabIndex = 9;
this.chkClose.Text = "Close";
//
// btnUpdateDiff
//
this.btnUpdateDiff.Location = new System.Drawing.Point(130, 88);
this.btnUpdateDiff.Name = "btnUpdateDiff";
this.btnUpdateDiff.Size = new System.Drawing.Size(109, 23);
this.btnUpdateDiff.TabIndex = 11;
this.btnUpdateDiff.Text = "Update D&ifferent";
this.btnUpdateDiff.Click += new System.EventHandler(this.btnUpdateDiff_Click);
//
// CloseStockButton
//
this.CloseStockButton.Location = new System.Drawing.Point(338, 88);
this.CloseStockButton.Name = "CloseStockButton";
this.CloseStockButton.Size = new System.Drawing.Size(120, 23);
this.CloseStockButton.TabIndex = 12;
this.CloseStockButton.Text = "Close Stock &Taking";
this.CloseStockButton.Click += new System.EventHandler(this.CloseStockButton_Click);
//
// UpdateBeginButton
//
this.UpdateBeginButton.Location = new System.Drawing.Point(245, 88);
this.UpdateBeginButton.Name = "UpdateBeginButton";
this.UpdateBeginButton.Size = new System.Drawing.Size(87, 23);
this.UpdateBeginButton.TabIndex = 11;
this.UpdateBeginButton.Text = "Update &Begin";
this.UpdateBeginButton.Click += new System.EventHandler(this.UpdateBeginButton_Click);
//
// StockTakingPeriod
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(466, 150);
this.Controls.Add(this.UpdateBeginButton);
this.Controls.Add(this.btnUpdateDiff);
this.Controls.Add(this.chkClose);
this.Controls.Add(this.CloseStockButton);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnEdit);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.cboCCN);
this.Controls.Add(this.lblCCN);
this.Controls.Add(this.dtmToDate);
this.Controls.Add(this.lblToDate);
this.Controls.Add(this.dtmFromDate);
this.Controls.Add(this.lblFromDate);
this.Controls.Add(this.txtStockTakingPeriod);
this.Controls.Add(this.btnStockTakingPeriod);
this.Controls.Add(this.lblStockTakingPeriod);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "StockTakingPeriod";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Stock Taking Period";
this.Closing += new System.ComponentModel.CancelEventHandler(this.StockTakingPeriod_Closing);
this.Load += new System.EventHandler(this.StockTakingPeriod_Load);
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmToDate)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromDate)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// StockTakingPeriod_Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void StockTakingPeriod_Load(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".StockTakingPeriod_Load()";
try
{
//Set authorization for user
Security objSecurity = new Security();
this.Name = THIS;
if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW ,MessageBoxIcon.Warning);
return;
}
// Load combo box
DataSet dstCCN = boUtil.ListCCN();
cboCCN.DataSource = dstCCN.Tables[MST_CCNTable.TABLE_NAME];
cboCCN.DisplayMember = MST_CCNTable.CODE_FLD;
cboCCN.ValueMember = MST_CCNTable.CCNID_FLD;
FormControlComponents.PutDataIntoC1ComboBox(cboCCN, dstCCN.Tables[MST_CCNTable.TABLE_NAME],MST_CCNTable.CODE_FLD,MST_CCNTable.CCNID_FLD,MST_CCNTable.TABLE_NAME);
if (SystemProperty.CCNID != 0)
{
cboCCN.SelectedValue = SystemProperty.CCNID;
}
dtmFromDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
dtmToDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
//switch form mode
formMode = EnumAction.Default;
SwitchFormMode();
btnUpdate.Enabled = false;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// SwitchFormMode
/// </summary>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void SwitchFormMode()
{
switch (formMode)
{
case EnumAction.Default:
btnStockTakingPeriod.Enabled = true;
txtStockTakingPeriod.Enabled = true;
dtmFromDate.Enabled = false;
dtmToDate.Enabled = false;
btnAdd.Enabled = true;
btnSave.Enabled = false;
btnEdit.Enabled = false;
btnDelete.Enabled = false;
chkClose.Enabled = false;
if (txtStockTakingPeriod.Tag != null)
{
btnUpdate.Enabled = true;
btnUpdateDiff.Enabled = true;
}
else
{
btnUpdate.Enabled = false;
btnUpdateDiff.Enabled = false;
}
break;
case EnumAction.Add:
btnStockTakingPeriod.Enabled = false;
txtStockTakingPeriod.Enabled = true;
dtmFromDate.Enabled = true;
dtmToDate.Enabled = true;
btnAdd.Enabled = false;
btnSave.Enabled = true;
btnEdit.Enabled = false;
btnDelete.Enabled = false;
btnUpdate.Enabled = false;
btnUpdateDiff.Enabled = false;
chkClose.Enabled = true;
break;
case EnumAction.Edit:
btnStockTakingPeriod.Enabled = false;
txtStockTakingPeriod.Enabled = true;
dtmFromDate.Enabled = true;
dtmToDate.Enabled = true;
btnAdd.Enabled = false;
btnSave.Enabled = true;
btnEdit.Enabled = false;
btnDelete.Enabled = false;
chkClose.Enabled = true;
btnUpdate.Enabled = false;
btnUpdateDiff.Enabled = false;
break;
}
}
/// <summary>
/// Clear all control in form
/// </summary>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void ClearForm()
{
txtStockTakingPeriod.Text = string.Empty;
txtStockTakingPeriod.Tag = null;
dtmFromDate.Value = null;
dtmToDate.Value = null;
chkClose.Checked = false;
}
/// <summary>
/// btnAdd_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void btnAdd_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnAdd_Click()";
try
{
//Clear form
ClearForm();
//Switch form Mode
formMode = EnumAction.Add;
SwitchFormMode();
txtStockTakingPeriod.Focus();
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Validating Data before saving
/// </summary>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private bool IsValidatingData()
{
if (FormControlComponents.CheckMandatory(txtStockTakingPeriod))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
txtStockTakingPeriod.Focus();
return false;
}
if (FormControlComponents.CheckMandatory(dtmFromDate))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
dtmFromDate.Focus();
return false;
}
if (FormControlComponents.CheckMandatory(dtmToDate))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
dtmToDate.Focus();
return false;
}
if (dtmFromDate.Value != DBNull.Value && dtmToDate.Value != DBNull.Value)
{
if ((DateTime)dtmFromDate.Value >= (DateTime) dtmToDate.Value)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_MP_PERIODDATE, MessageBoxIcon.Warning);
dtmToDate.Focus();
return false;
}
}
return true;
}
/// <summary>
/// btnSave_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void btnSave_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSave_Click()";
try
{
blnHasError = true;
//Validating data
if (IsValidatingData())
{
//Controls to VO
IV_StockTakingPeriodVO voStockTakingPeriod = new IV_StockTakingPeriodVO();
voStockTakingPeriod.CCNID = int.Parse(cboCCN.SelectedValue.ToString());
voStockTakingPeriod.Description = txtStockTakingPeriod.Text;
voStockTakingPeriod.FromDate = (DateTime)dtmFromDate.Value;
voStockTakingPeriod.ToDate = (DateTime)dtmToDate.Value;
voStockTakingPeriod.Closed = chkClose.Checked;
//add to database
StockTakingPeriodBO boStockTakingPeriod = new StockTakingPeriodBO();
switch (formMode)
{
case EnumAction.Add:
txtStockTakingPeriod.Tag = voStockTakingPeriod.StockTakingPeriodID = boStockTakingPeriod.AddAndReturnID(voStockTakingPeriod);
break;
case EnumAction.Edit:
//add ID
voStockTakingPeriod.StockTakingPeriodID = int.Parse(txtStockTakingPeriod.Tag.ToString());
boStockTakingPeriod.Update(voStockTakingPeriod);
break;
}
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
btnSave.Enabled = false;
//ClearForm();
formMode = EnumAction.Default;
blnHasError = false;
SwitchFormMode();
btnAdd.Focus();
btnAdd.Enabled = true;
btnEdit.Enabled = true;
btnDelete.Enabled = true;
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// btnEdit_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void btnEdit_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnEdit_Click()";
try
{
//Switch form Mode
formMode = EnumAction.Edit;
SwitchFormMode();
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// fill data to all controls by StockTakingPeriodID
/// </summary>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void FillDataToControls(DataRowView pdrwResult)
{
dtmFromDate.Value = (DateTime)pdrwResult[IV_StockTakingPeriodTable.FROMDATE_FLD];
dtmToDate.Value = (DateTime)pdrwResult[IV_StockTakingPeriodTable.TODATE_FLD];
}
/// <summary>
/// btnStockTakingPeriod_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void btnStockTakingPeriod_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnStockTakingPeriod_Click()";
try
{
DataRowView drwResult = null;
drwResult = FormControlComponents.OpenSearchForm(IV_StockTakingPeriodTable.TABLE_NAME, IV_StockTakingPeriodTable.DESCRIPTION_FLD, txtStockTakingPeriod.Text.Trim(), null, true);
if (drwResult != null)
{
btnEdit.Enabled = true;
btnDelete.Enabled = true;
btnUpdate.Enabled = true;
btnUpdateDiff.Enabled = true;
txtStockTakingPeriod.Text = drwResult[IV_StockTakingPeriodTable.DESCRIPTION_FLD].ToString();
txtStockTakingPeriod.Tag = drwResult[IV_StockTakingPeriodTable.STOCKTAKINGPERIODID_FLD];
chkClose.Checked = (bool) drwResult[IV_StockTakingPeriodTable.CLOSED_FLD];
FillDataToControls(drwResult);
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// txtStockTakingPeriod_Validating
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void txtStockTakingPeriod_Validating(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtStockTakingPeriod_Validating()";
try
{
if (btnStockTakingPeriod.Enabled)
{
if (!txtStockTakingPeriod.Modified)
return;
if (txtStockTakingPeriod.Text == string.Empty)
{
dtmFromDate.Value = null;
dtmToDate.Value = null;
btnEdit.Enabled = false;
btnDelete.Enabled = false;
btnUpdate.Enabled = false;
chkClose.Checked = false;
return;
}
DataRowView drwResult = null;
drwResult = FormControlComponents.OpenSearchForm(IV_StockTakingPeriodTable.TABLE_NAME, IV_StockTakingPeriodTable.DESCRIPTION_FLD, txtStockTakingPeriod.Text.Trim(), null, false);
if (drwResult != null)
{
btnEdit.Enabled = true;
btnDelete.Enabled = true;
if (drwResult[IV_StockTakingPeriodTable.STOCKTAKINGDATE_FLD].ToString() != string.Empty)
{
btnUpdate.Enabled = true;
}
else
btnUpdate.Enabled = false;
txtStockTakingPeriod.Text = drwResult[IV_StockTakingPeriodTable.DESCRIPTION_FLD].ToString();
txtStockTakingPeriod.Tag = drwResult[IV_StockTakingPeriodTable.STOCKTAKINGPERIODID_FLD];
chkClose.Checked = (bool) drwResult[IV_StockTakingPeriodTable.CLOSED_FLD];
FillDataToControls(drwResult);
}
else
e.Cancel = true;
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// txtStockTakingPeriod_KeyDown
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void txtStockTakingPeriod_KeyDown(object sender, KeyEventArgs e)
{
if (btnStockTakingPeriod.Enabled && e.KeyCode == Keys.F4)
{
btnStockTakingPeriod_Click(null, null);
}
}
/// <summary>
/// btnDelete_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void btnDelete_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnDelete_Click()";
try
{
if (PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
StockTakingPeriodBO boStockTakingPeriod = new StockTakingPeriodBO();
//check before delete
if (boStockTakingPeriod.CheckIfDataWasUsed(int.Parse(txtStockTakingPeriod.Tag.ToString())))
{
//delete
boStockTakingPeriod.DeleteByID(int.Parse(txtStockTakingPeriod.Tag.ToString()));
formMode = EnumAction.Default;
ClearForm();
SwitchFormMode();
}
else
{
string[] strParam = new string[1];
strParam[0] = " Stock Taking Period because this Period was used to setup Stock Taking";
PCSMessageBox.Show(ErrorCode.MESSAGE_CAN_NOT_DELETE, MessageBoxIcon.Warning, strParam);
return;
}
}
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
/// <summary>
/// StockTakingPeriod_Closing
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>Trada</author>
/// <date>Tuesday, July 25 2006</date>
private void StockTakingPeriod_Closing(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".StockTakingPeriod_Closing()";
try
{
if (formMode != EnumAction.Default)
{
DialogResult confirmDialog = PCSMessageBox.Show(ErrorCode.MESSAGE_QUESTION_STORE_INTO_DATABASE, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
switch (confirmDialog)
{
case DialogResult.Yes:
//Save before exit
btnSave_Click(btnSave, new EventArgs());
if (blnHasError)
{
e.Cancel = true;
}
break;
case DialogResult.No:
break;
case DialogResult.Cancel:
e.Cancel = true;
break;
}
}
else if (thrProcess != null)
{
if (thrProcess.IsAlive || thrProcess.ThreadState == ThreadState.Running)
{
string[] strMsg = {btnUpdate.Text.Replace("&", string.Empty)};
DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_PROCESS_IS_RUNNING, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, strMsg);
switch (dlgResult)
{
case DialogResult.OK:
// try to stop the thread
try
{
thrProcess.Abort();
}
catch
{
e.Cancel = false;
}
break;
case DialogResult.Cancel:
e.Cancel = true;
break;
}
}
}
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex.Message, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
/// <summary>
/// When Update Onhand button pressed,
/// we will calculate different between stock taking and current cache.
/// After that, need to generate adjustment transaction
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <author>DungLA</author>
/// <date>22-12-2006</date>
private void btnUpdate_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnUpdate_Click()";
try
{
if (cboCCN.SelectedValue.Equals(null))
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_CCN, MessageBoxIcon.Warning);
cboCCN.Focus();
return;
}
StockTakingPeriodBO boPeriod = new StockTakingPeriodBO();
if (txtStockTakingPeriod.Tag == null)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
txtStockTakingPeriod.Focus();
return;
}
// try to get period
try
{
IV_StockTakingPeriodVO voPeriod = (IV_StockTakingPeriodVO)boPeriod.GetObjectVO(Convert.ToInt32(txtStockTakingPeriod.Tag), string.Empty);
if (voPeriod.StockTakingPeriodID <= 0)
throw new Exception();
}
catch
{
string[] strMessage = new string[1];
strMessage[0] = lblStockTakingPeriod.Text;
PCSMessageBox.Show(ErrorCode.MESSAGE_SELECTION_NOT_EXIST, MessageBoxIcon.Error, strMessage);
// reset data
txtStockTakingPeriod.Text = string.Empty;
dtmFromDate.Value = DBNull.Value;
dtmToDate.Value = DBNull.Value;
chkClose.Checked = false;
txtStockTakingPeriod.Focus();
return;
}
// set mode to update inventory
IsUpdateInventory = true;
SwitchMode(true);
thrProcess = new Thread(new ThreadStart(UpdateInventory));
thrProcess.Start();
if (thrProcess.ThreadState == ThreadState.Stopped || !thrProcess.IsAlive)
thrProcess.Abort();
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
/// <summary>
/// This will start a new thread for update inventory
/// </summary>
private void UpdateInventory()
{
const string METHOD_NAME = THIS + ".UpdateInventory()";
try
{
this.Cursor = Cursors.WaitCursor;
DateTime dtmDate = (DateTime)dtmFromDate.Value;
if (IsUpdateInventory)
{
UpdateInventory(Convert.ToInt32(cboCCN.SelectedValue), Convert.ToInt32(txtStockTakingPeriod.Tag), dtmDate);
string[] strMsg = new string[]{btnUpdate.Text.Replace("&", string.Empty)};
PCSMessageBox.Show(ErrorCode.MESSAGE_TASK_COMPLETED, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, strMsg);
this.btnUpdate.Enabled = true;
this.btnUpdateDiff.Enabled = true;
}
else
{
UpdateDifferent(Convert.ToInt32(txtStockTakingPeriod.Tag), (DateTime)dtmToDate.Value);
string[] strMsg = new string[]{btnUpdateDiff.Text.Replace("&", string.Empty)};
PCSMessageBox.Show(ErrorCode.MESSAGE_TASK_COMPLETED, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, strMsg);
this.btnUpdate.Enabled = true;
this.btnUpdateDiff.Enabled = true;
}
this.Cursor = Cursors.Default;
SwitchMode(false);
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex.Message, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
string[] strMsg = new string[]{this.Text};
PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_ROLL_UP, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, strMsg);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
finally
{
this.Cursor = Cursors.Default;
SwitchMode(false);
}
}
private void UpdateInventory(int pintCCNID, int pintPeriodID, DateTime pdtmStockTakingDate)
{
StockTakingPeriodBO boPeriod = new StockTakingPeriodBO();
// first we will get all data of current period
DataTable dtbStockTaking = boPeriod.GetStockTakingByPeriodID(pintPeriodID).Tables[0];
// now get all data from all bin of current cache
DataTable dtbCache = boPeriod.ListAllCache();
// list all item with bin and location to be update
DataTable dtbItemToUpdate = boPeriod.ListItemToUpdate(pintPeriodID);
// list all location with master location
DataTable dtbLocations = boPeriod.ListLocation();
DataTable dtbAdjustmentTable = boPeriod.GetAdjustmentSchema();
string strTransNo;
FormInfo objFormInfo = FormControlComponents.GetFormInfo(new IVInventoryAdjustment(), out strTransNo);
string strFormat_Number = objFormInfo.mTransFormat.Substring(objFormInfo.mTransFormat.IndexOf("#"));
string strAutoNumber = strTransNo.Substring(strTransNo.Length - strFormat_Number.Length, strFormat_Number.Length);
strTransNo = strTransNo.Substring(0, strTransNo.Length - strFormat_Number.Length);
int intAutoNumber = Convert.ToInt32(strAutoNumber);
string strComment = "Stock Taking " + pdtmStockTakingDate.ToString(Constants.DATETIME_FORMAT);
foreach (DataRow drowItem in dtbItemToUpdate.Rows)
{
string strLocationID = drowItem[IV_BinCacheTable.LOCATIONID_FLD].ToString();
string strBinID = drowItem[IV_BinCacheTable.BINID_FLD].ToString();
string strProductID = drowItem[IV_BinCacheTable.PRODUCTID_FLD].ToString();
string strStockUMID = drowItem[ITM_ProductTable.STOCKUMID_FLD].ToString();
string strFilter = IV_BinCacheTable.LOCATIONID_FLD + "=" + strLocationID + " AND " + IV_BinCacheTable.BINID_FLD + "=" + strBinID + " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + strProductID;
decimal decCacheQuantity = 0, decTakingQuantity = 0, decCommitQuantity = 0;
// quantity from cache
try
{
decCacheQuantity = Convert.ToDecimal(dtbCache.Compute("SUM(" + IV_BinCacheTable.OHQUANTITY_FLD + ")", strFilter));
}
catch
{}
try
{
decCommitQuantity = Convert.ToDecimal(dtbCache.Compute("SUM(" + IV_BinCacheTable.COMMITQUANTITY_FLD + ")", strFilter));
}
catch
{}
// quantity from stock taking
try
{
decTakingQuantity = Convert.ToDecimal(dtbStockTaking.Compute("SUM(" + IV_StockTakingTable.QUANTITY_FLD + ")", strFilter));
}
catch
{
}
decimal decAdjustQuantity = decTakingQuantity - decCacheQuantity;
int intMasterLocationID = GetMasterLocationIDByLocationID(strLocationID, dtbLocations);
if (decAdjustQuantity != 0)
{
intAutoNumber++;
#region make new adjustment record
DataRow drowAdjust = dtbAdjustmentTable.NewRow();
drowAdjust[IV_AdjustmentTable.POSTDATE_FLD] = pdtmStockTakingDate;
drowAdjust[IV_AdjustmentTable.COMMENT_FLD] = strComment;
drowAdjust[IV_AdjustmentTable.PRODUCTID_FLD] = strProductID;
drowAdjust[IV_AdjustmentTable.STOCKUMID_FLD] = strStockUMID;
drowAdjust[IV_AdjustmentTable.CCNID_FLD] = pintCCNID;
drowAdjust[IV_AdjustmentTable.LOCATIONID_FLD] = strLocationID;
drowAdjust[IV_AdjustmentTable.BINID_FLD] = strBinID;
drowAdjust[IV_AdjustmentTable.MASTERLOCATIONID_FLD] = intMasterLocationID;
drowAdjust[IV_AdjustmentTable.ADJUSTQUANTITY_FLD] = decAdjustQuantity;
drowAdjust[IV_AdjustmentTable.AVAILABLEQTY_FLD] = decCacheQuantity - decCommitQuantity;
drowAdjust[IV_AdjustmentTable.USEDBYCOSTING_FLD] = false;
drowAdjust[IV_AdjustmentTable.USERNAME_FLD] = SystemProperty.UserName;
drowAdjust[IV_AdjustmentTable.TRANSNO_FLD] = strTransNo + intAutoNumber.ToString().PadLeft(strFormat_Number.Length, '0');
dtbAdjustmentTable.Rows.Add(drowAdjust);
#endregion
}
#region update cache
DataRow[] drowCaches = dtbCache.Select(strFilter);
if (drowCaches.Length > 0)
drowCaches[0][IV_BinCacheTable.OHQUANTITY_FLD] = decTakingQuantity;
else
{
DataRow drowCache = dtbCache.NewRow();
drowCache[IV_BinCacheTable.CCNID_FLD] = pintCCNID;
drowCache[IV_BinCacheTable.MASTERLOCATIONID_FLD] = intMasterLocationID;
drowCache[IV_BinCacheTable.LOCATIONID_FLD] = strLocationID;
drowCache[IV_BinCacheTable.BINID_FLD] = strBinID;
drowCache[IV_BinCacheTable.PRODUCTID_FLD] = strProductID;
drowCache[IV_BinCacheTable.OHQUANTITY_FLD] = decTakingQuantity;
dtbCache.Rows.Add(drowCache);
}
#endregion
}
boPeriod.UpdateInventory(dtbAdjustmentTable, dtbCache, strComment);
}
private void UpdateDifferent(int pintPeriodID, DateTime pdtmStockTakingDate)
{
StockTakingPeriodBO boPeriod = new StockTakingPeriodBO();
InventoryUtilsBO boIVUtils = new InventoryUtilsBO();
// first we will get all data of current period
DataTable dtbStockTaking = boPeriod.GetStockTakingByPeriodID(pintPeriodID).Tables[0];
DataTable dtbCache = boIVUtils.GetOHQtyByPostDate(pdtmStockTakingDate, 0, 0, 0, 0);
// transaction history of stock taking date
DataTable dtbHistory = boPeriod.ListTransactionHistory(pdtmStockTakingDate);
// list all item with bin and location to be update
DataTable dtbItemToUpdate = boPeriod.ListItemToUpdate(pintPeriodID);
// data for IV_StockTakingDifferent
DataTable dtbStockTakingDifferent = boPeriod.GetStockTakingDifferent(pintPeriodID);
string strLocationID, strBinID, strProductID, strFilter;
decimal decCacheQuantity = 0, decTakingQuantity = 0, decHistory = 0, decAdjustQuantity = 0;
foreach (DataRow drowItem in dtbItemToUpdate.Rows)
{
strLocationID = drowItem[IV_BinCacheTable.LOCATIONID_FLD].ToString();
strBinID = drowItem[IV_BinCacheTable.BINID_FLD].ToString();
strProductID = drowItem[IV_BinCacheTable.PRODUCTID_FLD].ToString();
strFilter = IV_BinCacheTable.LOCATIONID_FLD + "=" + strLocationID
+ " AND " + IV_BinCacheTable.BINID_FLD + "=" + strBinID
+ " AND " + IV_BinCacheTable.PRODUCTID_FLD + "=" + strProductID;
decCacheQuantity = 0;
decTakingQuantity = 0;
decHistory = 0;
// actual quantity in stock taking time
try
{
decCacheQuantity = Convert.ToDecimal(dtbCache.Compute("SUM(" + IV_BinCacheTable.OHQUANTITY_FLD + ")", strFilter));
}
catch{}
// quantity from stock taking
try
{
decTakingQuantity = Convert.ToDecimal(dtbStockTaking.Compute("SUM(" + IV_StockTakingTable.QUANTITY_FLD + ")", strFilter));
}
catch{}
decAdjustQuantity = decTakingQuantity - decCacheQuantity;
try
{
decHistory = Convert.ToDecimal(dtbHistory.Compute("SUM(" + MST_TransactionHistoryTable.QUANTITY_FLD + ")", strFilter));
}
catch{}
DataRow[] drowDiffs = null;
try
{
drowDiffs = dtbStockTakingDifferent.Select(strFilter);
}
catch
{
Logger.LogMessage(strFilter, string.Empty, Level.DEBUG);
}
if (drowDiffs.Length > 0)// already exist
{
// update the quantity only
drowDiffs[0][IV_StockTakingDifferentTable.OHQUANTITY_FLD] = decCacheQuantity;
drowDiffs[0][IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD] = decTakingQuantity;
drowDiffs[0][IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD] = decAdjustQuantity;
drowDiffs[0][IV_StockTakingDifferentTable.HISTORYQUANTITY_FLD] = decHistory;
drowDiffs[0][IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD] = pdtmStockTakingDate;
}
else // create new record
{
DataRow drowDiff = dtbStockTakingDifferent.NewRow();
drowDiff[IV_StockTakingDifferentTable.BINID_FLD] = strBinID;
drowDiff[IV_StockTakingDifferentTable.LOCATIONID_FLD] = strLocationID;
drowDiff[IV_StockTakingDifferentTable.PRODUCTID_FLD] = strProductID;
drowDiff[IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD] = pdtmStockTakingDate;
drowDiff[IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD] = pintPeriodID;
drowDiff[IV_StockTakingDifferentTable.OHQUANTITY_FLD] = decCacheQuantity;
drowDiff[IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD] = decTakingQuantity;
drowDiff[IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD] = decAdjustQuantity;
drowDiff[IV_StockTakingDifferentTable.HISTORYQUANTITY_FLD] = decHistory;
dtbStockTakingDifferent.Rows.Add(drowDiff);
}
}
boPeriod.UpdateDifferent(dtbStockTakingDifferent);
}
private int GetMasterLocationIDByLocationID(string pstrLocationID, DataTable pdtbLocation)
{
return Convert.ToInt32(pdtbLocation.Select(MST_LocationTable.LOCATIONID_FLD + "=" + pstrLocationID)[0][MST_LocationTable.MASTERLOCATIONID_FLD]);
}
private void SwitchMode(bool pblnProcessing)
{
cboCCN.ReadOnly = pblnProcessing;
txtStockTakingPeriod.Enabled = !pblnProcessing;
dtmFromDate.Enabled = !pblnProcessing;
dtmToDate.Enabled = !pblnProcessing;
chkClose.Enabled = !pblnProcessing;
btnStockTakingPeriod.Enabled = !pblnProcessing;
btnAdd.Enabled = !pblnProcessing;
btnEdit.Enabled = !pblnProcessing;
btnDelete.Enabled = !pblnProcessing;
btnSave.Enabled = !pblnProcessing;
btnUpdate.Enabled = !pblnProcessing;
btnUpdateDiff.Enabled = !pblnProcessing;
}
private void btnUpdateDiff_Click(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".btnUpdate_Click()";
try
{
if (cboCCN.SelectedValue.Equals(null))
{
PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_CCN, MessageBoxIcon.Warning);
cboCCN.Focus();
return;
}
StockTakingPeriodBO boPeriod = new StockTakingPeriodBO();
if (txtStockTakingPeriod.Tag == null)
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxIcon.Warning);
txtStockTakingPeriod.Focus();
return;
}
// try to get period
try
{
IV_StockTakingPeriodVO voPeriod = (IV_StockTakingPeriodVO)boPeriod.GetObjectVO(Convert.ToInt32(txtStockTakingPeriod.Tag), string.Empty);
if (voPeriod.StockTakingPeriodID <= 0)
throw new Exception();
}
catch
{
string[] strMessage = new string[1];
strMessage[0] = lblStockTakingPeriod.Text;
PCSMessageBox.Show(ErrorCode.MESSAGE_SELECTION_NOT_EXIST, MessageBoxIcon.Error, strMessage);
// reset data
txtStockTakingPeriod.Text = string.Empty;
dtmFromDate.Value = DBNull.Value;
dtmToDate.Value = DBNull.Value;
chkClose.Checked = false;
txtStockTakingPeriod.Focus();
return;
}
// set mode to update different
IsUpdateInventory = false;
SwitchMode(true);
thrProcess = new Thread(new ThreadStart(UpdateInventory));
thrProcess.Start();
if (thrProcess.ThreadState == ThreadState.Stopped || !thrProcess.IsAlive)
thrProcess.Abort();
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
private void CloseStockButton_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".CloseStockButton_Click()";
Cursor = Cursors.WaitCursor;
try
{
StockTakingPeriodBO boPeriod = new StockTakingPeriodBO();
// run script to close the stock taking
int periodId = Convert.ToInt32(txtStockTakingPeriod.Tag);
DateTime stockTakingDate = (DateTime)dtmFromDate.Value;
// reset to begin of month
stockTakingDate = new DateTime(stockTakingDate.Year, stockTakingDate.Month, 1);
boPeriod.CloseStockTaking(periodId, stockTakingDate);
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
finally
{
Cursor = Cursors.Default;
}
}
private void UpdateBeginButton_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".UpdateBeginButton_Click()";
Cursor = Cursors.WaitCursor;
try
{
StockTakingPeriodBO boPeriod = new StockTakingPeriodBO();
// run script to update begin stock
int periodId = Convert.ToInt32(txtStockTakingPeriod.Tag);
DateTime effectDate = (DateTime)dtmFromDate.Value;
// reset to begin of month
effectDate = new DateTime(effectDate.Year, effectDate.Month, 1);
boPeriod.UpdateBeginStock(periodId, effectDate);
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
finally
{
Cursor = Cursors.Default;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using Agent.Sdk;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Agent.Plugins.Repository
{
public abstract class TfsVCCliManager
{
public readonly Dictionary<string, string> AdditionalEnvironmentVariables = new Dictionary<string, string>();
public CancellationToken CancellationToken { protected get; set; }
public ServiceEndpoint Endpoint { protected get; set; }
public Pipelines.RepositoryResource Repository { protected get; set; }
public AgentTaskPluginExecutionContext ExecutionContext { protected get; set; }
public abstract TfsVCFeatures Features { get; }
public abstract Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace);
public abstract Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace);
protected virtual Encoding OutputEncoding => null;
protected string SourceVersion
{
get
{
string version = Repository.Version;
ArgUtil.NotNullOrEmpty(version, nameof(version));
return version;
}
}
protected string SourcesDirectory
{
get
{
string sourcesDirectory = Repository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Path);
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
return sourcesDirectory;
}
}
protected abstract string Switch { get; }
protected string WorkspaceName
{
get
{
string workspace = ExecutionContext.Variables.GetValueOrDefault("build.repository.tfvc.workspace")?.Value;
ArgUtil.NotNullOrEmpty(workspace, nameof(workspace));
return workspace;
}
}
protected Task RunCommandAsync(params string[] args)
{
return RunCommandAsync(FormatFlags.None, args);
}
protected Task RunCommandAsync(int retriesOnFailure, params string[] args)
{
return RunCommandAsync(FormatFlags.None, false, retriesOnFailure, args);
}
protected Task RunCommandAsync(FormatFlags formatFlags, params string[] args)
{
return RunCommandAsync(formatFlags, false, args);
}
protected Task RunCommandAsync(FormatFlags formatFlags, bool quiet, params string[] args)
{
return RunCommandAsync(formatFlags, quiet, 0, args);
}
protected async Task RunCommandAsync(FormatFlags formatFlags, bool quiet, int retriesOnFailure, params string[] args)
{
for (int attempt = 0; attempt < retriesOnFailure; attempt++)
{
int exitCode = await RunCommandAsync(formatFlags, quiet, false, args);
if (exitCode == 0)
{
return;
}
int sleep = Math.Min(200 * (int)Math.Pow(5, attempt), 30000);
ExecutionContext.Output($"Sleeping for {sleep} ms");
await Task.Delay(sleep);
// Use attempt+2 since we're using 0 based indexing and we're displaying this for the next attempt.
ExecutionContext.Output($@"Retrying. Attempt ${attempt+2}/${retriesOnFailure}");
}
// Perform one last try and fail on non-zero exit code
await RunCommandAsync(formatFlags, quiet, true, args);
}
protected async Task<int> RunCommandAsync(FormatFlags formatFlags, bool quiet, bool failOnNonZeroExitCode, params string[] args)
{
// Validation.
ArgUtil.NotNull(args, nameof(args));
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
// Invoke tf.
using (var processInvoker = new ProcessInvoker(ExecutionContext))
{
var outputLock = new object();
processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
if (quiet)
{
ExecutionContext.Debug(e.Data);
}
else
{
ExecutionContext.Output(e.Data);
}
}
};
processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
ExecutionContext.Output(e.Data);
}
};
string arguments = FormatArguments(formatFlags, args);
ExecutionContext.Command($@"tf {arguments}");
return await processInvoker.ExecuteAsync(
workingDirectory: SourcesDirectory,
fileName: "tf",
arguments: arguments,
environment: AdditionalEnvironmentVariables,
requireExitCodeZero: failOnNonZeroExitCode,
outputEncoding: OutputEncoding,
cancellationToken: CancellationToken);
}
}
protected Task<string> RunPorcelainCommandAsync(FormatFlags formatFlags, params string[] args)
{
return RunPorcelainCommandAsync(formatFlags, 0, args);
}
protected Task<string> RunPorcelainCommandAsync(params string[] args)
{
return RunPorcelainCommandAsync(FormatFlags.None, 0, args);
}
protected Task<string> RunPorcelainCommandAsync(int retriesOnFailure, params string[] args)
{
return RunPorcelainCommandAsync(FormatFlags.None, retriesOnFailure, args);
}
protected async Task<string> RunPorcelainCommandAsync(FormatFlags formatFlags, int retriesOnFailure, params string[] args)
{
// Run the command.
TfsVCPorcelainCommandResult result = await TryRunPorcelainCommandAsync(formatFlags, retriesOnFailure, args);
ArgUtil.NotNull(result, nameof(result));
if (result.Exception != null)
{
// The command failed. Dump the output and throw.
result.Output?.ForEach(x => ExecutionContext.Output(x ?? string.Empty));
throw result.Exception;
}
// Return the output.
// Note, string.join gracefully handles a null element within the IEnumerable<string>.
return string.Join(Environment.NewLine, result.Output ?? new List<string>());
}
protected async Task<TfsVCPorcelainCommandResult> TryRunPorcelainCommandAsync(FormatFlags formatFlags, int retriesOnFailure, params string[] args)
{
var result = await TryRunPorcelainCommandAsync(formatFlags, args);
for (int attempt = 0; attempt < retriesOnFailure && result.Exception != null && result.Exception?.ExitCode != 1; attempt++)
{
ExecutionContext.Warning($"{result.Exception.Message}");
int sleep = Math.Min(200 * (int)Math.Pow(5, attempt), 30000);
ExecutionContext.Output($"Sleeping for {sleep} ms before starting {attempt + 1}/{retriesOnFailure} retry");
await Task.Delay(sleep);
result = await TryRunPorcelainCommandAsync(formatFlags, args);
}
return result;
}
protected async Task<TfsVCPorcelainCommandResult> TryRunPorcelainCommandAsync(FormatFlags formatFlags, params string[] args)
{
// Validation.
ArgUtil.NotNull(args, nameof(args));
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
// Invoke tf.
using (var processInvoker = new ProcessInvoker(ExecutionContext))
{
var result = new TfsVCPorcelainCommandResult();
var outputLock = new object();
processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
ExecutionContext.Debug(e.Data);
result.Output.Add(e.Data);
}
};
processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
{
lock (outputLock)
{
ExecutionContext.Debug(e.Data);
result.Output.Add(e.Data);
}
};
string arguments = FormatArguments(formatFlags, args);
ExecutionContext.Debug($@"tf {arguments}");
// TODO: Test whether the output encoding needs to be specified on a non-Latin OS.
try
{
await processInvoker.ExecuteAsync(
workingDirectory: SourcesDirectory,
fileName: "tf",
arguments: arguments,
environment: AdditionalEnvironmentVariables,
requireExitCodeZero: true,
outputEncoding: OutputEncoding,
cancellationToken: CancellationToken);
}
catch (ProcessExitCodeException ex)
{
result.Exception = ex;
}
return result;
}
}
private string FormatArguments(FormatFlags formatFlags, params string[] args)
{
// Validation.
ArgUtil.NotNull(args, nameof(args));
ArgUtil.NotNull(Endpoint, nameof(Endpoint));
ArgUtil.NotNull(Endpoint.Authorization, nameof(Endpoint.Authorization));
ArgUtil.NotNull(Endpoint.Authorization.Parameters, nameof(Endpoint.Authorization.Parameters));
ArgUtil.Equal(EndpointAuthorizationSchemes.OAuth, Endpoint.Authorization.Scheme, nameof(Endpoint.Authorization.Scheme));
string accessToken = Endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out accessToken) ? accessToken : null;
ArgUtil.NotNullOrEmpty(accessToken, EndpointAuthorizationParameters.AccessToken);
ArgUtil.NotNull(Repository.Url, nameof(Repository.Url));
// Format each arg.
var formattedArgs = new List<string>();
foreach (string arg in args ?? new string[0])
{
// Validate the arg.
if (!string.IsNullOrEmpty(arg) && arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0)
{
throw new Exception(StringUtil.Loc("InvalidCommandArg", arg));
}
// Add the arg.
formattedArgs.Add(arg != null && arg.Contains(" ") ? $@"""{arg}""" : $"{arg}");
}
// Add the common parameters.
if (!formatFlags.HasFlag(FormatFlags.OmitCollectionUrl))
{
if (Features.HasFlag(TfsVCFeatures.EscapedUrl))
{
formattedArgs.Add($"{Switch}collection:{Repository.Url.AbsoluteUri}");
}
else
{
// TEE CLC expects the URL in unescaped form.
string url;
try
{
url = Uri.UnescapeDataString(Repository.Url.AbsoluteUri);
}
catch (Exception ex)
{
// Unlikely (impossible?), but don't fail if encountered. If we don't hear complaints
// about this warning then it is likely OK to remove the try/catch altogether and have
// faith that UnescapeDataString won't throw for this scenario.
url = Repository.Url.AbsoluteUri;
ExecutionContext.Warning($"{ex.Message} ({url})");
}
formattedArgs.Add($"\"{Switch}collection:{url}\"");
}
}
if (!formatFlags.HasFlag(FormatFlags.OmitLogin))
{
if (Features.HasFlag(TfsVCFeatures.LoginType))
{
formattedArgs.Add($"{Switch}loginType:OAuth");
formattedArgs.Add($"{Switch}login:.,{accessToken}");
}
else
{
formattedArgs.Add($"{Switch}jwt:{accessToken}");
}
}
if (!formatFlags.HasFlag(FormatFlags.OmitNoPrompt))
{
formattedArgs.Add($"{Switch}noprompt");
}
return string.Join(" ", formattedArgs);
}
[Flags]
protected enum FormatFlags
{
None = 0,
OmitCollectionUrl = 1,
OmitLogin = 2,
OmitNoPrompt = 4,
All = OmitCollectionUrl | OmitLogin | OmitNoPrompt,
}
}
[Flags]
public enum TfsVCFeatures
{
None = 0,
// Indicates whether "workspace /new" adds a default mapping.
DefaultWorkfoldMap = 1,
// Indicates whether the CLI accepts the collection URL in escaped form.
EscapedUrl = 2,
// Indicates whether the "eula" subcommand is supported.
Eula = 4,
// Indicates whether the "get" and "undo" subcommands will correctly resolve
// the workspace from an unmapped root folder. For example, if a workspace
// contains only two mappings, $/foo -> $(build.sourcesDirectory)\foo and
// $/bar -> $(build.sourcesDirectory)\bar, then "tf get $(build.sourcesDirectory)"
// will not be able to resolve the workspace unless this feature is supported.
GetFromUnmappedRoot = 8,
// Indicates whether the "loginType" parameter is supported.
LoginType = 16,
// Indicates whether the "scorch" subcommand is supported.
Scorch = 32,
}
public sealed class TfsVCPorcelainCommandResult
{
public TfsVCPorcelainCommandResult()
{
Output = new List<string>();
}
public ProcessExitCodeException Exception { get; set; }
public List<string> Output { get; }
}
////////////////////////////////////////////////////////////////////////////////
// tf shelvesets interfaces.
////////////////////////////////////////////////////////////////////////////////
public interface ITfsVCShelveset
{
string Comment { get; }
}
////////////////////////////////////////////////////////////////////////////////
// tf status interfaces.
////////////////////////////////////////////////////////////////////////////////
public interface ITfsVCStatus
{
IEnumerable<ITfsVCPendingChange> AllAdds { get; }
bool HasPendingChanges { get; }
}
public interface ITfsVCPendingChange
{
string LocalItem { get; }
}
////////////////////////////////////////////////////////////////////////////////
// tf workspaces interfaces.
////////////////////////////////////////////////////////////////////////////////
public interface ITfsVCWorkspace
{
string Computer { get; set; }
string Name { get; }
string Owner { get; }
ITfsVCMapping[] Mappings { get; }
}
public interface ITfsVCMapping
{
bool Cloak { get; }
string LocalPath { get; }
bool Recursive { get; }
string ServerPath { get; }
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json;
using Sensus.UI.UiProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using Syncfusion.SfChart.XForms;
using System.Threading.Tasks;
using Sensus.Context;
using Microsoft.AppCenter.Analytics;
using System.ComponentModel;
using Sensus.Extensions;
using Sensus.Exceptions;
using Sensus.Probes.User.Scripts;
using static Sensus.Adaptation.SensingAgent;
namespace Sensus.Probes
{
/// <summary>
/// Each Probe collects data of a particular type from the device. Sensus contains Probes for many of the hardware sensors present on many
/// smartphones as well as several software events (e.g., receipt of SMS messages). Sensus also contains Probes that can prompt the user
/// for information, which the user supplies via speech or textual input. Sensus defines a variety of Probes, with platform availability
/// and quality varying by device manufacturer (e.g., Apple, Motorola, Samsung, etc.). Availability and reliability of Probes will depend
/// on the device being used.
/// </summary>
public abstract class Probe : INotifyPropertyChanged, IProbe
{
#region static members
public static List<Probe> GetAll()
{
List<Probe> probes = null;
// the reflection stuff we do below (at least on android) needs to be run on the main thread.
SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
{
probes = Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Probe))).Select(t => Activator.CreateInstance(t) as Probe).OrderBy(p => p.DisplayName).ToList();
});
return probes;
}
#endregion
/// <summary>
/// Delegate for methods that handle <see cref="MostRecentDatumChanged"/> events from <see cref="Probe"/>s.
/// </summary>
public delegate Task MostRecentDatumChangedDelegateAsync(Datum previous, Datum current);
/// <summary>
/// Fired when the most recently sensed datum is changed, regardless of whether the datum was stored.
/// </summary>
public event MostRecentDatumChangedDelegateAsync MostRecentDatumChanged;
public event PropertyChangedEventHandler PropertyChanged;
private bool _enabled;
private Datum _mostRecentDatum;
private Protocol _protocol;
private bool _storeData;
private DateTimeOffset? _mostRecentStoreTimestamp;
private bool _originallyEnabled;
private List<Tuple<bool, DateTime>> _startStopTimes;
private List<DateTime> _successfulHealthTestTimes;
private List<ChartDataPoint> _chartData;
private int _maxChartDataCount;
private DataRateCalculator _rawRateCalculator;
private DataRateCalculator _storageRateCalculator;
private DataRateCalculator _uiUpdateRateCalculator;
private EventHandler<bool> _powerConnectionChanged;
private CancellationTokenSource _processDataCanceller;
private ProbeState _state;
private readonly object _stateLocker = new object();
[JsonIgnore]
public abstract string DisplayName { get; }
[JsonIgnore]
public abstract string CollectionDescription { get; }
/// <summary>
/// Whether the <see cref="Probe"/> should be turned on when the user starts the <see cref="Protocol"/>.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
[OnOffUiProperty("Enabled:", true, 2)]
public bool Enabled
{
get { return _enabled; }
set
{
if (value != _enabled)
{
// lock the state so that enabling/disabling does not interfere with ongoing
// start, stop, restart, etc. operations.
lock (_stateLocker)
{
_enabled = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Enabled)));
}
}
}
}
/// <summary>
/// Gets or sets whether or not this probe was originally enabled within the protocol. Some probes can become disabled when
/// attempting to start them. For example, the temperature probe might not be supported on all hardware and will thus become
/// disabled after its failed initialization. Thus, we need a separate variable (other than Enabled) to tell us whether the
/// probe was originally enabled. We use this value to calculate participation levels and also to restore the probe before
/// sharing it with others (e.g., since other people might have temperature hardware in their devices).
/// </summary>
/// <value>Whether or not this probe was enabled the first time the protocol was started.</value>
public bool OriginallyEnabled
{
get
{
return _originallyEnabled;
}
set
{
_originallyEnabled = value;
}
}
[JsonIgnore]
public ProbeState State
{
get { return _state; }
}
[JsonIgnore]
public DateTimeOffset? MostRecentStoreTimestamp
{
get { return _mostRecentStoreTimestamp; }
}
public Protocol Protocol
{
get { return _protocol; }
set { _protocol = value; }
}
/// <summary>
/// Whether the Probe should store the data it collects. This might be turned off if the <see cref="Probe"/> is used to trigger
/// the <see cref="User.Scripts.ScriptProbe"/> but the probed data are not needed.
/// </summary>
/// <value><c>true</c> if store data; otherwise, <c>false</c>.</value>
[OnOffUiProperty("Store Data:", true, 3)]
public bool StoreData
{
get { return _storeData; }
set { _storeData = value; }
}
/// <summary>
/// Whether or not to allow the user to disable this <see cref="Probe"/> when starting the <see cref="Protocol"/>.
/// </summary>
/// <value>Allow user to disable on start up.</value>
[OnOffUiProperty("Allow Disable On Startup:", true, 5)]
public bool AllowDisableOnStartUp { get; set; } = false;
[JsonIgnore]
public abstract Type DatumType { get; }
[JsonIgnore]
protected abstract double RawParticipation { get; }
[JsonIgnore]
protected abstract long DataRateSampleSize { get; }
public abstract double? MaxDataStoresPerSecond { get; set; }
/// <summary>
/// Gets a list of times at which the probe was started (tuple bool = True) and stopped (tuple bool = False). Only includes
/// those that have occurred within the protocol's participation horizon.
/// </summary>
/// <value>The start stop times.</value>
public List<Tuple<bool, DateTime>> StartStopTimes
{
get { return _startStopTimes; }
}
/// <summary>
/// Gets the successful health test times. Only includes those that have occurred within the
/// protocol's participation horizon.
/// </summary>
/// <value>The successful health test times.</value>
public List<DateTime> SuccessfulHealthTestTimes
{
get { return _successfulHealthTestTimes; }
}
/// <summary>
/// How much data to save from the <see cref="Probe"/> for the purpose of charting within the Sensus app.
/// </summary>
/// <value>The maximum chart data count.</value>
[EntryIntegerUiProperty("Max Chart Data Count:", true, 50, true)]
public int MaxChartDataCount
{
get
{
return _maxChartDataCount;
}
set
{
if (value > 0)
{
_maxChartDataCount = value;
}
// trim chart data collection
lock (_chartData)
{
while (_chartData.Count > 0 && _chartData.Count > _maxChartDataCount)
{
_chartData.RemoveAt(0);
}
}
}
}
[JsonIgnore]
public string Caption
{
get
{
string type = "";
if (this is ListeningProbe)
{
type = "Listening";
}
else if (this is PollingProbe)
{
type = "Polling";
}
return DisplayName + (type == "" ? "" : " (" + type + ")");
}
}
[JsonIgnore]
public string SubCaption
{
get
{
// get and check reference to most recent datum, as it might change due to
// concurrent access by probe reading.
Datum mostRecentDatum = _mostRecentDatum;
if (mostRecentDatum == null)
{
return "[no data]";
}
else
{
return mostRecentDatum.DisplayDetail + " " + mostRecentDatum.Timestamp.ToLocalTime();
}
}
}
protected Probe()
{
_enabled = false;
_state = ProbeState.Stopped;
_storeData = true;
_startStopTimes = new List<Tuple<bool, DateTime>>();
_successfulHealthTestTimes = new List<DateTime>();
_maxChartDataCount = 10;
_chartData = new List<ChartDataPoint>(_maxChartDataCount + 1);
_powerConnectionChanged = async (sender, connected) =>
{
if (connected)
{
// ask the probe to start processing its data
try
{
SensusServiceHelper.Get().Logger.Log("AC power connected. Initiating data processing within probe.", LoggingLevel.Normal, GetType());
_processDataCanceller = new CancellationTokenSource();
await ProcessDataAsync(_processDataCanceller.Token);
SensusServiceHelper.Get().Logger.Log("Probe data processing complete.", LoggingLevel.Normal, GetType());
}
catch (OperationCanceledException)
{
// don't report task cancellation exceptions. these are expected whenever the user unplugs the device while processing data.
SensusServiceHelper.Get().Logger.Log("Data processing task was cancelled.", LoggingLevel.Normal, GetType());
}
catch (Exception ex)
{
// the data processing actually failed prior to cancellation. this should not happen, so report it.
SensusException.Report("Non-cancellation exception while processing probe data: " + ex.Message, ex);
}
}
else
{
// cancel any previous attempt to process data
_processDataCanceller?.Cancel();
}
};
}
protected virtual Task InitializeAsync()
{
SensusServiceHelper.Get().Logger.Log("Initializing...", LoggingLevel.Normal, GetType());
lock (_chartData)
{
_chartData.Clear();
}
_mostRecentDatum = null;
_mostRecentStoreTimestamp = DateTimeOffset.UtcNow; // mark storage delay from initialization of probe
// track/limit the raw data rate
_rawRateCalculator = new DataRateCalculator(DataRateSampleSize, MaxDataStoresPerSecond);
// track the storage rate
_storageRateCalculator = new DataRateCalculator(DataRateSampleSize);
// track/limit the UI update rate
_uiUpdateRateCalculator = new DataRateCalculator(DataRateSampleSize, 1);
// hook into the AC charge event signal -- add handler to AC broadcast receiver
SensusContext.Current.PowerConnectionChangeListener.PowerConnectionChanged += _powerConnectionChanged;
return Task.CompletedTask;
}
public async Task StartAsync()
{
lock (_stateLocker)
{
// don't attempt to start the probe if it is not enabled. this can happen, e.g., when remote protocol
// updates disable the probe and the probe is subsequently restarted to take on the update values.
if (Enabled && _state == ProbeState.Stopped)
{
_state = ProbeState.Initializing;
}
else
{
SensusServiceHelper.Get().Logger.Log("Attempted to start probe, but it was already in state " + _state + " with " + nameof(Enabled) + "=" + Enabled + ".", LoggingLevel.Normal, GetType());
return;
}
}
try
{
await InitializeAsync();
lock (_stateLocker)
{
_state = ProbeState.Starting;
}
// start data rate calculators
_rawRateCalculator.Start();
_storageRateCalculator.Start();
_uiUpdateRateCalculator.Start();
await ProtectedStartAsync();
lock (_stateLocker)
{
_state = ProbeState.Running;
}
lock (_startStopTimes)
{
_startStopTimes.Add(new Tuple<bool, DateTime>(true, DateTime.Now));
_startStopTimes.RemoveAll(t => t.Item2 < Protocol.ParticipationHorizon);
}
}
catch (Exception startException)
{
if (startException is NotSupportedException)
{
Enabled = false;
}
// stop probe to clean up any inconsistent state information
try
{
await StopAsync();
}
catch (Exception stopException)
{
SensusServiceHelper.Get().Logger.Log("Failed to stop probe after failing to start it: " + stopException.Message, LoggingLevel.Normal, GetType());
}
string message = "Sensus failed to start probe \"" + GetType().Name + "\": " + startException.Message;
SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType());
await SensusServiceHelper.Get().FlashNotificationAsync(message);
throw startException;
}
}
protected virtual Task ProtectedStartAsync()
{
SensusServiceHelper.Get().Logger.Log("Starting...", LoggingLevel.Normal, GetType());
return Task.CompletedTask;
}
/// <summary>
/// Stores a <see cref="Datum"/> within the <see cref="LocalDataStore"/>. Will not throw an <see cref="Exception"/>.
/// </summary>
/// <param name="datum">Datum.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public async Task StoreDatumAsync(Datum datum, CancellationToken? cancellationToken = null)
{
// it's possible for the current method to be called when the protocol is not running. the obvious case is when
// the protocol is paused, but there are other race-like conditions. we try to prevent this (e.g., by forcing
// the user to start the protocol before taking a survey saved from a previous run of the app), but there are
// probably corner cases we haven't accounted for. at the very least, there are race conditions (e.g., taking a
// survey when a protocol is about to stop) that could cause data to be stored without a running protocol.
if (_protocol.State != ProtocolState.Running)
{
return;
}
// track/limit the raw rate of non-null data. all null data will pass this test, and this is
// fine given such data are generated by polling probes when no data were retrieved. such
// return values from polling probes are used to indicate that the poll was completed, which
// will be reflected in the _mostRecentStoreTimestamp below.
if (datum != null)
{
// impose a limit on the raw data rate
if (_rawRateCalculator.Add(datum) == DataRateCalculator.SamplingAction.Drop)
{
return;
}
// set properties that we were unable to set within the datum constructor.
datum.ProtocolId = Protocol.Id;
datum.ParticipantId = Protocol.ParticipantId;
// tag the data if we're in tagging mode, indicated with a non-null event id on the protocol. avoid
// any race conditions related to starting/stopping a tagging by getting the required values and
// then checking both for validity. we need to guarantee that any tagged datum has both an id and tags.
string taggedEventId = Protocol.TaggedEventId;
List<string> taggedEventTags = Protocol.TaggedEventTags.ToList();
if (!string.IsNullOrWhiteSpace(taggedEventId) && taggedEventTags.Count > 0)
{
datum.TaggedEventId = taggedEventId;
datum.TaggedEventTags = taggedEventTags;
}
// if the protocol is configured with a sensing agent,
if (Protocol.Agent != null)
{
datum.SensingAgentStateDescription = Protocol.Agent.StateDescription;
}
}
// store non-null data
if (_storeData && datum != null)
{
#region update chart data
ChartDataPoint chartDataPoint = null;
try
{
chartDataPoint = GetChartDataPointFromDatum(datum);
}
catch (NotImplementedException)
{
}
if (chartDataPoint != null)
{
lock (_chartData)
{
_chartData.Add(chartDataPoint);
while (_chartData.Count > 0 && _chartData.Count > _maxChartDataCount)
{
_chartData.RemoveAt(0);
}
}
}
#endregion
// write datum to local data store. catch any exceptions, as the caller (e.g., a listening
// probe) could very well be unprotected on the UI thread. throwing an exception here can crash the app.
try
{
_protocol.LocalDataStore.WriteDatum(datum, cancellationToken.GetValueOrDefault());
// track the storage rate
_storageRateCalculator.Add(datum);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to write datum: " + ex, LoggingLevel.Normal, GetType());
}
}
// update the timestamp of the most recent store. this is used to calculate storage latency, so we
// do not restrict its values to those obtained when non-null data are stored (see above). some
// probes call this method with null data to signal that they have run their collection to completion.
_mostRecentStoreTimestamp = DateTimeOffset.UtcNow;
// don't update the UI too often, as doing so at really high rates causes UI deadlocks. always let
// null data update the UI, as these are only generated by polling probes at low rates.
if (datum == null || _uiUpdateRateCalculator.Add(datum) == DataRateCalculator.SamplingAction.Keep)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SubCaption)));
}
// track the most recent datum regardless of whether the datum is null or whether we're storing data
Datum previousDatum = _mostRecentDatum;
_mostRecentDatum = datum;
// notify observers of the stored data and associated UI values
await (MostRecentDatumChanged?.Invoke(previousDatum, _mostRecentDatum) ?? Task.CompletedTask);
// let the script probe's agent observe the data, as long as the probe is enabled and there is an agent.
Protocol.TryGetProbe(typeof(ScriptProbe), out Probe scriptProbe);
if (scriptProbe?.Enabled ?? false)
{
// agents might be third-party and badly behaving...catch their exceptions.
try
{
await ((scriptProbe as ScriptProbe).Agent?.ObserveAsync(datum) ?? Task.CompletedTask);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while script probe agent was observing datum: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
// let the protocol's sensing agent observe the data, and schedule any returned control
// completion check. agents might be third-party and badly behaving...catch their exceptions.
try
{
await Protocol.ScheduleAgentControlCompletionCheckAsync(await (Protocol.Agent?.ObserveAsync(datum, cancellationToken.GetValueOrDefault()) ?? Task.FromResult<ControlCompletionCheck>(null)));
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Exception while sensing agent was observing datum: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
/// <summary>
/// Instructs the current probe to process data that it has collected. This call does not provide the data
/// to process. Rather, it is up to each probe to cache data in memory or on disk as appropriate, in such a
/// way that they can be processed when this method is called. This method will only be
/// called under suitable conditions (e.g., when the device is charging). Any <see cref="Datum"/> objects that
/// result from this processing should be stored via calls to <see cref="StoreDatumAsync(Datum, CancellationToken?)"/>.
/// The <see cref="CancellationToken"/> passed to this method should be monitored carefully when processing data.
/// If the token is cancelled, then the data processing should abort immediately and the method should return as quickly
/// as possible. The <see cref="CancellationToken"/> passed to this method should also be passed to
/// <see cref="StoreDatumAsync(Datum, CancellationToken?)"/>, as this ensures that all operations associated
/// with data storage terminate promptly if the token is cancelled. It is up to the overriding implementation to
/// handle multiple calls to this method (even in quick succession and/or concurrently) properly.
/// </summary>
/// <returns>The data async.</returns>
/// <param name="cancellationToken">Cancellation token.</param>
public virtual Task ProcessDataAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
/// <summary>
/// Gets the participation level for the current probe. If this probe was originally enabled within the protocol, then
/// this will be a value between 0 and 1, with 1 indicating perfect participation and 0 indicating no participation. If
/// this probe was not originally enabled within the protocol, then the returned value will be null, indicating that this
/// probe should not be included in calculations of overall protocol participation. Probes can become disabled if they
/// are not supported on the current device or if the user refuses to initialize them (e.g., by denying Health Kit).
/// Although they become disabled, they were originally enabled within the protocol and participation should reflect this.
/// Lastly, this will return null if the probe is not storing its data, as might be the case if a probe is enabled in order
/// to trigger scripts but not told to store its data.
/// </summary>
/// <returns>The participation level (null, or somewhere 0-1).</returns>
public double? GetParticipation()
{
if (_originallyEnabled && _storeData)
{
return Math.Min(RawParticipation, 1); // raw participations can be > 1, e.g. in the case of polling probes that the user can cause to poll repeatedly. cut off at 1 to maintain the interpretation of 1 as perfect participation.
}
else
{
return null;
}
}
public async Task StopAsync()
{
lock (_stateLocker)
{
if (_state == ProbeState.Stopped || _state == ProbeState.Stopping)
{
SensusServiceHelper.Get().Logger.Log("Attempted to stop probe, but it was already in state " + _state + ".", LoggingLevel.Normal, GetType());
return;
}
else
{
_state = ProbeState.Stopping;
}
}
try
{
await ProtectedStopAsync();
}
finally
{
lock (_startStopTimes)
{
_startStopTimes.Add(new Tuple<bool, DateTime>(false, DateTime.Now));
_startStopTimes.RemoveAll(t => t.Item2 < Protocol.ParticipationHorizon);
}
// unhook from the AC charge event signal -- remove handler to AC broadcast receiver
SensusContext.Current.PowerConnectionChangeListener.PowerConnectionChanged -= _powerConnectionChanged;
lock (_stateLocker)
{
_state = ProbeState.Stopped;
}
}
}
protected virtual Task ProtectedStopAsync()
{
SensusServiceHelper.Get().Logger.Log("Stopping...", LoggingLevel.Normal, GetType());
return Task.CompletedTask;
}
public async Task RestartAsync()
{
await StopAsync();
await StartAsync();
}
public virtual Task<HealthTestResult> TestHealthAsync(List<AnalyticsTrackedEvent> events)
{
HealthTestResult result = HealthTestResult.Okay;
lock (_stateLocker)
{
string eventName = TrackedEvent.Health + ":" + GetType().Name;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{ "State", _state.ToString() }
};
// we'll only have data rates if the probe is running -- it might have failed to start.
if (_state == ProbeState.Running)
{
double? rawDataPerSecond = _rawRateCalculator.GetDataPerSecond();
double? storedDataPerSecond = _storageRateCalculator.GetDataPerSecond();
double? percentageNominalStoreRate = null;
if (storedDataPerSecond.HasValue && MaxDataStoresPerSecond.HasValue)
{
percentageNominalStoreRate = (storedDataPerSecond.Value / MaxDataStoresPerSecond.Value) * 100;
}
properties.Add("Percentage Nominal Storage Rate", Convert.ToString(percentageNominalStoreRate?.RoundToWhole(5)));
Analytics.TrackEvent(eventName, properties);
// we don't have a great way of tracking data rates, as they are continuous values and event tracking is string-based. so,
// just add the rates to the properties after event tracking. this way it will still be included in the status.
properties.Add("Raw Data / Second", Convert.ToString(rawDataPerSecond));
properties.Add("Stored Data / Second", Convert.ToString(storedDataPerSecond));
}
events.Add(new AnalyticsTrackedEvent(eventName, properties));
}
return Task.FromResult(result);
}
public virtual Task ResetAsync()
{
lock (_stateLocker)
{
if (_state != ProbeState.Stopped)
{
throw new Exception("Cannot reset probe unless it is stopped.");
}
}
lock (_chartData)
{
_chartData.Clear();
}
lock (_startStopTimes)
{
_startStopTimes.Clear();
}
lock (_successfulHealthTestTimes)
{
_successfulHealthTestTimes.Clear();
}
_mostRecentDatum = null;
_mostRecentStoreTimestamp = null;
return Task.CompletedTask;
}
public SfChart GetChart()
{
ChartSeries series = GetChartSeries();
if (series == null)
{
return null;
}
// provide the series with a copy of the chart data. if we provide the actual list, then the
// chart wants to auto-update the display on subsequent additions to the list. if this happens,
// then we'll need to update the list on the UI thread so that the chart is redrawn correctly.
// and if this is the case then we're in trouble because xamarin forms is not always initialized
// when the list is updated with probed data (if the activity is killed).
lock (_chartData)
{
series.ItemsSource = _chartData.ToList();
}
SfChart chart = new SfChart
{
PrimaryAxis = GetChartPrimaryAxis(),
SecondaryAxis = GetChartSecondaryAxis(),
};
chart.Series.Add(series);
chart.ChartBehaviors.Add(new ChartZoomPanBehavior
{
EnablePanning = true,
EnableZooming = true,
EnableDoubleTap = true
});
return chart;
}
protected abstract ChartSeries GetChartSeries();
protected abstract ChartAxis GetChartPrimaryAxis();
protected abstract RangeAxisBase GetChartSecondaryAxis();
protected abstract ChartDataPoint GetChartDataPointFromDatum(Datum datum);
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
/// We expect 2 order from the algorithm, which are:
///
/// * Initial entry, sell ES Put Option (expiring OTM)
/// - Profit the option premium, since the option was not assigned.
///
/// * Liquidation of ES put OTM contract on the last trade date
///
/// Additionally, we test delistings for future options and assert that our
/// portfolio holdings reflect the orders the algorithm has submitted.
/// </summary>
public class FutureOptionShortPutOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _es19m20;
private Symbol _esOption;
private Symbol _expectedContract;
public override void Initialize()
{
SetStartDate(2020, 1, 5);
SetEndDate(2020, 6, 30);
_es19m20 = AddFutureContract(
QuantConnect.Symbol.CreateFuture(
Futures.Indices.SP500EMini,
Market.CME,
new DateTime(2020, 6, 19)),
Resolution.Minute).Symbol;
// Select a future option expiring ITM, and adds it to the algorithm.
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
.Where(x => x.ID.StrikePrice <= 3000m && x.ID.OptionRight == OptionRight.Put)
.OrderByDescending(x => x.ID.StrikePrice)
.Take(1)
.Single(), Resolution.Minute).Symbol;
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Put, 3000m, new DateTime(2020, 6, 19));
if (_esOption != _expectedContract)
{
throw new Exception($"Contract {_expectedContract} was not found in the chain");
}
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
{
MarketOrder(_esOption, -1);
});
}
public override void OnData(Slice data)
{
// Assert delistings, so that we can make sure that we receive the delisting warnings at
// the expected time. These assertions detect bug #4872
foreach (var delisting in data.Delistings.Values)
{
if (delisting.Type == DelistingType.Warning)
{
if (delisting.Time != new DateTime(2020, 6, 19))
{
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
}
}
if (delisting.Type == DelistingType.Delisted)
{
if (delisting.Time != new DateTime(2020, 6, 20))
{
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status != OrderStatus.Filled)
{
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
return;
}
if (!Securities.ContainsKey(orderEvent.Symbol))
{
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
}
var security = Securities[orderEvent.Symbol];
if (security.Symbol == _es19m20)
{
throw new Exception($"Expected no order events for underlying Symbol {security.Symbol}");
}
if (security.Symbol == _expectedContract)
{
AssertFutureOptionContractOrder(orderEvent, security);
}
else
{
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
}
Log($"{orderEvent}");
}
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
{
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != -1)
{
throw new Exception($"No holdings were created for option contract {option.Symbol}");
}
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 0)
{
throw new Exception("Expected no options holdings after closing position");
}
if (orderEvent.IsAssignment)
{
throw new Exception($"Assignment was not expected for {orderEvent.Symbol}");
}
}
/// <summary>
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
/// </summary>
/// <exception cref="Exception">The algorithm has holdings</exception>
public override void OnEndOfAlgorithm()
{
if (Portfolio.Invested)
{
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "3.29%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "6.869%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "3.286%"},
{"Sharpe Ratio", "1.205"},
{"Probabilistic Sharpe Ratio", "61.483%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.048"},
{"Beta", "-0.002"},
{"Annual Standard Deviation", "0.04"},
{"Annual Variance", "0.002"},
{"Information Ratio", "0.07"},
{"Tracking Error", "0.377"},
{"Treynor Ratio", "-24.401"},
{"Total Fees", "$1.85"},
{"Estimated Strategy Capacity", "$80000000.00"},
{"Lowest Capacity Asset", "ES 31EL5FAJQ6SBO|ES XFH59UK0MYO1"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "150.849"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "76ed4eaa5f6ed50aa6134aecfbbe9e29"}
};
}
}
| |
using System;
using bsn.GoldParser.Parser;
namespace GoldAddin
{
/// <summary>
/// Resposnsible for parsing the raw messages output by the GOLDBuild
/// command line compiler
/// </summary>
public class GoldBuildOutputParser
{
readonly string fileName;
readonly GoldParsedDocument parsedDoc;
/// <summary>
/// Initializes a new instance of the <see cref="GoldAddin.GoldBuildOutputParser"/> class.
/// </summary>
/// <param name="fileName">File name.</param>
public GoldBuildOutputParser(string fileName)
{
this.fileName = fileName;
parsedDoc = new GoldParsedDocument ();
parsedDoc.ParseFromFile (fileName);
}
/// <summary>
/// Parses the raw message and returns a compiler
/// message object representing the raw message from the compiler
/// </summary>
/// <param name="data">A message provided by the GOLDbuild compiler.
/// Assumed to be a singe line</param>
/// <returns>A CompilerMessage representation of the given message string</returns>
public CompilerMessage ParseRawMessage(string data)
{
int line = 0;
int column = 0;
string text = data;
MessageSeverity severity = getSeverity (data);
bool isNewProblem = (!isContinuationMessage (data)) &&
(severity == MessageSeverity.Warning || severity == MessageSeverity.Error);
if (isNewProblem)
{
string problemText = getProblemText (data);
text = problemText;
var location = locateError (problemText);
line = location.Line;
column = location.Column;
}
else
{
//dont want to report an existing problem again,
// so downgrade the message
severity = MessageSeverity.Info;
}
return new CompilerMessage(severity, text, fileName, line, column, data);
}
static readonly char[] fieldDelimiters = {':'};
LineInfo locateError (string problemText)
{
//text will be in the form:
// TYPE : DESCRIPTION : OPTIONAL
// optional field may or may not be present
// in at least one case, description field is not present
string[] fields = problemText.Split (fieldDelimiters, StringSplitOptions.RemoveEmptyEntries);
string type = string.Empty;
string descr = string.Empty;
if (fields.Length > 0)
type = fields [0];
if (fields.Length > 1)
descr = fields [1];
if (type.Contains ("Undefined"))
{
//use the first location of the token in question
string name = getTokenText (type, descr);
return getLocationOfToken (name);
}
if (type.Contains ("Unused") || type.Contains ("Unreachable"))
{
//search for declaration start
string name = getTokenText (type, descr);
return getLocationOfDefinition (name);
}
if (type.Contains ("start symbol"))
{
//search for start symbol declaration. may or may not be there
return getLocationOfDefinition ("\"Start Symbol\"");
}
if (type.Contains ("Duplicate") || type.Contains ("redefined"))
{
string name = getTokenTextForDuplicateMessage (type, descr);
return getLocationOfReDefinition (name);
}
//handle DFA error where multiple terminals can accept the same text
//this particular error actually has four fields:
// TYPE:DESCRIPTION:TERMINAL-LIST:DETAILS
if (type.Contains("DFA") && descr.Contains ("Cannot distinguish between"))
{
//this error will contain a space seperated list of terminals
//use the first terminal from the list for location info
string terminals = fields[2];
string firstTerminal = terminals.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)[0];
return getLocationOfDefinition(firstTerminal);
}
return new LineInfo (0, 0, 0);
}
static string getTokenText(string problemType, string description)
{
if (problemType.Contains ("terminal"))
{
//description is already terminal name!
return description.Trim();
}
if (problemType.Contains ("rule"))
{
return GrammarText.FindNonTerminalName (description);
}
if (problemType.Contains ("Set"))
{
return GrammarText.FindSetName (description);
}
if (problemType.Contains ("property"))
{
return GrammarText.FindPropertyName (description);
}
return string.Empty;
}
//unfortunately duplicate errors must be handled slightly differently because
// duplicate terminal messages from GOLD do not match the pattern of all the
// other messages. In those cases, the description field is empty!
static string getTokenTextForDuplicateMessage(string problemType, string description)
{
if (problemType.Contains ("terminal"))
{
return GrammarText.FindTerminalName (problemType);
}
return getTokenText (problemType, description);
}
//name is already delimited. ie: {set name}, <non terminal>, ...
// the location of the first matching token is returned
LineInfo getLocationOfToken(string tokenName)
{
var enumerator = parsedDoc.FindUsesOf (tokenName).GetEnumerator();
var location = new LineInfo (0, 0, 0);
if (enumerator.MoveNext ())
{
location= enumerator.Current.Position;
}
return location;
}
//assumes tokenName is already delimited. eg: {set name}, <non terminal>, ...
//returns the location where the given name is first defined
LineInfo getLocationOfDefinition(string tokenName)
{
var enumerator = parsedDoc.FindDefinitionsByName (tokenName).GetEnumerator ();
var location = new LineInfo (0, 0, 0);
if (enumerator.MoveNext ())
location = enumerator.Current.Location;
if (locationNotFound (location))
{
//some error messages could report unused, even though the symbol was not
// defined formally (such as a terminal), which can be confusing.
// In those cases, just find the first use
location = getLocationOfToken (tokenName);
}
return location;
}
//name is already delimited. ie: {set name}, <non terminal>, ...
//returns the location of the second definition of the given name
LineInfo getLocationOfReDefinition(string name)
{
var enumerator = parsedDoc.FindDefinitionsByName (name).GetEnumerator ();
if (enumerator.MoveNext ())
{
if (enumerator.MoveNext ())
{
return enumerator.Current.Location;
}
}
return new LineInfo (0, 0, 0);
}
//assumes that the given string is already in the form SEVERITY:PHASE:PROBLEM
static string getProblemText (string data)
{
//first field is severity, second is phase
const int FieldsToRemove = 2; //fields are separated by colons
string messageText = data;
//get the index of the 2nd field delimiter
int dataLength = data.Length;
int colonCount = 0;
int index = 0;
for (int i=0; i<dataLength; i++)
{
if (data [i] == ':')
{
colonCount += 1;
if (colonCount == FieldsToRemove)
{
index = i;
break;
}
}
}
int startIndex = index + 1;
if (startIndex < dataLength)
messageText = data.Substring (startIndex).Trim();
return messageText;
}
static MessageSeverity getSeverity (string rawMessage)
{
var severity = MessageSeverity.Info;
if(startsWithIgnoreCase(rawMessage,"ERROR") || isContinuationMessage(rawMessage))
severity = MessageSeverity.Error;
else if(startsWithIgnoreCase(rawMessage,"WARNING"))
severity= MessageSeverity.Warning;
return severity;
}
static bool startsWithIgnoreCase(string str, string substr)
{
return str.StartsWith (substr, StringComparison.OrdinalIgnoreCase);
}
static bool isContinuationMessage(string data)
{
return startsWithIgnoreCase (data, "Expecting");
}
static bool locationNotFound(LineInfo lineInfo)
{
return lineInfo.Line == 0 && lineInfo.Column == 0;
}
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: api@oanda.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// A DelayedTradeClosure Transaction is created administratively to indicate open trades that should have been closed but weren't because the open trades' instruments were untradeable at the time. Open trades listed in this transaction will be closed once their respective instruments become tradeable.
/// </summary>
[DataContract]
public partial class DelayedTradeClosureTransaction : IEquatable<DelayedTradeClosureTransaction>, IValidatableObject
{
/// <summary>
/// The Type of the Transaction. Always set to \"DELAYED_TRADE_CLOSURE\" for an DelayedTradeClosureTransaction.
/// </summary>
/// <value>The Type of the Transaction. Always set to \"DELAYED_TRADE_CLOSURE\" for an DelayedTradeClosureTransaction.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum CREATE for "CREATE"
/// </summary>
[EnumMember(Value = "CREATE")]
CREATE,
/// <summary>
/// Enum CLOSE for "CLOSE"
/// </summary>
[EnumMember(Value = "CLOSE")]
CLOSE,
/// <summary>
/// Enum REOPEN for "REOPEN"
/// </summary>
[EnumMember(Value = "REOPEN")]
REOPEN,
/// <summary>
/// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE"
/// </summary>
[EnumMember(Value = "CLIENT_CONFIGURE")]
CLIENTCONFIGURE,
/// <summary>
/// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT"
/// </summary>
[EnumMember(Value = "CLIENT_CONFIGURE_REJECT")]
CLIENTCONFIGUREREJECT,
/// <summary>
/// Enum TRANSFERFUNDS for "TRANSFER_FUNDS"
/// </summary>
[EnumMember(Value = "TRANSFER_FUNDS")]
TRANSFERFUNDS,
/// <summary>
/// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT"
/// </summary>
[EnumMember(Value = "TRANSFER_FUNDS_REJECT")]
TRANSFERFUNDSREJECT,
/// <summary>
/// Enum MARKETORDER for "MARKET_ORDER"
/// </summary>
[EnumMember(Value = "MARKET_ORDER")]
MARKETORDER,
/// <summary>
/// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "MARKET_ORDER_REJECT")]
MARKETORDERREJECT,
/// <summary>
/// Enum LIMITORDER for "LIMIT_ORDER"
/// </summary>
[EnumMember(Value = "LIMIT_ORDER")]
LIMITORDER,
/// <summary>
/// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "LIMIT_ORDER_REJECT")]
LIMITORDERREJECT,
/// <summary>
/// Enum STOPORDER for "STOP_ORDER"
/// </summary>
[EnumMember(Value = "STOP_ORDER")]
STOPORDER,
/// <summary>
/// Enum STOPORDERREJECT for "STOP_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "STOP_ORDER_REJECT")]
STOPORDERREJECT,
/// <summary>
/// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER"
/// </summary>
[EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")]
MARKETIFTOUCHEDORDER,
/// <summary>
/// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")]
MARKETIFTOUCHEDORDERREJECT,
/// <summary>
/// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER"
/// </summary>
[EnumMember(Value = "TAKE_PROFIT_ORDER")]
TAKEPROFITORDER,
/// <summary>
/// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")]
TAKEPROFITORDERREJECT,
/// <summary>
/// Enum STOPLOSSORDER for "STOP_LOSS_ORDER"
/// </summary>
[EnumMember(Value = "STOP_LOSS_ORDER")]
STOPLOSSORDER,
/// <summary>
/// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "STOP_LOSS_ORDER_REJECT")]
STOPLOSSORDERREJECT,
/// <summary>
/// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER"
/// </summary>
[EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")]
TRAILINGSTOPLOSSORDER,
/// <summary>
/// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")]
TRAILINGSTOPLOSSORDERREJECT,
/// <summary>
/// Enum ORDERFILL for "ORDER_FILL"
/// </summary>
[EnumMember(Value = "ORDER_FILL")]
ORDERFILL,
/// <summary>
/// Enum ORDERCANCEL for "ORDER_CANCEL"
/// </summary>
[EnumMember(Value = "ORDER_CANCEL")]
ORDERCANCEL,
/// <summary>
/// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT"
/// </summary>
[EnumMember(Value = "ORDER_CANCEL_REJECT")]
ORDERCANCELREJECT,
/// <summary>
/// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY"
/// </summary>
[EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")]
ORDERCLIENTEXTENSIONSMODIFY,
/// <summary>
/// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT"
/// </summary>
[EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")]
ORDERCLIENTEXTENSIONSMODIFYREJECT,
/// <summary>
/// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY"
/// </summary>
[EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")]
TRADECLIENTEXTENSIONSMODIFY,
/// <summary>
/// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT"
/// </summary>
[EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")]
TRADECLIENTEXTENSIONSMODIFYREJECT,
/// <summary>
/// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER"
/// </summary>
[EnumMember(Value = "MARGIN_CALL_ENTER")]
MARGINCALLENTER,
/// <summary>
/// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND"
/// </summary>
[EnumMember(Value = "MARGIN_CALL_EXTEND")]
MARGINCALLEXTEND,
/// <summary>
/// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT"
/// </summary>
[EnumMember(Value = "MARGIN_CALL_EXIT")]
MARGINCALLEXIT,
/// <summary>
/// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE"
/// </summary>
[EnumMember(Value = "DELAYED_TRADE_CLOSURE")]
DELAYEDTRADECLOSURE,
/// <summary>
/// Enum DAILYFINANCING for "DAILY_FINANCING"
/// </summary>
[EnumMember(Value = "DAILY_FINANCING")]
DAILYFINANCING,
/// <summary>
/// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL"
/// </summary>
[EnumMember(Value = "RESET_RESETTABLE_PL")]
RESETRESETTABLEPL
}
/// <summary>
/// The reason for the delayed trade closure
/// </summary>
/// <value>The reason for the delayed trade closure</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum ReasonEnum
{
/// <summary>
/// Enum CLIENTORDER for "CLIENT_ORDER"
/// </summary>
[EnumMember(Value = "CLIENT_ORDER")]
CLIENTORDER,
/// <summary>
/// Enum TRADECLOSE for "TRADE_CLOSE"
/// </summary>
[EnumMember(Value = "TRADE_CLOSE")]
TRADECLOSE,
/// <summary>
/// Enum POSITIONCLOSEOUT for "POSITION_CLOSEOUT"
/// </summary>
[EnumMember(Value = "POSITION_CLOSEOUT")]
POSITIONCLOSEOUT,
/// <summary>
/// Enum MARGINCLOSEOUT for "MARGIN_CLOSEOUT"
/// </summary>
[EnumMember(Value = "MARGIN_CLOSEOUT")]
MARGINCLOSEOUT,
/// <summary>
/// Enum DELAYEDTRADECLOSE for "DELAYED_TRADE_CLOSE"
/// </summary>
[EnumMember(Value = "DELAYED_TRADE_CLOSE")]
DELAYEDTRADECLOSE
}
/// <summary>
/// The Type of the Transaction. Always set to \"DELAYED_TRADE_CLOSURE\" for an DelayedTradeClosureTransaction.
/// </summary>
/// <value>The Type of the Transaction. Always set to \"DELAYED_TRADE_CLOSURE\" for an DelayedTradeClosureTransaction.</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// The reason for the delayed trade closure
/// </summary>
/// <value>The reason for the delayed trade closure</value>
[DataMember(Name="reason", EmitDefaultValue=false)]
public ReasonEnum? Reason { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DelayedTradeClosureTransaction" /> class.
/// </summary>
/// <param name="Id">The Transaction's Identifier..</param>
/// <param name="Time">The date/time when the Transaction was created..</param>
/// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param>
/// <param name="AccountID">The ID of the Account the Transaction was created for..</param>
/// <param name="BatchID">The ID of the \"batch\" that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param>
/// <param name="RequestID">The Request ID of the request which generated the transaction..</param>
/// <param name="Type">The Type of the Transaction. Always set to \"DELAYED_TRADE_CLOSURE\" for an DelayedTradeClosureTransaction..</param>
/// <param name="Reason">The reason for the delayed trade closure.</param>
/// <param name="TradeIDs">List of Trade ID's identifying the open trades that will be closed when their respective instruments become tradeable.</param>
public DelayedTradeClosureTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?), ReasonEnum? Reason = default(ReasonEnum?), string TradeIDs = default(string))
{
this.Id = Id;
this.Time = Time;
this.UserID = UserID;
this.AccountID = AccountID;
this.BatchID = BatchID;
this.RequestID = RequestID;
this.Type = Type;
this.Reason = Reason;
this.TradeIDs = TradeIDs;
}
/// <summary>
/// The Transaction's Identifier.
/// </summary>
/// <value>The Transaction's Identifier.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// The date/time when the Transaction was created.
/// </summary>
/// <value>The date/time when the Transaction was created.</value>
[DataMember(Name="time", EmitDefaultValue=false)]
public string Time { get; set; }
/// <summary>
/// The ID of the user that initiated the creation of the Transaction.
/// </summary>
/// <value>The ID of the user that initiated the creation of the Transaction.</value>
[DataMember(Name="userID", EmitDefaultValue=false)]
public int? UserID { get; set; }
/// <summary>
/// The ID of the Account the Transaction was created for.
/// </summary>
/// <value>The ID of the Account the Transaction was created for.</value>
[DataMember(Name="accountID", EmitDefaultValue=false)]
public string AccountID { get; set; }
/// <summary>
/// The ID of the \"batch\" that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.
/// </summary>
/// <value>The ID of the \"batch\" that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value>
[DataMember(Name="batchID", EmitDefaultValue=false)]
public string BatchID { get; set; }
/// <summary>
/// The Request ID of the request which generated the transaction.
/// </summary>
/// <value>The Request ID of the request which generated the transaction.</value>
[DataMember(Name="requestID", EmitDefaultValue=false)]
public string RequestID { get; set; }
/// <summary>
/// List of Trade ID's identifying the open trades that will be closed when their respective instruments become tradeable
/// </summary>
/// <value>List of Trade ID's identifying the open trades that will be closed when their respective instruments become tradeable</value>
[DataMember(Name="tradeIDs", EmitDefaultValue=false)]
public string TradeIDs { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DelayedTradeClosureTransaction {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Time: ").Append(Time).Append("\n");
sb.Append(" UserID: ").Append(UserID).Append("\n");
sb.Append(" AccountID: ").Append(AccountID).Append("\n");
sb.Append(" BatchID: ").Append(BatchID).Append("\n");
sb.Append(" RequestID: ").Append(RequestID).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Reason: ").Append(Reason).Append("\n");
sb.Append(" TradeIDs: ").Append(TradeIDs).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DelayedTradeClosureTransaction);
}
/// <summary>
/// Returns true if DelayedTradeClosureTransaction instances are equal
/// </summary>
/// <param name="other">Instance of DelayedTradeClosureTransaction to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DelayedTradeClosureTransaction other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Time == other.Time ||
this.Time != null &&
this.Time.Equals(other.Time)
) &&
(
this.UserID == other.UserID ||
this.UserID != null &&
this.UserID.Equals(other.UserID)
) &&
(
this.AccountID == other.AccountID ||
this.AccountID != null &&
this.AccountID.Equals(other.AccountID)
) &&
(
this.BatchID == other.BatchID ||
this.BatchID != null &&
this.BatchID.Equals(other.BatchID)
) &&
(
this.RequestID == other.RequestID ||
this.RequestID != null &&
this.RequestID.Equals(other.RequestID)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.Reason == other.Reason ||
this.Reason != null &&
this.Reason.Equals(other.Reason)
) &&
(
this.TradeIDs == other.TradeIDs ||
this.TradeIDs != null &&
this.TradeIDs.Equals(other.TradeIDs)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Time != null)
hash = hash * 59 + this.Time.GetHashCode();
if (this.UserID != null)
hash = hash * 59 + this.UserID.GetHashCode();
if (this.AccountID != null)
hash = hash * 59 + this.AccountID.GetHashCode();
if (this.BatchID != null)
hash = hash * 59 + this.BatchID.GetHashCode();
if (this.RequestID != null)
hash = hash * 59 + this.RequestID.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.Reason != null)
hash = hash * 59 + this.Reason.GetHashCode();
if (this.TradeIDs != null)
hash = hash * 59 + this.TradeIDs.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
** $Id: loslib.c,v 1.19.1.3 2008/01/18 16:38:18 roberto Exp $
** Standard Operating System library
** See Copyright Notice in lua.h
*/
using System;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace SharpLua
{
using TValue = Lua.lua_TValue;
using StkId = Lua.lua_TValue;
using lua_Integer = System.Int32;
using lua_Number = System.Double;
public partial class Lua
{
private static int os_pushresult (LuaState L, int i, CharPtr filename) {
int en = errno(); /* calls to Lua API may change this value */
if (i != 0) {
lua_pushboolean(L, 1);
return 1;
}
else {
lua_pushnil(L);
lua_pushfstring(L, "%s: %s", filename, strerror(en));
lua_pushinteger(L, en);
return 3;
}
}
private static int os_execute (LuaState L) {
#if XBOX || SILVERLIGHT
luaL_error(L, "os_execute not supported on XBox360");
#else
//CharPtr strCmdLine = "/C regenresx " + luaL_optstring(L, 1, null);
CharPtr strCmdLine = "/C" + luaL_optstring(L, 1, null);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.Arguments = strCmdLine.ToString();
proc.Start();
proc.WaitForExit();
lua_pushinteger(L, proc.ExitCode);
#endif
return 1;
}
private static int os_remove (LuaState L) {
CharPtr filename = luaL_checkstring(L, 1);
int result = 1;
try {File.Delete(filename.ToString());} catch {result = 0;}
return os_pushresult(L, result, filename);
}
private static int os_rename (LuaState L) {
CharPtr fromname = luaL_checkstring(L, 1);
CharPtr toname = luaL_checkstring(L, 2);
int result;
try
{
File.Move(fromname.ToString(), toname.ToString());
result = 0;
}
catch
{
result = 1; // todo: this should be a proper error code
}
return os_pushresult(L, result, fromname);
}
private static int os_tmpname (LuaState L) {
#if XBOX
luaL_error(L, "os_tmpname not supported on Xbox360");
#else
lua_pushstring(L, Path.GetTempFileName());
#endif
return 1;
}
private static int os_getenv (LuaState L) {
lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if null push nil */
return 1;
}
private static int os_clock (LuaState L) {
long ticks = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
lua_pushnumber(L, ((lua_Number)ticks)/(lua_Number)1000);
return 1;
}
/*
** {======================================================
** Time/Date operations
** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
** wday=%w+1, yday=%j, isdst=? }
** =======================================================
*/
private static void setfield (LuaState L, CharPtr key, int value) {
lua_pushinteger(L, value);
lua_setfield(L, -2, key);
}
private static void setboolfield (LuaState L, CharPtr key, int value) {
if (value < 0) /* undefined? */
return; /* does not set field */
lua_pushboolean(L, value);
lua_setfield(L, -2, key);
}
private static int getboolfield (LuaState L, CharPtr key) {
int res;
lua_getfield(L, -1, key);
res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1);
lua_pop(L, 1);
return res;
}
private static int getfield (LuaState L, CharPtr key, int d) {
int res;
lua_getfield(L, -1, key);
if (lua_isnumber(L, -1) != 0)
res = (int)lua_tointeger(L, -1);
else {
if (d < 0)
return luaL_error(L, "field " + LUA_QS + " missing in date table", key);
res = d;
}
lua_pop(L, 1);
return res;
}
private static int os_date (LuaState L) {
CharPtr s = luaL_optstring(L, 1, "%c");
DateTime stm;
if (s[0] == '!') { /* UTC? */
stm = DateTime.UtcNow;
s.inc(); /* skip `!' */
}
else
stm = DateTime.Now;
if (strcmp(s, "*t") == 0) {
lua_createtable(L, 0, 9); /* 9 = number of fields */
setfield(L, "sec", stm.Second);
setfield(L, "min", stm.Minute);
setfield(L, "hour", stm.Hour);
setfield(L, "day", stm.Day);
setfield(L, "month", stm.Month);
setfield(L, "year", stm.Year);
setfield(L, "wday", (int)stm.DayOfWeek);
setfield(L, "yday", stm.DayOfYear);
setboolfield(L, "isdst", stm.IsDaylightSavingTime() ? 1 : 0);
}
else {
luaL_error(L, "strftime not implemented yet"); // todo: implement this - mjf
#if false
CharPtr cc = new char[3];
luaL_Buffer b;
cc[0] = '%'; cc[2] = '\0';
luaL_buffinit(L, b);
for (; s[0] != 0; s.inc()) {
if (s[0] != '%' || s[1] == '\0') /* no conversion specifier? */
luaL_addchar(b, s[0]);
else {
uint reslen;
CharPtr buff = new char[200]; /* should be big enough for any conversion result */
s.inc();
cc[1] = s[0];
reslen = strftime(buff, buff.Length, cc, stm);
luaL_addlstring(b, buff, reslen);
}
}
luaL_pushresult(b);
#endif // #if 0
}
return 1;
}
private static int os_time (LuaState L) {
DateTime t;
if (lua_isnoneornil(L, 1)) /* called without args? */
t = DateTime.Now; /* get current time */
else {
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1); /* make sure table is at the top */
int sec = getfield(L, "sec", 0);
int min = getfield(L, "min", 0);
int hour = getfield(L, "hour", 12);
int day = getfield(L, "day", -1);
int month = getfield(L, "month", -1) - 1;
int year = getfield(L, "year", -1) - 1900;
int isdst = getboolfield(L, "isdst"); // todo: implement this - mjf
t = new DateTime(year, month, day, hour, min, sec);
}
lua_pushnumber(L, t.Ticks);
return 1;
}
private static int os_difftime (LuaState L) {
long ticks = (long)luaL_checknumber(L, 1) - (long)luaL_optnumber(L, 2, 0);
lua_pushnumber(L, ticks/TimeSpan.TicksPerSecond);
return 1;
}
/* }====================================================== */
// locale not supported yet
private static int os_setlocale (LuaState L) {
/*
static string[] cat = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
LC_NUMERIC, LC_TIME};
static string[] catnames[] = {"all", "collate", "ctype", "monetary",
"numeric", "time", null};
CharPtr l = luaL_optstring(L, 1, null);
int op = luaL_checkoption(L, 2, "all", catnames);
lua_pushstring(L, setlocale(cat[op], l));
*/
CharPtr l = luaL_optstring(L, 1, null);
lua_pushstring(L, "C");
return (l.ToString() == "C") ? 1 : 0;
}
private static int os_exit (LuaState L) {
#if XBOX
luaL_error(L, "os_exit not supported on XBox360");
#else
#if SILVERLIGHT
throw new SystemException();
#else
Environment.Exit(EXIT_SUCCESS);
#endif
#endif
return 0;
}
private readonly static luaL_Reg[] syslib = {
new luaL_Reg("clock", os_clock),
new luaL_Reg("date", os_date),
new luaL_Reg("difftime", os_difftime),
new luaL_Reg("execute", os_execute),
new luaL_Reg("exit", os_exit),
new luaL_Reg("getenv", os_getenv),
new luaL_Reg("remove", os_remove),
new luaL_Reg("rename", os_rename),
new luaL_Reg("setlocale", os_setlocale),
new luaL_Reg("time", os_time),
new luaL_Reg("tmpname", os_tmpname),
new luaL_Reg(null, null)
};
/* }====================================================== */
public static int luaopen_os (LuaState L) {
luaL_register(L, LUA_OSLIBNAME, syslib);
return 1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Nest;
namespace Tests.Framework.Integration
{
public class ElasticsearchNode : IDisposable
{
private static readonly object _lock = new object();
// <installpath> <> <plugin folder prefix>
private readonly Dictionary<string, string> SupportedPlugins = new Dictionary<string, string>
{
{ "delete-by-query", "delete-by-query" },
{ "cloud-azure", "cloud-azure" }
};
private readonly bool _doNotSpawnIfAlreadyRunning;
private ObservableProcess _process;
private IDisposable _processListener;
public string Version { get; }
public string Binary { get; }
private string RoamingFolder { get; }
private string RoamingClusterFolder { get; }
public bool Started { get; private set; }
public bool RunningIntegrations { get; private set; }
public string Prefix { get; set; }
public string ClusterName { get; }
public string NodeName { get; }
public string RepositoryPath { get; private set; }
public ElasticsearchNodeInfo Info { get; private set; }
public int Port { get; private set; }
private readonly Subject<ManualResetEvent> _blockingSubject = new Subject<ManualResetEvent>();
public IObservable<ManualResetEvent> BootstrapWork { get; }
public ElasticsearchNode(string elasticsearchVersion, bool runningIntegrations, bool doNotSpawnIfAlreadyRunning, string prefix)
{
_doNotSpawnIfAlreadyRunning = doNotSpawnIfAlreadyRunning;
this.Version = elasticsearchVersion;
this.RunningIntegrations = runningIntegrations;
this.Prefix = prefix.ToLowerInvariant();
var suffix = Guid.NewGuid().ToString("N").Substring(0, 6);
this.ClusterName = $"{this.Prefix}-cluster-{suffix}";
this.NodeName = $"{this.Prefix}-node-{suffix}";
this.BootstrapWork = _blockingSubject;
if (!runningIntegrations)
{
this.Port = 9200;
return;
}
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
this.RoamingFolder = Path.Combine(appdata, "NEST", this.Version);
this.RoamingClusterFolder = Path.Combine(this.RoamingFolder, "elasticsearch-" + elasticsearchVersion);
this.RepositoryPath = Path.Combine(RoamingFolder, "repositories");
this.Binary = Path.Combine(this.RoamingClusterFolder, "bin", "elasticsearch") + ".bat";
Console.WriteLine("========> {0}", this.RoamingFolder);
this.DownloadAndExtractElasticsearch();
}
public IObservable<ElasticsearchMessage> Start()
{
if (!this.RunningIntegrations) return Observable.Empty<ElasticsearchMessage>();
this.Stop();
var timeout = TimeSpan.FromSeconds(60);
var handle = new ManualResetEvent(false);
if (_doNotSpawnIfAlreadyRunning)
{
var client = TestClient.GetClient();
var alreadyUp = client.RootNodeInfo();
if (alreadyUp.IsValid)
{
var checkPlugins = client.CatPlugins();
if (checkPlugins.IsValid)
{
foreach (var supportedPlugin in SupportedPlugins)
{
if (!checkPlugins.Records.Any(r => r.Component.Equals(supportedPlugin.Key)))
throw new ApplicationException($"Already running elasticsearch does not have supported plugin {supportedPlugin.Key} installed.");
}
this.Started = true;
this.Port = 9200;
this.Info = new ElasticsearchNodeInfo(alreadyUp.Version.Number, null, alreadyUp.Version.LuceneVersion);
this._blockingSubject.OnNext(handle);
if (!handle.WaitOne(timeout, true))
throw new ApplicationException($"Could not launch tests on already running elasticsearch within {timeout}");
return Observable.Empty<ElasticsearchMessage>();
}
}
}
this._process = new ObservableProcess(this.Binary,
$"-Des.cluster.name={this.ClusterName}",
$"-Des.node.name={this.NodeName}",
$"-Des.path.repo={this.RepositoryPath}",
$"-Des.script.inline=on",
$"-Des.script.indexed=on"
);
var observable = Observable.Using(() => this._process, process => process.Start())
.Select(consoleLine => new ElasticsearchMessage(consoleLine));
this._processListener = observable.Subscribe(onNext: s => HandleConsoleMessage(s, handle));
if (!handle.WaitOne(timeout, true))
{
this.Stop();
throw new ApplicationException($"Could not start elasticsearch within {timeout}");
}
return observable;
}
private void HandleConsoleMessage(ElasticsearchMessage s, ManualResetEvent handle)
{
//no need to snoop for metadata if we already started
if (!this.RunningIntegrations || this.Started) return;
ElasticsearchNodeInfo info;
int port;
if (s.TryParseNodeInfo(out info))
{
this.Info = info;
}
else if (s.TryGetStartedConfirmation())
{
var healthyCluster = this.Client().ClusterHealth(g => g.WaitForStatus(WaitForStatus.Yellow).Timeout(TimeSpan.FromSeconds(30)));
if (healthyCluster.IsValid)
{
this._blockingSubject.OnNext(handle);
this.Started = true;
}
else
{
this._blockingSubject.OnError(new Exception("Did not see a healthy cluster after the node started for 30 seconds"));
handle.Set();
this.Stop();
}
}
else if (s.TryGetPortNumber(out port))
{
this.Port = port;
}
}
private void DownloadAndExtractElasticsearch()
{
lock (_lock)
{
var zip = $"elasticsearch-{this.Version}.zip";
var downloadUrl = $"https://download.elasticsearch.org/elasticsearch/release/org/elasticsearch/distribution/zip/elasticsearch/{this.Version}/{zip}";
var localZip = Path.Combine(this.RoamingFolder, zip);
Directory.CreateDirectory(this.RoamingFolder);
if (!File.Exists(localZip))
{
Console.WriteLine($"Download elasticsearch: {this.Version} ...");
new WebClient().DownloadFile(downloadUrl, localZip);
Console.WriteLine($"Downloaded elasticsearch: {this.Version}");
}
if (!Directory.Exists(this.RoamingClusterFolder))
{
Console.WriteLine($"Unziping elasticsearch: {this.Version} ...");
ZipFile.ExtractToDirectory(localZip, this.RoamingFolder);
}
InstallPlugins();
//hunspell config
var hunspellFolder = Path.Combine(this.RoamingClusterFolder, "config", "hunspell", "en_US");
var hunspellPrefix = Path.Combine(hunspellFolder, "en_US");
if (!File.Exists(hunspellPrefix + ".dic"))
{
Directory.CreateDirectory(hunspellFolder);
//File.Create(hunspellPrefix + ".dic");
File.WriteAllText(hunspellPrefix + ".dic", "1\r\nabcdegf");
//File.Create(hunspellPrefix + ".aff");
File.WriteAllText(hunspellPrefix + ".aff", "SET UTF8\r\nSFX P Y 1\r\nSFX P 0 s");
}
var analysFolder = Path.Combine(this.RoamingClusterFolder, "config", "analysis");
if (!Directory.Exists(analysFolder)) Directory.CreateDirectory(analysFolder);
var fopXml = Path.Combine(analysFolder, "fop") + ".xml";
if (!File.Exists(fopXml)) File.WriteAllText(fopXml, "<languages-info />");
var customStems = Path.Combine(analysFolder, "custom_stems") + ".txt";
if (!File.Exists(customStems)) File.WriteAllText(customStems, "");
var stopwords = Path.Combine(analysFolder, "stopwords") + ".txt";
if (!File.Exists(stopwords)) File.WriteAllText(stopwords, "");
}
}
private void InstallPlugins()
{
var pluginBat = Path.Combine(this.RoamingClusterFolder, "bin", "plugin") + ".bat";
foreach (var plugin in SupportedPlugins)
{
var installPath = plugin.Key;
var localPath = plugin.Value;
var pluginFolder = Path.Combine(this.RoamingClusterFolder, "plugins", localPath);
if (!Directory.Exists(this.RoamingClusterFolder)) continue;
// assume plugin already installed
if (Directory.Exists(pluginFolder)) continue;
Console.WriteLine($"Installing elasticsearch plugin: {localPath} ...");
var timeout = TimeSpan.FromSeconds(60);
var handle = new ManualResetEvent(false);
Task.Run(() =>
{
using (var p = new ObservableProcess(pluginBat, "install", installPath))
{
var o = p.Start();
Console.WriteLine($"Calling: {pluginBat} install {installPath}");
o.Subscribe(e=>Console.WriteLine(e),
(e) =>
{
Console.WriteLine($"Failed installing elasticsearch plugin: {localPath} ");
handle.Set();
throw e;
},
() => {
Console.WriteLine($"Finished installing elasticsearch plugin: {localPath} exit code: {p.ExitCode}");
handle.Set();
});
if (!handle.WaitOne(timeout, true))
throw new ApplicationException($"Could not install ${installPath} within {timeout}");
}
});
if (!handle.WaitOne(timeout, true))
throw new ApplicationException($"Could not install ${installPath} within {timeout}");
}
}
public IElasticClient Client(Func<ConnectionSettings, ConnectionSettings> settings = null)
{
var port = this.Started ? this.Port : 9200;
settings = settings ?? (s => s);
var client = TestClient.GetClient(s => AppendClusterNameToHttpHeaders(settings(s)), port);
return client;
}
private ConnectionSettings AppendClusterNameToHttpHeaders(ConnectionSettings settings)
{
IConnectionConfigurationValues values = settings;
var headers = values.Headers ?? new NameValueCollection();
headers.Add("ClusterName", this.ClusterName);
return settings;
}
public void Stop()
{
if (!this.RunningIntegrations || !this.Started) return;
this.Started = false;
Console.WriteLine($"Stopping... ran integrations: {this.RunningIntegrations}");
Console.WriteLine($"Node started: {this.Started} on port: {this.Port} using PID: {this.Info?.Pid}");
this._process?.Dispose();
this._processListener?.Dispose();
if (this.Info != null && this.Info.Pid.HasValue)
{
var esProcess = Process.GetProcessById(this.Info.Pid.Value);
Console.WriteLine($"Killing elasticsearch PID {this.Info.Pid}");
esProcess.Kill();
esProcess.WaitForExit(5000);
esProcess.Close();
}
if (this._doNotSpawnIfAlreadyRunning) return;
var dataFolder = Path.Combine(this.RoamingClusterFolder, "data", this.ClusterName);
if (Directory.Exists(dataFolder))
{
Console.WriteLine($"attempting to delete cluster data: {dataFolder}");
Directory.Delete(dataFolder, true);
}
//var logPath = Path.Combine(this.RoamingClusterFolder, "logs");
//var files = Directory.GetFiles(logPath, this.ClusterName + "*.log");
//foreach (var f in files)
//{
// Console.WriteLine($"attempting to delete log file: {f}");
// File.Delete(f);
//}
if (Directory.Exists(this.RepositoryPath))
{
Console.WriteLine("attempting to delete repositories");
Directory.Delete(this.RepositoryPath, true);
}
}
public void Dispose()
{
this.Stop();
}
}
public class ElasticsearchMessage
{
/*
[2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] version[1.5.2], pid[7704], build[62ff986/2015-04-27T09:21:06Z]
[2015-05-26 20:05:07,681][INFO ][node ] [Nick Fury] initializing ...
[2015-05-26 20:05:07,681][INFO ][plugins ] [Nick Fury] loaded [], sites []
[2015-05-26 20:05:10,790][INFO ][node ] [Nick Fury] initialized
[2015-05-26 20:05:10,821][INFO ][node ] [Nick Fury] starting ...
[2015-05-26 20:05:11,041][INFO ][transport ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9300]}, publish_address {inet[/192.168.194.146:9300]}
[2015-05-26 20:05:11,056][INFO ][discovery ] [Nick Fury] elasticsearch-martijnl/yuiyXva3Si6sQE5tY_9CHg
[2015-05-26 20:05:14,103][INFO ][cluster.service ] [Nick Fury] new_master [Nick Fury][yuiyXva3Si6sQE5tY_9CHg][WIN-DK60SLEMH8C][inet[/192.168.194.146:9300]], reason: zen-disco-join (elected_as_master)
[2015-05-26 20:05:14,134][INFO ][gateway ] [Nick Fury] recovered [0] indices into cluster_state
[2015-05-26 20:05:14,150][INFO ][http ] [Nick Fury] bound_address {inet[/0:0:0:0:0:0:0:0:9200]}, publish_address {inet[/192.168.194.146:9200]}
[2015-05-26 20:05:14,150][INFO ][node ] [Nick Fury] started
*/
public DateTime Date { get; }
public string Level { get; }
public string Section { get; }
public string Node { get; }
public string Message { get; }
private static readonly Regex ConsoleLineParser =
new Regex(@"\[(?<date>.*?)\]\[(?<level>.*?)\]\[(?<section>.*?)\] \[(?<node>.*?)\] (?<message>.+)");
public ElasticsearchMessage(string consoleLine)
{
Console.WriteLine(consoleLine);
if (string.IsNullOrEmpty(consoleLine)) return;
var match = ConsoleLineParser.Match(consoleLine);
if (!match.Success) return;
var dateString = match.Groups["date"].Value.Trim();
Date = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss,fff", CultureInfo.CurrentCulture);
Level = match.Groups["level"].Value.Trim();
Section = match.Groups["section"].Value.Trim().Replace("org.elasticsearch.", "");
Node = match.Groups["node"].Value.Trim();
Message = match.Groups["message"].Value.Trim();
}
private static readonly Regex InfoParser =
new Regex(@"version\[(?<version>.*)\], pid\[(?<pid>.*)\], build\[(?<build>.+)\]");
public bool TryParseNodeInfo(out ElasticsearchNodeInfo nodeInfo)
{
nodeInfo = null;
if (this.Section != "node") return false;
var match = InfoParser.Match(this.Message);
if (!match.Success) return false;
var version = match.Groups["version"].Value.Trim();
var pid = match.Groups["pid"].Value.Trim();
var build = match.Groups["build"].Value.Trim();
nodeInfo = new ElasticsearchNodeInfo(version, pid, build);
return true;
}
public bool TryGetStartedConfirmation()
{
if (this.Section != "node") return false;
return this.Message == "started";
}
private static readonly Regex PortParser =
new Regex(@"bound_address(es)? {.+\:(?<port>\d+)}");
public bool TryGetPortNumber(out int port)
{
port = 0;
if (this.Section != "http") return false;
var match = PortParser.Match(this.Message);
if (!match.Success) return false;
var portString = match.Groups["port"].Value.Trim();
port = int.Parse(portString);
return true;
}
}
public class ElasticsearchNodeInfo
{
public string Version { get; }
public int? Pid { get; }
public string Build { get; }
public ElasticsearchNodeInfo(string version, string pid, string build)
{
this.Version = version;
if (!string.IsNullOrEmpty(pid))
Pid = int.Parse(pid);
Build = build;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace CalorieCounter.API.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// <copyright file="SparseVectorTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// 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>
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single
{
using LinearAlgebra;
using LinearAlgebra.Single;
using LinearAlgebra.Storage;
using NUnit.Framework;
using System;
using System.Collections.Generic;
/// <summary>
/// Sparse vector tests.
/// </summary>
public class SparseVectorTest : VectorTests
{
/// <summary>
/// Creates a new instance of the Vector class.
/// </summary>
/// <param name="size">The size of the <strong>Vector</strong> to construct.</param>
/// <returns>The new <c>Vector</c>.</returns>
protected override Vector<float> CreateVector(int size)
{
return new SparseVector(size);
}
/// <summary>
/// Creates a new instance of the Vector class.
/// </summary>
/// <param name="data">The array to create this vector from.</param>
/// <returns>The new <c>Vector</c>.</returns>
protected override Vector<float> CreateVector(IList<float> data)
{
var vector = new SparseVector(data.Count);
for (var index = 0; index < data.Count; index++)
{
vector[index] = data[index];
}
return vector;
}
/// <summary>
/// Can create a sparse vector form array.
/// </summary>
[Test]
public void CanCreateSparseVectorFromArray()
{
var data = new float[Data.Length];
Array.Copy(Data, data, Data.Length);
var vector = SparseVector.OfEnumerable(data);
for (var i = 0; i < data.Length; i++)
{
Assert.AreEqual(data[i], vector[i]);
}
}
/// <summary>
/// Can create a sparse vector from another sparse vector.
/// </summary>
[Test]
public void CanCreateSparseVectorFromAnotherSparseVector()
{
var vector = SparseVector.OfEnumerable(Data);
var other = SparseVector.OfVector(vector);
Assert.AreNotSame(vector, other);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(vector[i], other[i]);
}
}
/// <summary>
/// Can create a sparse vector from another vector.
/// </summary>
[Test]
public void CanCreateSparseVectorFromAnotherVector()
{
var vector = (Vector<float>)SparseVector.OfEnumerable(Data);
var other = SparseVector.OfVector(vector);
Assert.AreNotSame(vector, other);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(vector[i], other[i]);
}
}
/// <summary>
/// Can create a sparse vector from user defined vector.
/// </summary>
[Test]
public void CanCreateSparseVectorFromUserDefinedVector()
{
var vector = new UserDefinedVector(Data);
var other = SparseVector.OfVector(vector);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(vector[i], other[i]);
}
}
/// <summary>
/// Can create a sparse matrix.
/// </summary>
[Test]
public void CanCreateSparseMatrix()
{
var vector = new SparseVector(3);
var matrix = Matrix<float>.Build.SameAs(vector, 2, 3);
Assert.IsInstanceOf<SparseMatrix>(matrix);
Assert.AreEqual(2, matrix.RowCount);
Assert.AreEqual(3, matrix.ColumnCount);
}
/// <summary>
/// Can convert a sparse vector to an array.
/// </summary>
[Test]
public void CanConvertSparseVectorToArray()
{
var vector = SparseVector.OfEnumerable(Data);
var array = vector.ToArray();
Assert.IsInstanceOf(typeof (float[]), array);
CollectionAssert.AreEqual(vector, array);
}
/// <summary>
/// Can convert an array to a sparse vector.
/// </summary>
[Test]
public void CanConvertArrayToSparseVector()
{
var array = new[] {0.0f, 1.0f, 2.0f, 3.0f, 4.0f};
var vector = SparseVector.OfEnumerable(array);
Assert.IsInstanceOf(typeof (SparseVector), vector);
CollectionAssert.AreEqual(vector, array);
}
/// <summary>
/// Can multiply a sparse vector by a scalar using "*" operator.
/// </summary>
[Test]
public void CanMultiplySparseVectorByScalarUsingOperators()
{
var vector = SparseVector.OfEnumerable(Data);
vector = vector*2.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i]*2.0f, vector[i]);
}
vector = vector*1.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i]*2.0f, vector[i]);
}
vector = SparseVector.OfEnumerable(Data);
vector = 2.0f*vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i]*2.0f, vector[i]);
}
vector = 1.0f*vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i]*2.0f, vector[i]);
}
}
/// <summary>
/// Can divide a sparse vector by a scalar using "/" operator.
/// </summary>
[Test]
public void CanDivideSparseVectorByScalarUsingOperators()
{
var vector = SparseVector.OfEnumerable(Data);
vector = vector/2.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i]/2.0f, vector[i]);
}
vector = vector/1.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i]/2.0f, vector[i]);
}
}
/// <summary>
/// Can calculate an outer product for a sparse vector.
/// </summary>
[Test]
public void CanCalculateOuterProductForSparseVector()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
var m = Vector<float>.OuterProduct(vector1, vector2);
for (var i = 0; i < vector1.Count; i++)
{
for (var j = 0; j < vector2.Count; j++)
{
Assert.AreEqual(m[i, j], vector1[i]*vector2[j]);
}
}
}
/// <summary>
/// Check sparse mechanism by setting values.
/// </summary>
[Test]
public void CheckSparseMechanismBySettingValues()
{
var vector = new SparseVector(10000);
var storage = (SparseVectorStorage<float>) vector.Storage;
// Add non-zero elements
vector[200] = 1.5f;
Assert.AreEqual(1.5f, vector[200]);
Assert.AreEqual(1, storage.ValueCount);
vector[500] = 3.5f;
Assert.AreEqual(3.5f, vector[500]);
Assert.AreEqual(2, storage.ValueCount);
vector[800] = 5.5f;
Assert.AreEqual(5.5f, vector[800]);
Assert.AreEqual(3, storage.ValueCount);
vector[0] = 7.5f;
Assert.AreEqual(7.5f, vector[0]);
Assert.AreEqual(4, storage.ValueCount);
// Remove non-zero elements
vector[200] = 0;
Assert.AreEqual(0, vector[200]);
Assert.AreEqual(3, storage.ValueCount);
vector[500] = 0;
Assert.AreEqual(0, vector[500]);
Assert.AreEqual(2, storage.ValueCount);
vector[800] = 0;
Assert.AreEqual(0, vector[800]);
Assert.AreEqual(1, storage.ValueCount);
vector[0] = 0;
Assert.AreEqual(0, vector[0]);
Assert.AreEqual(0, storage.ValueCount);
}
/// <summary>
/// Check sparse mechanism by zero multiply.
/// </summary>
[Test]
public void CheckSparseMechanismByZeroMultiply()
{
var vector = new SparseVector(10000);
// Add non-zero elements
vector[200] = 1.5f;
vector[500] = 3.5f;
vector[800] = 5.5f;
vector[0] = 7.5f;
// Multiply by 0
vector *= 0;
var storage = (SparseVectorStorage<float>) vector.Storage;
Assert.AreEqual(0, vector[200]);
Assert.AreEqual(0, vector[500]);
Assert.AreEqual(0, vector[800]);
Assert.AreEqual(0, vector[0]);
Assert.AreEqual(0, storage.ValueCount);
}
/// <summary>
/// Can calculate a dot product of two sparse vectors.
/// </summary>
[Test]
public void CanDotProductOfTwoSparseVectors()
{
var vectorA = new SparseVector(10000);
vectorA[200] = 1;
vectorA[500] = 3;
vectorA[800] = 5;
vectorA[100] = 7;
vectorA[900] = 9;
var vectorB = new SparseVector(10000);
vectorB[300] = 3;
vectorB[500] = 5;
vectorB[800] = 7;
Assert.AreEqual(50.0f, vectorA.DotProduct(vectorB));
}
/// <summary>
/// Can pointwise multiple a sparse vector.
/// </summary>
[Test]
public void CanPointwiseMultiplySparseVector()
{
var zeroArray = new[] {0.0f, 1.0f, 0.0f, 1.0f, 0.0f};
var vector1 = SparseVector.OfEnumerable(Data);
var vector2 = SparseVector.OfEnumerable(zeroArray);
var result = new SparseVector(vector1.Count);
vector1.PointwiseMultiply(vector2, result);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i]*zeroArray[i], result[i]);
}
var resultStorage = (SparseVectorStorage<float>) result.Storage;
Assert.AreEqual(2, resultStorage.ValueCount);
}
/// <summary>
/// Test for issues #52. When setting previous non-zero values to zero,
/// DoMultiply would copy non-zero values to the result, but use the
/// length of nonzerovalues instead of NonZerosCount.
/// </summary>
[Test]
public void CanScaleAVectorWhenSettingPreviousNonzeroElementsToZero()
{
var vector = new SparseVector(20);
vector[10] = 1.0f;
vector[11] = 2.0f;
vector[11] = 0.0f;
var scaled = new SparseVector(20);
vector.Multiply(3.0f, scaled);
Assert.AreEqual(3.0f, scaled[10]);
Assert.AreEqual(0.0f, scaled[11]);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Loon.Utils;
namespace Loon.Net
{
public class Base64Coder
{
private const int BASELENGTH = 255;
private const int LOOKUPLENGTH = 64;
private const int TWENTYFOURBITGROUP = 24;
private const int EIGHTBIT = 8;
private const int SIXTEENBIT = 16;
private const int FOURBYTE = 4;
private const int SIGN = -128;
private const byte PAD = (byte) '=';
private static byte[] BASE64_ALPHABET;
private static byte[] LOOKUP_BASE64_ALPHABET;
private Base64Coder() {
}
public static byte[] FromBinHexString(string s)
{
char[] chars = s.ToCharArray();
byte[] bytes = new byte[chars.Length / 2 + chars.Length % 2];
FromBinHexString(chars, 0, chars.Length, bytes);
return bytes;
}
public static int FromBinHexString(char[] chars, int offset,
int charLength, byte[] buffer)
{
int bufIndex = offset;
for (int i = 0; i < charLength - 1; i += 2)
{
buffer[bufIndex] = (chars[i] > '9' ? (byte)(chars[i] - 'A' + 10)
: (byte)(chars[i] - '0'));
buffer[bufIndex] <<= 4;
buffer[bufIndex] += chars[i + 1] > '9' ? (byte)(chars[i + 1] - 'A' + 10)
: (byte)(chars[i + 1] - '0');
bufIndex++;
}
if (charLength % 2 != 0)
buffer[bufIndex++] = (byte)((chars[charLength - 1] > '9' ? (byte)(chars[charLength - 1] - 'A' + 10)
: (byte)(chars[charLength - 1] - '0')) << 4);
return bufIndex - offset;
}
private static void Checking() {
if (BASE64_ALPHABET == null) {
BASE64_ALPHABET = new byte[BASELENGTH];
for (int i = 0; i < BASELENGTH; i++) {
BASE64_ALPHABET[i] = 0;
}
for (int i_0 = 'Z'; i_0 >= 'A'; i_0--) {
BASE64_ALPHABET[i_0] = (byte) (i_0 - 'A');
}
for (int i_1 = 'z'; i_1 >= 'a'; i_1--) {
BASE64_ALPHABET[i_1] = (byte) (i_1 - 'a' + 26);
}
for (int i_2 = '9'; i_2 >= '0'; i_2--) {
BASE64_ALPHABET[i_2] = (byte) (i_2 - '0' + 52);
}
BASE64_ALPHABET['+'] = 62;
BASE64_ALPHABET['/'] = 63;
}
if (LOOKUP_BASE64_ALPHABET == null) {
LOOKUP_BASE64_ALPHABET = new byte[LOOKUPLENGTH];
for (int i_3 = 0; i_3 <= 25; i_3++) {
LOOKUP_BASE64_ALPHABET[i_3] = (byte) ('A' + i_3);
}
for (int i_4 = 26, j = 0; i_4 <= 51; i_4++, j++) {
LOOKUP_BASE64_ALPHABET[i_4] = (byte) ('a' + j);
}
for (int i_5 = 52, j_6 = 0; i_5 <= 61; i_5++, j_6++) {
LOOKUP_BASE64_ALPHABET[i_5] = (byte) ('0' + j_6);
}
LOOKUP_BASE64_ALPHABET[62] = (byte) '+';
LOOKUP_BASE64_ALPHABET[63] = (byte) '/';
}
}
public static bool IsBase64(string v) {
return IsArrayByteBase64(StringUtils.GetAsciiBytes(v));
}
public static bool IsArrayByteBase64(byte[] bytes) {
Checking();
int length = bytes.Length;
if (length == 0) {
return true;
}
for (int i = 0; i < length; i++) {
if (!Base64Coder.IsBase64(bytes[i])) {
return false;
}
}
return true;
}
private static bool IsBase64(byte octect) {
return (octect == PAD || BASE64_ALPHABET[octect] != 0);
}
public static byte[] Encode(byte[] binaryData) {
Checking();
int lengthDataBits = binaryData.Length * EIGHTBIT;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
byte[] encodedData = null;
if (fewerThan24bits != 0) {
encodedData = new byte[(numberTriplets + 1) * 4];
} else {
encodedData = new byte[numberTriplets * 4];
}
byte k = 0;
byte l = 0;
byte b1 = 0;
byte b2 = 0;
byte b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
int i = 0;
for (i = 0; i < numberTriplets; i++) {
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
encodedIndex = i * 4;
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex] = LOOKUP_BASE64_ALPHABET[val1];
encodedData[encodedIndex + 1] = LOOKUP_BASE64_ALPHABET[val2
| (k << 4)];
encodedData[encodedIndex + 2] = LOOKUP_BASE64_ALPHABET[(l << 2)
| val3];
encodedData[encodedIndex + 3] = LOOKUP_BASE64_ALPHABET[b3 & 0x3f];
}
dataIndex = i * 3;
encodedIndex = i * 4;
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1_0 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex] = LOOKUP_BASE64_ALPHABET[val1_0];
encodedData[encodedIndex + 1] = LOOKUP_BASE64_ALPHABET[k << 4];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1_1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2_2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex] = LOOKUP_BASE64_ALPHABET[val1_1];
encodedData[encodedIndex + 1] = LOOKUP_BASE64_ALPHABET[val2_2
| (k << 4)];
encodedData[encodedIndex + 2] = LOOKUP_BASE64_ALPHABET[l << 2];
encodedData[encodedIndex + 3] = PAD;
}
return encodedData;
}
public static byte[] Decode(byte[] base64Data) {
Checking();
if (base64Data.Length == 0) {
return new byte[0];
}
int numberQuadruple = base64Data.Length / FOURBYTE;
byte[] decodedData = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
int encodedIndex = 0;
int dataIndex = 0;
{
int lastData = base64Data.Length;
while (base64Data[lastData - 1] == PAD) {
if (--lastData == 0) {
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++) {
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = BASE64_ALPHABET[base64Data[dataIndex]];
b2 = BASE64_ALPHABET[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD) {
b3 = BASE64_ALPHABET[marker0];
b4 = BASE64_ALPHABET[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
} else if (marker0 == PAD) {
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
} else if (marker1 == PAD) {
b3 = BASE64_ALPHABET[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
public static byte[] DecodeBase64(char[] data) {
Checking();
int size = data.Length;
int temp = size;
for (int ix = 0; ix < data.Length; ix++) {
if ((data[ix] > 255) || BASE64_ALPHABET[data[ix]] < 0) {
--temp;
}
}
int len = (temp / 4) * 3;
if ((temp % 4) == 3) {
len += 2;
}
if ((temp % 4) == 2) {
len += 1;
}
byte[] xout = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix_0 = 0; ix_0 < size; ix_0++) {
int value_ren = (data[ix_0] > 255) ? 0: (byte) (BASE64_ALPHABET[data[ix_0]]);
if (value_ren >= 0) {
accum <<= 6;
shift += 6;
accum |= value_ren;
if (shift >= 8) {
shift -= 8;
xout[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != xout.Length) {
throw new Exception("index != " + xout.Length);
}
return xout;
}
}
}
| |
namespace Nwc.XmlRpc
{
using System;
using System.Collections;
using System.Reflection;
/// <summary> XML-RPC System object implementation of extended specifications.</summary>
[XmlRpcExposed]
public class XmlRpcSystemObject
{
private XmlRpcServer _server;
static private IDictionary _methodHelp = new Hashtable();
/// <summary>Static <c>IDictionary</c> to hold mappings of method name to associated documentation String</summary>
static public IDictionary MethodHelp {
get { return _methodHelp; }
}
/// <summary>Constructor.</summary>
/// <param name="server"><c>XmlRpcServer</c> server to be the system object for.</param>
public XmlRpcSystemObject(XmlRpcServer server)
{
_server = server;
server.Add("system",this);
_methodHelp.Add(this.GetType().FullName + ".methodHelp", "Return a string description.");
}
/// <summary>Invoke a method on a given object.</summary>
/// <remarks>Using reflection, and respecting the <c>XmlRpcExposed</c> attribute,
/// invoke the <paramref>methodName</paramref> method on the <paramref>target</paramref>
/// instance with the <paramref>parameters</paramref> provided. All this packages other <c>Invoke</c> methods
/// end up calling this.</remarks>
/// <returns><c>Object</c> the value the invoked method returns.</returns>
/// <exception cref="XmlRpcException">If method does not exist, is not exposed, parameters invalid, or invocation
/// results in an exception. Note, the <c>XmlRpcException.Code</c> will indicate cause.</exception>
static public Object Invoke(Object target, String methodName, IList parameters)
{
if (target == null)
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_METHOD,
XmlRpcErrorCodes.SERVER_ERROR_METHOD_MSG + ": Invalid target object.");
Type type = target.GetType();
MethodInfo method = type.GetMethod(methodName);
try
{
if (!XmlRpcExposedAttribute.ExposedMethod(target,methodName))
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_METHOD,
XmlRpcErrorCodes.SERVER_ERROR_METHOD_MSG + ": Method " + methodName + " is not exposed.");
}
catch (MissingMethodException me)
{
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_METHOD,
XmlRpcErrorCodes.SERVER_ERROR_METHOD_MSG + ": " + me.Message);
}
Object[] args = new Object[parameters.Count];
int index = 0;
foreach (Object arg in parameters)
{
args[index] = arg;
index++;
}
try
{
Object retValue = method.Invoke(target, args);
if (retValue == null)
throw new XmlRpcException(XmlRpcErrorCodes.APPLICATION_ERROR,
XmlRpcErrorCodes.APPLICATION_ERROR_MSG + ": Method returned NULL.");
return retValue;
}
catch (XmlRpcException e)
{
throw e;
}
catch (ArgumentException ae)
{
Logger.WriteEntry(XmlRpcErrorCodes.SERVER_ERROR_PARAMS_MSG + ": " + ae.Message,
LogLevel.Information);
String call = methodName + "( ";
foreach (Object o in args)
{
call += o.GetType().Name;
call += " ";
}
call += ")";
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_PARAMS,
XmlRpcErrorCodes.SERVER_ERROR_PARAMS_MSG + ": Arguement type mismatch invoking " + call);
}
catch (TargetParameterCountException tpce)
{
Logger.WriteEntry(XmlRpcErrorCodes.SERVER_ERROR_PARAMS_MSG + ": " + tpce.Message,
LogLevel.Information);
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_PARAMS,
XmlRpcErrorCodes.SERVER_ERROR_PARAMS_MSG + ": Arguement count mismatch invoking " + methodName);
}
catch (TargetInvocationException tie)
{
throw new XmlRpcException(XmlRpcErrorCodes.APPLICATION_ERROR,
XmlRpcErrorCodes.APPLICATION_ERROR_MSG + " Invoked method " + methodName + ": " + tie.Message);
}
}
/// <summary>List methods available on all handlers of this server.</summary>
/// <returns><c>IList</c> An array of <c>Strings</c>, each <c>String</c> will have form "object.method".</returns>
[XmlRpcExposed]
public IList listMethods()
{
IList methods = new ArrayList();
Boolean considerExposure;
foreach (DictionaryEntry handlerEntry in _server)
{
considerExposure = XmlRpcExposedAttribute.IsExposed(handlerEntry.Value.GetType());
foreach (MemberInfo mi in handlerEntry.Value.GetType().GetMembers())
{
if (mi.MemberType != MemberTypes.Method)
continue;
if(!((MethodInfo)mi).IsPublic)
continue;
if (considerExposure && !XmlRpcExposedAttribute.IsExposed(mi))
continue;
methods.Add(handlerEntry.Key + "." + mi.Name);
}
}
return methods;
}
/// <summary>Given a method name return the possible signatures for it.</summary>
/// <param name="name"><c>String</c> The object.method name to look up.</param>
/// <returns><c>IList</c> Of arrays of signatures.</returns>
[XmlRpcExposed]
public IList methodSignature(String name)
{
IList signatures = new ArrayList();
int index = name.IndexOf('.');
if (index < 0)
return signatures;
String oName = name.Substring(0,index);
Object obj = _server[oName];
if (obj == null)
return signatures;
MemberInfo[] mi = obj.GetType().GetMember(name.Substring(index + 1));
if (mi == null || mi.Length != 1) // for now we want a single signature
return signatures;
MethodInfo method;
try
{
method = (MethodInfo)mi[0];
}
catch (Exception e)
{
Logger.WriteEntry("Attempted methodSignature call on " + mi[0] + " caused: " + e,
LogLevel.Information);
return signatures;
}
if (!method.IsPublic)
return signatures;
IList signature = new ArrayList();
signature.Add(method.ReturnType.Name);
foreach (ParameterInfo param in method.GetParameters())
{
signature.Add(param.ParameterType.Name);
}
signatures.Add(signature);
return signatures;
}
/// <summary>Help for given method signature. Not implemented yet.</summary>
/// <param name="name"><c>String</c> The object.method name to look up.</param>
/// <returns><c>String</c> help text. Rich HTML text.</returns>
[XmlRpcExposed]
public String methodHelp(String name)
{
String help = null;
try
{
help = (String)_methodHelp[_server.MethodName(name)];
}
catch (XmlRpcException e)
{
throw e;
}
catch (Exception) { /* ignored */ };
if (help == null)
help = "No help available for: " + name;
return help;
}
/// <summary>Boxcarring support method.</summary>
/// <param name="calls"><c>IList</c> of calls</param>
/// <returns><c>ArrayList</c> of results/faults.</returns>
[XmlRpcExposed]
public IList multiCall(IList calls)
{
IList responses = new ArrayList();
XmlRpcResponse fault = new XmlRpcResponse();
foreach (IDictionary call in calls)
{
try
{
XmlRpcRequest req = new XmlRpcRequest((String)call[XmlRpcXmlTokens.METHOD_NAME],
(ArrayList)call[XmlRpcXmlTokens.PARAMS]);
Object results = _server.Invoke(req);
IList response = new ArrayList();
response.Add(results);
responses.Add(response);
}
catch (XmlRpcException e)
{
fault.SetFault(e.FaultCode, e.FaultString);
responses.Add(fault.Value);
}
catch (Exception e2)
{
fault.SetFault(XmlRpcErrorCodes.APPLICATION_ERROR,
XmlRpcErrorCodes.APPLICATION_ERROR_MSG + ": " + e2.Message);
responses.Add(fault.Value);
}
}
return responses;
}
}
}
| |
// <copyright file="ISavedGameClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace GooglePlayGames.BasicApi.SavedGame
{
using System;
using System.Collections.Generic;
/// <summary>
/// An enum for the different strategies that can be used to resolve saved game conflicts (i.e.
/// conflicts produced by two or more separate writes to the same saved game at once).
/// </summary>
public enum ConflictResolutionStrategy
{
/// <summary>
/// Choose which saved game should be used on the basis of which one has the longest recorded
/// play time. In other words, in the case of a conflicting write, the saved game with the
/// longest play time will be considered cannonical. If play time has not been provided by the
/// developer, or in the case of two saved games with equal play times,
/// <see cref="UseOriginal"/> will be used instead.
/// </summary>
UseLongestPlaytime,
/// <summary>
/// Choose the version of the saved game that existed before any conflicting write occurred.
/// Consider the following case:
/// - An initial version of a save game ("X") is written from a device ("Dev_A")
/// - The save game X is downloaded by another device ("Dev_B").
/// - Dev_A writes a new version of the save game to the cloud ("Y")
/// - Dev_B does not see the new save game Y, and attempts to write a new save game ("Z").
/// - Since Dev_B is performing a write using out of date information, a conflict is generated.
///
/// In this situation, we can resolve the conflict by declaring either keeping Y as the
/// canonical version of the saved game (i.e. choose "original" aka <see cref="UseOriginal"/>),
/// or by overwriting it with conflicting value, Z (i.e. choose "unmerged" aka
/// <see cref="UseUnmerged"/>).
/// </summary>
///
UseOriginal,
/// <summary>
/// See the documentation for <see cref="UseOriginal"/>
/// </summary>
UseUnmerged
}
public enum SavedGameRequestStatus
{
Success = 1,
/// <summary>
/// The request failed due to a timeout.
/// </summary>
///
TimeoutError = -1,
/// <summary>
/// An unexpected internal error. Check the log for error messages.
/// </summary>
///
InternalError = -2,
/// <summary>
/// A error related to authentication. This is probably due to the user being signed out
/// before the request could be issued.
/// </summary>
///
AuthenticationError = -3,
/// <summary>
/// The request failed because it was given bad input (e.g. a filename with 200 characters).
/// </summary>
///
BadInputError = -4
}
public enum SelectUIStatus
{
/// <summary>
/// The user selected a saved game.
/// </summary>
SavedGameSelected = 1,
/// <summary>
/// The user closed the UI without selecting a saved game.
/// </summary>
///
UserClosedUI = 2,
/// <summary>
/// An unexpected internal error. Check the log for error messages.
/// </summary>
///
InternalError = -1,
/// <summary>
/// There was a timeout while displaying the UI.
/// </summary>
///
TimeoutError = -2,
/// <summary>
/// A error related to authentication. This is probably due to the user being signed out
/// before the request could be issued.
/// </summary>
///
AuthenticationError = -3,
/// <summary>
/// The request failed because it was given bad input (e.g. a filename with 200 characters).
/// </summary>
///
BadInputError = -4
}
/// <summary>
/// A delegate that is invoked when we encounter a conflict during execution of
/// <see cref="ISavedGameClient.OpenWithAutomaticConflictResolution"/>. The caller must resolve the
/// conflict using the passed <see cref="ConflictResolver"/>. All passed metadata is open.
/// If <see cref="ISavedGameClient.OpenWithAutomaticConflictResolution"/> was invoked with
/// <c>prefetchDataOnConflict</c> set to <c>true</c>, the <paramref name="originalData"/> and
/// <paramref name="unmergedData"/> will be equal to the binary data of the "original" and
/// "unmerged" saved game respectively (and null otherwise). Since conflict files may be generated
/// by other clients, it is possible that neither of the passed saved games were originally written
/// by the current device. Consequently, any conflict resolution strategy should not rely on local
/// data that is not part of the binary data of the passed saved games - this data will not be
/// present if conflict resolution occurs on a different device. In addition, since a given saved
/// game may have multiple conflicts, this callback must be designed to handle multiple invocations.
/// </summary>
public delegate void ConflictCallback(IConflictResolver resolver, ISavedGameMetadata original,
byte[] originalData, ISavedGameMetadata unmerged, byte[] unmergedData);
/// <summary>
/// The main entry point for interacting with saved games. Saved games are persisted in the cloud
/// along with several game-specific properties (<see cref="ISavedGameMetadata"/> for more
/// information). There are several core concepts involved with saved games:
///
/// <para><strong>Filenames</strong> - act as unique identifiers for saved games. Two devices
/// performing a read or write using the same filename will end up reading or modifying the same
/// file (i.e. filenames are not device specific).
/// </para>
///
/// <para><strong>Saved Game Metadata</strong> are represented by <see cref="ISavedGameMetadata"/>.
/// The instances allow access to metadata properties about the underlying saved game (e.g.
/// description). In addition, metadata functions as a handle that are required to read and
/// manipulate saved game contents. Lastly, metadata may be "Open". Open metadata instances are
/// required to manipulate the underlying binary data of the saved game. See method comments to
/// determine whether a specific method requires or returns an open saved game.
/// </para>
///
/// <para><strong>Conflicts</strong> occur when multiple devices attempt to write to the same file
/// at the same time. The saved game system guarantees that no conflicting writes will be lost or
/// silently overwritten. Instead, they must be handled the next time the file with a conflict is
/// Opened. Conflicts can be handled automatically (
/// <see cref="OpenWithAutomaticConflictResolution"/>) or can be manuallyhandled by the developer
/// (<see cref="OpenWithManualConflictResolution"/>). See the Open methods for more discussion.
/// </para>
///
/// <para>Saved games will generally be used in the following workflow:</para>
/// <list type="number">
/// <item><description>Determine which saved game to use (either using a hardcoded filename or
/// ShowSelectSavedGameUI)</description></item>
/// <item><description>Open the file using OpenWithManualConflictResolution or
/// OpenWithAutomaticConflictResolution</description></item>
/// <item><description>Read the binary data of the saved game using ReadBinaryData handle it
/// as appropriate for your game.</description></item>
/// </item><description>When you have updates, persist them in the cloud using CommitUpdate. Note
/// that writing to the cloud is relatively expensive, and shouldn't be done frequently.
/// </description></item>
/// </list>
///
/// <para>See online <a href="https://developers.google.com/games/services/common/concepts/savedgames">
/// documentation for Saved Games</a> for more information.</para>
/// </summary>
public interface ISavedGameClient
{
/// <summary>
/// Opens the file with the indicated name and data source. If the file has an outstanding
/// conflict, it will be resolved using the specified conflict resolution strategy. The
/// metadata returned by this method will be "Open" - it can be used as a parameter for
/// <see cref="CommitUpdate"/> and <see cref="ResolveConflictByChoosingMetadata"/>.
/// </summary>
/// <param name="filename">The name of the file to open. Filenames must consist of
/// only non-URL reserved characters (i.e. a-z, A-Z, 0-9, or the symbols "-", ".", "_", or "~")
/// be between 1 and 100 characters in length (inclusive).</param>
/// <param name="source">The data source to use. <see cref="DataSource"/> for a description
/// of the available options here.</param>
/// <param name="resolutionStrategy">The conflict resolution that should be used if any
/// conflicts are encountered while opening the file.
/// <see cref="ConflictResolutionStrategy"/> for a description of these strategies.</param>
/// <param name="callback">The callback that is invoked when this operation finishes. The
/// returned metadata will only be non-null if the open succeeded. This callback will always
/// execute on the game thread and the returned metadata (if any) will be "Open".</param>
void OpenWithAutomaticConflictResolution(string filename, DataSource source,
ConflictResolutionStrategy resolutionStrategy,
Action<SavedGameRequestStatus, ISavedGameMetadata> callback);
/// <summary>
/// Opens the file with the indicated name and data source. If there is a conflict that
/// requires resolution, it will be resolved manually using the passed conflict callback. Once
/// all pending conflicts are resolved, the completed callback will be invoked with the
/// retrieved data. In the event of an error, the completed callback will be invoked with the
/// corresponding error status. All callbacks will be executed on the game thread.
/// </summary>
/// <param name="filename">The name of the file to open. Filenames must consist of
/// only non-URL reserved characters (i.e. a-z, A-Z, 0-9, or the symbols "-", ".", "_", or "~")
/// be between 1 and 100 characters in length (inclusive).</param>
/// <param name="source">The data source to use. <see cref="DataSource"/> for a description
/// of the available options here.</param>
/// <param name="prefetchDataOnConflict">If set to <c>true</c>, the data for the two
/// conflicting files will be automatically retrieved and passed as parameters in
/// <paramref name="conflictCallback"/>. If set to <c>false</c>, <c>null</c> binary data
/// will be passed into <paramref name="conflictCallback"/> and the caller will have to fetch
/// it themselves.</param>
/// <param name="conflictCallback">The callback that will be invoked if one or more conflict is
/// encountered while executing this method. Note that more than one conflict may be present
/// and that this callback might be executed more than once to resolve multiple conflicts.
/// This callback is always executed on the game thread.</param>
/// <param name="completedCallback">The callback that is invoked when this operation finishes.
/// The returned metadata will only be non-null if the open succeeded. If an error is
/// encountered during conflict resolution, that error will be reflected here. This callback
/// will always execute on the game thread and the returned metadata (if any) will be "Open".
/// </param>
void OpenWithManualConflictResolution(string filename, DataSource source,
bool prefetchDataOnConflict, ConflictCallback conflictCallback,
Action<SavedGameRequestStatus, ISavedGameMetadata> completedCallback);
/// <summary>
/// Reads the binary data of the passed saved game. The passed metadata must be opened (i.e.
/// <see cref="ISavedGameMetadata.IsOpen"/> returns true). The callback will always be executed
/// on the game thread.
/// </summary>
/// <param name="metadata">The metadata for the saved game whose binary data we want to read.
/// This metadata must be open. If it is not open, the method will immediately fail with status
/// <see cref="BadInputError"/>.
/// </param>
/// <param name="completedCallback">The callback that is invoked when the read finishes. If the
/// read completed without error, the passed status will be <see cref="Success"/> and the passed
/// bytes will correspond to the binary data for the file. In the case of
/// </param>
void ReadBinaryData(ISavedGameMetadata metadata,
Action<SavedGameRequestStatus, byte[]> completedCallback);
/// <summary>
/// Shows the select saved game UI with the indicated configuration. If the user selects a
/// saved game in that UI, it will be returned in the passed callback. This metadata will be
/// unopened and must be passed to either <see cref="OpenWithManualConflictResolution"/> or
/// <see cref="OpenWithAutomaticConflictResolution"/> in order to retrieve the binary data.
/// The callback will always be executed on the game thread.
/// </summary>
/// <param name="uiTitle">The user-visible title of the displayed selection UI.</param>
/// <param name="maxDisplayedSavedGames">The maximum number of saved games the UI may display.
/// This value must be greater than 0.</param>
/// <param name="showCreateSaveUI">If set to <c>true</c>, show UI that will allow the user to
/// create a new saved game.</param>
/// <param name="showDeleteSaveUI">If set to <c>true</c> show UI that will allow the user to
/// delete a saved game.</param>
/// <param name="callback">The callback that is invoked when an error occurs or if the user
/// finishes interacting with the UI. If the user selected a saved game, this will be passed
/// into the callback along with the <see cref="SavedGameSelected"/> status. This saved game
/// will not be Open, and must be opened before it can be written to or its binary data can be
/// read. If the user backs out of the UI without selecting a saved game, this callback will
/// receive <see cref="UserClosedUI"/> and a null saved game. This callback will always execute
/// on the game thread.</param>
void ShowSelectSavedGameUI(string uiTitle, uint maxDisplayedSavedGames, bool showCreateSaveUI,
bool showDeleteSaveUI, Action<SelectUIStatus, ISavedGameMetadata> callback);
/// <summary>
/// Durably commits an update to the passed saved game. When this method returns successfully,
/// the data is durably persisted to disk and will eventually be uploaded to the cloud (in
/// practice, this will happen very quickly unless the device does not have a network
/// connection). If an update to the saved game has occurred after the metadata was retrieved
/// from the cloud, this update will produce a conflict (this commonly occurs if two different
/// devices are writing to the cloud at the same time). All conflicts must be handled the next
/// time this saved game is opened. See <see cref="OpenWithManualConflictResolution"/> and
/// <see cref="OpenWithAutomaticConflictResolution"/> for more information.
/// </summary>
/// <param name="metadata">The metadata for the saved game to update. This metadata must be
/// Open (i.e. <see cref="ISavedGameMetadata.IsOpen/> returns true)."/> If it is not open, the
/// method will immediately fail with status <see cref="BadInputError"/></param>
/// <param name="updateForMetadata">All updates that should be applied to the saved game
/// metadata.</param>
/// <param name="updatedBinaryData">The new binary content of the saved game</param>
/// <param name="callback">The callback that is invoked when this operation finishes.
/// The returned metadata will only be non-null if the commit succeeded. If an error is
/// encountered during conflict resolution, that error will be reflected here. This callback
/// will always execute on the game thread and the returned metadata (if any) will NOT be
/// "Open" (i.e. commiting an update closes the metadata).</param>
void CommitUpdate(ISavedGameMetadata metadata, SavedGameMetadataUpdate updateForMetadata,
byte[] updatedBinaryData, Action<SavedGameRequestStatus, ISavedGameMetadata> callback);
/// <summary>
/// Returns the metadata for all known saved games for this game. All returned saved games are
/// not open, and must be opened before they can be used for writes or binary data reads. The
/// callback will always occur on the game thread.
/// </summary>
/// <param name="source">The data source to use. <see cref="DataSource"/> for a description
/// of the available options here.</param>
/// <param name="callback">The callback that is invoked when this operation finishes.
/// The returned metadata will only be non-empty if the commit succeeded. If an error is
/// encountered during the fetch, that error will be reflected here. This callback
/// will always execute on the game thread and the returned metadata (if any) will NOT be
/// "Open".</param>
void FetchAllSavedGames(DataSource source,
Action<SavedGameRequestStatus, List<ISavedGameMetadata>> callback);
/// <summary>
/// Delete the specified snapshot.
/// This will delete the data of the snapshot locally and on the server.
/// </summary>
/// <param name="metadata">the saved game metadata identifying the data to
/// delete.</param>
void Delete(ISavedGameMetadata metadata);
}
/// <summary>
/// An interface that allows developers to resolve metadata conflicts that may be encountered while
/// opening saved games.
/// </summary>
public interface IConflictResolver
{
/// <summary>
/// Resolves the conflict by choosing the passed metadata to be canonical. The passed metadata
/// must be one of the two instances passed as parameters into <see cref="ConflictCallback"/> -
/// this instance will be kept as the cannonical value in the cloud.
/// </summary>
/// <param name="chosenMetadata">The chosen metadata. This metadata must be open. If it is not
/// open, the invokation of <see cref="OpenWithManualConflictResolution"/> that produced this
/// ConflictResolver will immediately fail with <see cref="BadInputError"/>.</param>
/// <param name="callback">Callback.</param>
void ChooseMetadata(ISavedGameMetadata chosenMetadata);
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using SquabPie.Mono.Collections.Generic;
namespace SquabPie.Mono.Cecil.Cil {
public sealed class ILProcessor {
readonly MethodBody body;
readonly Collection<Instruction> instructions;
public MethodBody Body {
get { return body; }
}
internal ILProcessor (MethodBody body)
{
this.body = body;
this.instructions = body.Instructions;
}
public Instruction Create (OpCode opcode)
{
return Instruction.Create (opcode);
}
public Instruction Create (OpCode opcode, TypeReference type)
{
return Instruction.Create (opcode, type);
}
public Instruction Create (OpCode opcode, CallSite site)
{
return Instruction.Create (opcode, site);
}
public Instruction Create (OpCode opcode, MethodReference method)
{
return Instruction.Create (opcode, method);
}
public Instruction Create (OpCode opcode, FieldReference field)
{
return Instruction.Create (opcode, field);
}
public Instruction Create (OpCode opcode, string value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, sbyte value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, byte value)
{
if (opcode.OperandType == OperandType.ShortInlineVar)
return Instruction.Create (opcode, body.Variables [value]);
if (opcode.OperandType == OperandType.ShortInlineArg)
return Instruction.Create (opcode, body.GetParameter (value));
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, int value)
{
if (opcode.OperandType == OperandType.InlineVar)
return Instruction.Create (opcode, body.Variables [value]);
if (opcode.OperandType == OperandType.InlineArg)
return Instruction.Create (opcode, body.GetParameter (value));
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, long value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, float value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, double value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, Instruction target)
{
return Instruction.Create (opcode, target);
}
public Instruction Create (OpCode opcode, Instruction [] targets)
{
return Instruction.Create (opcode, targets);
}
public Instruction Create (OpCode opcode, VariableDefinition variable)
{
return Instruction.Create (opcode, variable);
}
public Instruction Create (OpCode opcode, ParameterDefinition parameter)
{
return Instruction.Create (opcode, parameter);
}
public void Emit (OpCode opcode)
{
Append (Create (opcode));
}
public void Emit (OpCode opcode, TypeReference type)
{
Append (Create (opcode, type));
}
public void Emit (OpCode opcode, MethodReference method)
{
Append (Create (opcode, method));
}
public void Emit (OpCode opcode, CallSite site)
{
Append (Create (opcode, site));
}
public void Emit (OpCode opcode, FieldReference field)
{
Append (Create (opcode, field));
}
public void Emit (OpCode opcode, string value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, byte value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, sbyte value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, int value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, long value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, float value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, double value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, Instruction target)
{
Append (Create (opcode, target));
}
public void Emit (OpCode opcode, Instruction [] targets)
{
Append (Create (opcode, targets));
}
public void Emit (OpCode opcode, VariableDefinition variable)
{
Append (Create (opcode, variable));
}
public void Emit (OpCode opcode, ParameterDefinition parameter)
{
Append (Create (opcode, parameter));
}
public void InsertBefore (Instruction target, Instruction instruction)
{
if (target == null)
throw new ArgumentNullException ("target");
if (instruction == null)
throw new ArgumentNullException ("instruction");
var index = instructions.IndexOf (target);
if (index == -1)
throw new ArgumentOutOfRangeException ("target");
instructions.Insert (index, instruction);
}
public void InsertAfter (Instruction target, Instruction instruction)
{
if (target == null)
throw new ArgumentNullException ("target");
if (instruction == null)
throw new ArgumentNullException ("instruction");
var index = instructions.IndexOf (target);
if (index == -1)
throw new ArgumentOutOfRangeException ("target");
instructions.Insert (index + 1, instruction);
}
public void Append (Instruction instruction)
{
if (instruction == null)
throw new ArgumentNullException ("instruction");
instructions.Add (instruction);
}
public void Replace (Instruction target, Instruction instruction)
{
if (target == null)
throw new ArgumentNullException ("target");
if (instruction == null)
throw new ArgumentNullException ("instruction");
InsertAfter (target, instruction);
Remove (target);
}
public void Remove (Instruction instruction)
{
if (instruction == null)
throw new ArgumentNullException ("instruction");
if (!instructions.Remove (instruction))
throw new ArgumentOutOfRangeException ("instruction");
}
}
}
| |
/*
* Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using PropertyManager = org.javarosa.core.services.PropertyManager;
using Localization = org.javarosa.core.services.locale.Localization;
using Localizer = org.javarosa.core.services.locale.Localizer;
namespace org.javarosa.core.services.properties
{
/// <summary> A set of rules governing the allowable properties for JavaRosa's
/// core funtionality.
///
/// </summary>
/// <author> ctsims
///
/// </author>
public class JavaRosaPropertyRules : IPropertyRules
{
//UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
internal System.Collections.Hashtable rules;
internal System.Collections.ArrayList readOnlyProperties;
public const System.String DEVICE_ID_PROPERTY = "DeviceID";
public const System.String CURRENT_LOCALE = "cur_locale";
public const System.String LOGS_ENABLED = "logenabled";
public const System.String LOGS_ENABLED_YES = "Enabled";
public const System.String LOGS_ENABLED_NO = "Disabled";
/// <summary>The expected compliance version for the OpenRosa API set *</summary>
public const System.String OPENROSA_API_LEVEL = "jr_openrosa_api";
/// <summary> Creates the JavaRosa set of property rules</summary>
public JavaRosaPropertyRules()
{
//UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
rules = new System.Collections.Hashtable();
readOnlyProperties = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
//DeviceID Property
rules[DEVICE_ID_PROPERTY] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
System.Collections.ArrayList logs = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
logs.Add(LOGS_ENABLED_NO);
logs.Add(LOGS_ENABLED_YES);
rules[LOGS_ENABLED] = logs;
rules[CURRENT_LOCALE] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
rules[OPENROSA_API_LEVEL] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
readOnlyProperties.Add(DEVICE_ID_PROPERTY);
readOnlyProperties.Add(OPENROSA_API_LEVEL);
}
/// <summary>(non-Javadoc)</summary>
/// <seealso cref="org.javarosa.core.services.properties.IPropertyRules.allowableValues(String)">
/// </seealso>
public virtual System.Collections.ArrayList allowableValues(System.String propertyName)
{
if (CURRENT_LOCALE.Equals(propertyName))
{
Localizer l = Localization.GlobalLocalizerAdvanced;
System.Collections.ArrayList v = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
System.String[] locales = l.getAvailableLocales();
for (int i = 0; i < locales.Length; ++i)
{
v.Add(locales[i]);
}
return v;
}
//UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
return (System.Collections.ArrayList)rules[propertyName];
}
/// <summary>(non-Javadoc)</summary>
/// <seealso cref="org.javarosa.core.services.properties.IPropertyRules.checkValueAllowed(String, String)">
/// </seealso>
public virtual bool checkValueAllowed(System.String propertyName, System.String potentialValue)
{
if (CURRENT_LOCALE.Equals(propertyName))
{
return Localization.GlobalLocalizerAdvanced.hasLocale(potentialValue);
}
//UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
System.Collections.ArrayList prop = ((System.Collections.ArrayList)rules[propertyName]);
if (prop.Count != 0)
{
//Check whether this is a dynamic property
if (prop.Count == 1 && checkPropertyAllowed((System.String)prop[0]))
{
// If so, get its list of available values, and see whether the potentival value is acceptable.
return ((System.Collections.ArrayList)PropertyManager._().getProperty((System.String)prop[0])).Contains(potentialValue);
}
else
{
//UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
return ((System.Collections.ArrayList)rules[propertyName]).Contains(potentialValue);
}
}
else
return true;
}
/// <summary>(non-Javadoc)</summary>
/// <seealso cref="org.javarosa.core.services.properties.IPropertyRules.allowableProperties()">
/// </seealso>
public virtual System.Collections.ArrayList allowableProperties()
{
System.Collections.ArrayList propList = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
//UPGRADE_TODO: Method 'java.util.HashMap.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapkeySet'"
System.Collections.IEnumerator iter = new System.Collections.ArrayList(rules.Keys).GetEnumerator();
//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
while (iter.MoveNext())
{
//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
propList.Add(iter.Current);
}
return propList;
}
/// <summary>(non-Javadoc)</summary>
/// <seealso cref="org.javarosa.core.services.properties.IPropertyRules.checkPropertyAllowed)">
/// </seealso>
public virtual bool checkPropertyAllowed(System.String propertyName)
{
//UPGRADE_TODO: Method 'java.util.HashMap.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapkeySet'"
System.Collections.IEnumerator iter = new System.Collections.ArrayList(rules.Keys).GetEnumerator();
//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
while (iter.MoveNext())
{
//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
if (propertyName.Equals(iter.Current))
{
return true;
}
}
return false;
}
/// <summary>(non-Javadoc)</summary>
/// <seealso cref="org.javarosa.core.services.properties.IPropertyRules.checkPropertyUserReadOnly)">
/// </seealso>
public virtual bool checkPropertyUserReadOnly(System.String propertyName)
{
return readOnlyProperties.Contains(propertyName);
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.properties.IPropertyRules#getHumanReadableDescription(java.lang.String)
*/
public virtual System.String getHumanReadableDescription(System.String propertyName)
{
if (DEVICE_ID_PROPERTY.Equals(propertyName))
{
return "Unique Device ID";
}
else if (LOGS_ENABLED.Equals(propertyName))
{
return "Device Logging";
}
else if (CURRENT_LOCALE.Equals(propertyName))
{
return Localization.get_Renamed("settings.language");
}
else if (OPENROSA_API_LEVEL.Equals(propertyName))
{
return "OpenRosa API Level";
}
return propertyName;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.properties.IPropertyRules#getHumanReadableValue(java.lang.String, java.lang.String)
*/
public virtual System.String getHumanReadableValue(System.String propertyName, System.String value_Renamed)
{
if (CURRENT_LOCALE.Equals(propertyName))
{
System.String name = Localization.GlobalLocalizerAdvanced.getText(value_Renamed);
if (name != null)
{
return name;
}
}
return value_Renamed;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.properties.IPropertyRules#handlePropertyChanges(java.lang.String)
*/
public virtual void handlePropertyChanges(System.String propertyName)
{
if (CURRENT_LOCALE.Equals(propertyName))
{
System.String locale = PropertyManager._().getSingularProperty(propertyName);
Localization.Locale = locale;
}
}
}
}
| |
using System;
using UnityEngine;
namespace UnityTools.Base
{
/// <summary>
/// This is a generic Singleton implementation for Monobehaviours.
/// Create a derived class where the type T is the script you want to "Singletonize"
/// Upon loading it will call DontDestroyOnLoad on the gameobject where this script is contained
/// so it persists upon scene changes.
/// </summary>
/// <remarks>
/// DO NOT REDEFINE Awake() Start() or OnDestroy() in derived classes. EVER.
/// Instead, use protected virtual methods:
/// SingletonAwakened()
/// SingletonStarted()
/// SingletonDestroyed()
/// to perform the initialization/cleanup: those methods are guaranteed to only be called once in the
/// entire lifetime of the MonoBehaviour
/// </remarks>
public class MonoBehaviourSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
/// <summary>
/// <c>true</c> if this Singleton Awake() method has already been called by Unity; otherwise, <c>false</c>.
/// </summary>
public static bool IsAwakened { get; private set; }
/// <summary>
/// <c>true</c> if this Singleton Start() method has already been called by Unity; otherwise, <c>false</c>.
/// </summary>
public static bool IsStarted { get; private set; }
/// <summary>
/// <c>true</c> if this Singleton OnDestroy() method has already been called by Unity; otherwise, <c>false</c>.
/// </summary>
public static bool IsDestroyed { get; private set; }
/// <summary>
/// Global access point to the unique instance of this class.
/// </summary>
public static T Instance
{
get
{
if (_instance == null)
{
if (IsDestroyed) return null;
_instance = FindExistingInstance() ?? CreateNewInstance();
}
return _instance;
}
}
#region Singleton Implementation
/// <summary>
/// Holds the unique instance for this class
/// </summary>
private static T _instance;
/// <summary>
/// Finds an existing instance of this singleton in the scene.
/// </summary>
private static T FindExistingInstance()
{
T[] existingInstances = FindObjectsOfType<T>();
// No instance found
if (existingInstances == null || existingInstances.Length == 0) return null;
return existingInstances[0];
}
/// <summary>
/// If no instance of the T MonoBehaviour exists, creates a new GameObject in the scene
/// and adds T to it.
/// </summary>
private static T CreateNewInstance()
{
var containerGO = new GameObject("__" + typeof(T).Name + " (Singleton)");
return containerGO.AddComponent<T>();
}
#endregion
#region Singleton Life-time Management
/// <summary>
/// Unity3D Awake method.
/// </summary>
/// <remarks>
/// This method will only be called once even if multiple instances of the
/// singleton MonoBehaviour exist in the scene.
/// You can override this method in derived classes to customize the initialization of your MonoBehaviour
/// </remarks>
protected virtual void SingletonAwakened() {}
/// <summary>
/// Unity3D Start method.
/// </summary>
/// <remarks>
/// This method will only be called once even if multiple instances of the
/// singleton MonoBehaviour exist in the scene.
/// You can override this method in derived classes to customize the initialization of your MonoBehaviour
/// </remarks>
protected virtual void SingletonStarted() {}
/// <summary>
/// Unity3D OnDestroy method.
/// </summary>
/// <remarks>
/// This method will only be called once even if multiple instances of the
/// singleton MonoBehaviour exist in the scene.
/// You can override this method in derived classes to customize the initialization of your MonoBehaviour
/// </remarks>
protected virtual void SingletonDestroyed() {}
/// <summary>
/// If a duplicated instance of a Singleton MonoBehaviour is loaded into the scene
/// this method will be called instead of SingletonAwakened(). That way you can customize
/// what to do with repeated instances.
/// </summary>
/// <remarks>
/// The default approach is delete the duplicated MonoBehaviour
/// </remarks>
protected virtual void NotifyInstanceRepeated()
{
Component.Destroy(this.GetComponent<T>());
}
#endregion
#region Unity3d Messages - DO NOT OVERRRIDE NOR IMPLEMENT THESE METHODS in child classes!
void Awake()
{
T thisInstance = this.GetComponent<T>();
// Initialize the singleton
if (_instance == null)
{
_instance = thisInstance;
DontDestroyOnLoad(_instance.gameObject);
}
// She singleton if was already living in a GameObject
else if(thisInstance != _instance)
{
PrintWarn(string.Format(
"Found a duplicated instance of a Singleton with type {0} in the GameObject {1} that will be ignored",
this.GetType(), this.gameObject.name));
NotifyInstanceRepeated();
return;
}
if(!IsAwakened)
{
PrintLog(string.Format(
"Awake() Singleton with type {0} in the GameObject {1}",
this.GetType(), this.gameObject.name));
SingletonAwakened();
IsAwakened = true;
}
}
void Start()
{
// do not start it twice
if(IsStarted) return;
PrintLog(string.Format(
"Start() Singleton with type {0} in the GameObject {1}",
this.GetType(), this.gameObject.name));
SingletonStarted();
IsStarted = true;
}
void OnDestroy()
{
// Here we are dealing with a duplicate so we don't need to shut the singleton down
if (this != _instance) return;
// Flag set when Unity sends the message OnDestroy to this Component.
// This is needed because there is a chance that the GameObject A holding this singleton
// is destroyed before some other GameObject B that also access this singleton when B is being destroyed.
// If that happens as the singleton instance whould be null a new singleton would be created
// including a brand new GO to which the singleton instance is attached to.
// As this is happening during the Unity app shutdown for some reason the newly created GO
// is kept in the scene when you exist play mode, so this prevent filling your scene with remmants
// of singleton GameObjects
IsDestroyed = true;
PrintLog(string.Format(
"Destroy() Singleton with type {0} in the GameObject {1}",
this.GetType(), this.gameObject.name));
SingletonDestroyed();
}
#endregion
#region Debug Methods (available in child classes)
[Header("Debug")]
/// <summary>
/// Set this to true either by code or in the inspector to print trace log messages
/// </summary>
public bool PrintTrace = false;
protected void PrintLog(string str, params object[] args)
{
Print(UnityEngine.Debug.Log, PrintTrace, str, args);
}
protected void PrintWarn(string str, params object[] args)
{
Print(UnityEngine.Debug.LogWarning, PrintTrace, str, args);
}
protected void PrintError(string str, params object[] args)
{
Print(UnityEngine.Debug.LogError, true, str, args);
}
private void Print(Action<string> printFunc, bool doPrint, string str, params object[] args)
{
if(doPrint)
{
printFunc(string.Format(
"<b>[{0}][{1}] {2} </b>",
Time.frameCount,
this.GetType().Name.ToUpper(),
string.Format(str, args)
)
);
}
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// individual machine serving provisioning (block) data
/// First published in XenServer 7.1.
/// </summary>
public partial class PVS_server : XenObject<PVS_server>
{
#region Constructors
public PVS_server()
{
}
public PVS_server(string uuid,
string[] addresses,
long first_port,
long last_port,
XenRef<PVS_site> site)
{
this.uuid = uuid;
this.addresses = addresses;
this.first_port = first_port;
this.last_port = last_port;
this.site = site;
}
/// <summary>
/// Creates a new PVS_server from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PVS_server(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new PVS_server from a Proxy_PVS_server.
/// </summary>
/// <param name="proxy"></param>
public PVS_server(Proxy_PVS_server proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PVS_server.
/// </summary>
public override void UpdateFrom(PVS_server update)
{
uuid = update.uuid;
addresses = update.addresses;
first_port = update.first_port;
last_port = update.last_port;
site = update.site;
}
internal void UpdateFrom(Proxy_PVS_server proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
addresses = proxy.addresses == null ? new string[] {} : (string [])proxy.addresses;
first_port = proxy.first_port == null ? 0 : long.Parse(proxy.first_port);
last_port = proxy.last_port == null ? 0 : long.Parse(proxy.last_port);
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
}
public Proxy_PVS_server ToProxy()
{
Proxy_PVS_server result_ = new Proxy_PVS_server();
result_.uuid = uuid ?? "";
result_.addresses = addresses;
result_.first_port = first_port.ToString();
result_.last_port = last_port.ToString();
result_.site = site ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PVS_server
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("addresses"))
addresses = Marshalling.ParseStringArray(table, "addresses");
if (table.ContainsKey("first_port"))
first_port = Marshalling.ParseLong(table, "first_port");
if (table.ContainsKey("last_port"))
last_port = Marshalling.ParseLong(table, "last_port");
if (table.ContainsKey("site"))
site = Marshalling.ParseRef<PVS_site>(table, "site");
}
public bool DeepEquals(PVS_server other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._addresses, other._addresses) &&
Helper.AreEqual2(this._first_port, other._first_port) &&
Helper.AreEqual2(this._last_port, other._last_port) &&
Helper.AreEqual2(this._site, other._site);
}
internal static List<PVS_server> ProxyArrayToObjectList(Proxy_PVS_server[] input)
{
var result = new List<PVS_server>();
foreach (var item in input)
result.Add(new PVS_server(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, PVS_server server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_server.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static PVS_server get_record(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_record(session.opaque_ref, _pvs_server);
else
return new PVS_server(session.XmlRpcProxy.pvs_server_get_record(session.opaque_ref, _pvs_server ?? "").parse());
}
/// <summary>
/// Get a reference to the PVS_server instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_server> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PVS_server>.Create(session.XmlRpcProxy.pvs_server_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_server.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static string get_uuid(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_uuid(session.opaque_ref, _pvs_server);
else
return session.XmlRpcProxy.pvs_server_get_uuid(session.opaque_ref, _pvs_server ?? "").parse();
}
/// <summary>
/// Get the addresses field of the given PVS_server.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static string[] get_addresses(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_addresses(session.opaque_ref, _pvs_server);
else
return (string [])session.XmlRpcProxy.pvs_server_get_addresses(session.opaque_ref, _pvs_server ?? "").parse();
}
/// <summary>
/// Get the first_port field of the given PVS_server.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static long get_first_port(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_first_port(session.opaque_ref, _pvs_server);
else
return long.Parse(session.XmlRpcProxy.pvs_server_get_first_port(session.opaque_ref, _pvs_server ?? "").parse());
}
/// <summary>
/// Get the last_port field of the given PVS_server.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static long get_last_port(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_last_port(session.opaque_ref, _pvs_server);
else
return long.Parse(session.XmlRpcProxy.pvs_server_get_last_port(session.opaque_ref, _pvs_server ?? "").parse());
}
/// <summary>
/// Get the site field of the given PVS_server.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_site(session.opaque_ref, _pvs_server);
else
return XenRef<PVS_site>.Create(session.XmlRpcProxy.pvs_server_get_site(session.opaque_ref, _pvs_server ?? "").parse());
}
/// <summary>
/// introduce new PVS server
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_addresses">IPv4 addresses of the server</param>
/// <param name="_first_port">first UDP port accepted by this server</param>
/// <param name="_last_port">last UDP port accepted by this server</param>
/// <param name="_site">PVS site this server is a part of</param>
public static XenRef<PVS_server> introduce(Session session, string[] _addresses, long _first_port, long _last_port, string _site)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_introduce(session.opaque_ref, _addresses, _first_port, _last_port, _site);
else
return XenRef<PVS_server>.Create(session.XmlRpcProxy.pvs_server_introduce(session.opaque_ref, _addresses, _first_port.ToString(), _last_port.ToString(), _site ?? "").parse());
}
/// <summary>
/// introduce new PVS server
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_addresses">IPv4 addresses of the server</param>
/// <param name="_first_port">first UDP port accepted by this server</param>
/// <param name="_last_port">last UDP port accepted by this server</param>
/// <param name="_site">PVS site this server is a part of</param>
public static XenRef<Task> async_introduce(Session session, string[] _addresses, long _first_port, long _last_port, string _site)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_server_introduce(session.opaque_ref, _addresses, _first_port, _last_port, _site);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pvs_server_introduce(session.opaque_ref, _addresses, _first_port.ToString(), _last_port.ToString(), _site ?? "").parse());
}
/// <summary>
/// forget a PVS server
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static void forget(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pvs_server_forget(session.opaque_ref, _pvs_server);
else
session.XmlRpcProxy.pvs_server_forget(session.opaque_ref, _pvs_server ?? "").parse();
}
/// <summary>
/// forget a PVS server
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_server">The opaque_ref of the given pvs_server</param>
public static XenRef<Task> async_forget(Session session, string _pvs_server)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pvs_server_forget(session.opaque_ref, _pvs_server);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pvs_server_forget(session.opaque_ref, _pvs_server ?? "").parse());
}
/// <summary>
/// Return a list of all the PVS_servers known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_server>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_all(session.opaque_ref);
else
return XenRef<PVS_server>.Create(session.XmlRpcProxy.pvs_server_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PVS_server Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_server>, PVS_server> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pvs_server_get_all_records(session.opaque_ref);
else
return XenRef<PVS_server>.Create<Proxy_PVS_server>(session.XmlRpcProxy.pvs_server_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// IPv4 addresses of this server
/// </summary>
public virtual string[] addresses
{
get { return _addresses; }
set
{
if (!Helper.AreEqual(value, _addresses))
{
_addresses = value;
NotifyPropertyChanged("addresses");
}
}
}
private string[] _addresses = {};
/// <summary>
/// First UDP port accepted by this server
/// </summary>
public virtual long first_port
{
get { return _first_port; }
set
{
if (!Helper.AreEqual(value, _first_port))
{
_first_port = value;
NotifyPropertyChanged("first_port");
}
}
}
private long _first_port = 0;
/// <summary>
/// Last UDP port accepted by this server
/// </summary>
public virtual long last_port
{
get { return _last_port; }
set
{
if (!Helper.AreEqual(value, _last_port))
{
_last_port = value;
NotifyPropertyChanged("last_port");
}
}
}
private long _last_port = 0;
/// <summary>
/// PVS site this server is part of
/// </summary>
[JsonConverter(typeof(XenRefConverter<PVS_site>))]
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL");
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Common.Util;
using System.Collections.Generic;
using Alachisoft.NCache.Runtime.Caching;
using Alachisoft.NCache.Management.ServiceControl;
using System.Threading;
using System.Net;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Common.FeatureUsageData;
using Alachisoft.NCache.Management;
namespace Alachisoft.NCache.SocketServer.Command
{
class InitializeCommand : CommandBase
{
private struct CommandInfo
{
public string RequestId;
public string CacheId;
public string UserName;
public string Password;
public bool IsDotNetClient;
public string ClientID;
public string LicenceCode;
public int clientVersion;
public Runtime.Caching.ClientInfo clientInfo;
public byte[] UserNameBinary;
public byte[] PassworNameBinary;
public string clientIP;
public bool isAzureClient;
public int CommandVersion;
public string clientEditionId;
public bool SecureConnectionEnabled;
public int operationTimeout;
internal int cores;
}
private bool requestLoggingEnabled;
//PROTOBUF
public InitializeCommand(bool requestLoggingEnabled)
{
this.requestLoggingEnabled = requestLoggingEnabled;
}
public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command)
{
CommandInfo cmdInfo;
try
{
cmdInfo = ParseCommand(command, clientManager);
}
catch (Exception exc)
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("InitializeCommand.Execute", clientManager.ClientSocket.RemoteEndPoint.ToString() + " parsing error " + exc.ToString());
if (!base.immatureId.Equals("-2"))
{
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithoutType(exc, command.requestID, command.commandID));
}
return;
}
try
{
clientManager.ClientID = cmdInfo.ClientID;
clientManager.IsDotNetClient = cmdInfo.IsDotNetClient;
clientManager.SupportAcknowledgement = cmdInfo.CommandVersion >= 2 && requestLoggingEnabled;
clientManager.ClientVersion = cmdInfo.clientVersion;
clientManager.SecureConnectionEnabled = cmdInfo.SecureConnectionEnabled;
cmdInfo.clientInfo.ClientVersion = cmdInfo.clientVersion;
GetClientUsage(clientManager, cmdInfo);
ClientLedger.Instance.RegisterClientForCache(clientManager.ClientAddress, clientManager.ClientID);
//Older client do not send operation timeout
clientManager.RequestTimeout = cmdInfo.operationTimeout != -1? cmdInfo.operationTimeout: 90* 1000;
clientManager.CmdExecuter = new NCache(cmdInfo.CacheId, cmdInfo.IsDotNetClient, clientManager, cmdInfo.LicenceCode, cmdInfo.UserName, cmdInfo.Password, cmdInfo.UserNameBinary, cmdInfo.PassworNameBinary, cmdInfo.clientInfo);
if (clientManager.PoolManager == null)
{
var shouldCreateFakePools = (clientManager.CmdExecuter as NCache).Cache.TransactionalPoolManager.IsUsingFakePools;
clientManager.ConnectionManager.CreatePools(shouldCreateFakePools);
}
clientManager.CacheTransactionalPool = ((NCache)clientManager.CmdExecuter).Cache.Context.TransactionalPoolManager;
clientManager.CacheFakePool = ((NCache)clientManager.CmdExecuter).Cache.Context.FakeObjectPool;
ClientManager cmgr = null;
int noOfConnectedClients = 0;
lock (ConnectionManager.ConnectionTable)
{
if (ConnectionManager.ConnectionTable.Contains(clientManager.ClientID))
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("InitializeCommand.Execute", "Another client with same clientID exists. Client ID is " + clientManager.ClientID);
cmgr = ConnectionManager.ConnectionTable[clientManager.ClientID] as ClientManager;
ConnectionManager.ConnectionTable.Remove(clientManager.ClientID);
}
ConnectionManager.ConnectionTable.Add(clientManager.ClientID, clientManager);
clientManager.ConnectionManager.PerfStatsColl.ConncetedClients = noOfConnectedClients = ConnectionManager.ConnectionTable.Count;
}
clientManager.CmdExecuter.OnClientConnected(clientManager.ClientID, cmdInfo.CacheId, cmdInfo.clientInfo, noOfConnectedClients);
try
{
if (cmgr != null)
{
cmgr.RaiseClientDisconnectEvent = false;
cmgr.Dispose();
}
}
catch (Exception e)
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("InitializeCommand.Execute", " an error occurred while forcefully disposing a client. " + e.ToString());
}
clientManager.EventQueue = new EventsQueue();
clientManager.SlaveId = clientManager.ConnectionManager.EventsAndCallbackQueue.RegisterSlaveQueue(clientManager.EventQueue, clientManager.ClientID); // register queue with distributed queue.
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("InitializeCommand.Execute", clientManager.ClientID + " is connected to " + cmdInfo.CacheId);
//PROTOBUF:RESPONSE
Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
Alachisoft.NCache.Common.Protobuf.InitializeCacheResponse initializeCacheResponse = new Alachisoft.NCache.Common.Protobuf.InitializeCacheResponse();
response.requestId = Convert.ToInt64(cmdInfo.RequestId);
response.commandID = command.commandID;
response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.INIT;
response.initCache = initializeCacheResponse;
initializeCacheResponse.requestLoggingEnabled = this.requestLoggingEnabled;
initializeCacheResponse.isPersistenceEnabled = ((NCache)clientManager.CmdExecuter).Cache.IsPersistEnabled;
initializeCacheResponse.persistenceInterval = ((NCache)clientManager.CmdExecuter).Cache.PersistenceInterval;
initializeCacheResponse.cacheType = ((NCache)clientManager.CmdExecuter).Cache.CacheType.ToLower();
#if SERVER
initializeCacheResponse.targetCacheUniqueID = ((NCache)(clientManager.CmdExecuter)).Cache.TargetCacheUniqueID;
#endif
//if graceful shutdown is happening on any server node...
List<Alachisoft.NCache.Caching.ShutDownServerInfo> shutDownServers = ((NCache)(clientManager.CmdExecuter)).Cache.GetShutDownServers();
if (shutDownServers != null && shutDownServers.Count > 0)
{
initializeCacheResponse.isShutDownProcessEnabled = true;
foreach (Alachisoft.NCache.Caching.ShutDownServerInfo ssInfo in shutDownServers)
{
Alachisoft.NCache.Common.Protobuf.ShutDownServerInfo server = new Alachisoft.NCache.Common.Protobuf.ShutDownServerInfo();
server.serverIP = ssInfo.RenderedAddress.IpAddress.ToString();
server.port = ssInfo.RenderedAddress.Port;
server.uniqueKey = ssInfo.UniqueBlockingId;
server.timeoutInterval = ssInfo.BlockInterval;
initializeCacheResponse.shutDownServerInfo.Add(server);
}
}
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
if (SocketServer.Logger.IsDetailedLogsEnabled) SocketServer.Logger.NCacheLog.Info("InitializeCommand.Execute", clientManager.ClientSocket.RemoteEndPoint.ToString() + " : " + clientManager.ClientID + " connected to " + cmdInfo.CacheId);
}
catch (SecurityException sec)
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("InitializeCommand.Execute", clientManager.ClientSocket.RemoteEndPoint.ToString() + " : " + clientManager.ClientID + " failed to connect to " + cmdInfo.CacheId + " Error: " + sec.ToString());
//PROTOBUF:RESPONSE
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithoutType(sec, command.requestID,command.commandID));
}
catch (Exception exc)
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("InitializeCommand.Execute", clientManager.ClientSocket.RemoteEndPoint.ToString() + " : " + clientManager.ClientID + " failed to connect to " + cmdInfo.CacheId + " Error: " + exc.ToString());
//PROTOBUF:RESPONSE
_serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithoutType(exc, command.requestID, command.commandID));
}
}
private bool IsServerAsClient(Node[] server, string clientIp)
{
if (server != null)
{
foreach (Node node in server)
{
if (node.Address.IpAddress.ToString().Equals(clientIp))
{
return true;
}
}
}
return false;
}
private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager)
{
CommandInfo cmdInfo = new CommandInfo();
Alachisoft.NCache.Common.Protobuf.InitCommand initCommand = command.initCommand;
cmdInfo.CacheId = initCommand.cacheId;
cmdInfo.ClientID = initCommand.clientId;
cmdInfo.IsDotNetClient = initCommand.isDotnetClient;
cmdInfo.LicenceCode = initCommand.licenceCode;
cmdInfo.operationTimeout = initCommand.operationTimeout;
cmdInfo.Password = initCommand.pwd;
cmdInfo.PassworNameBinary = initCommand.binaryPwd;
cmdInfo.RequestId = initCommand.requestId.ToString();
cmdInfo.UserName = initCommand.userId;
cmdInfo.UserNameBinary = initCommand.binaryUserid;
cmdInfo.clientVersion = initCommand.clientVersion;
cmdInfo.clientIP = initCommand.clientIP;
cmdInfo.isAzureClient = initCommand.isAzureClient;
clientManager.IsAzureClient = initCommand.isAzureClient;
cmdInfo.clientEditionId = initCommand.clientEditionId;
cmdInfo.SecureConnectionEnabled = initCommand.secureConnectionEnabled;
cmdInfo.CommandVersion = command.commandVersion;
if (cmdInfo.clientVersion < 4620)
{
cmdInfo.clientInfo = ClientInfo.TryParseLegacyClientID(initCommand.clientId);
if (cmdInfo.clientInfo != null)
{
cmdInfo.clientInfo.IPAddress = clientManager.ClientAddress;
cmdInfo.clientInfo.ClientID = "Legacy Client (AppName Not Supported)";
}
}
else
{
cmdInfo.clientInfo = new Runtime.Caching.ClientInfo();
cmdInfo.clientInfo.ProcessID = command.initCommand.clientInfo.processId;
cmdInfo.clientInfo.AppName = command.initCommand.clientInfo.appName;
cmdInfo.clientInfo.ClientID = command.initCommand.clientInfo.clientId;
cmdInfo.clientInfo.MacAddress = command.initCommand.clientInfo.macAddress;
cmdInfo.clientInfo.MachineName = command.initCommand.clientInfo.machineName;
cmdInfo.clientInfo.IPAddress = clientManager.ClientAddress;
cmdInfo.clientInfo.Cores = initCommand.clientInfo.cores;
cmdInfo.clientInfo.Memory = command.initCommand.memory;
cmdInfo.clientInfo.IsDotNetCore = command.initCommand.isDotNetCoreClient;
cmdInfo.clientInfo.OperationSystem = command.initCommand.OperationSystem;
}
return cmdInfo;
}
private void GetClientUsage(ClientManager clientManager, CommandInfo cmdInfo)
{
ClientProfile clientProfile = new ClientProfile();
if (clientManager.IsDotNetClient)
clientProfile.Platform = ".net";
else
clientProfile.Platform = "java";
if (cmdInfo.clientInfo.IsDotNetCore)
clientProfile.Platform = ".netcore";
clientProfile.EditionID = cmdInfo.clientEditionId;
clientProfile.ClientId = cmdInfo.ClientID;
clientProfile.Cores = cmdInfo.clientInfo.Cores;
clientProfile.Mac = cmdInfo.clientInfo.MacAddress;
clientProfile.IpAddress = cmdInfo.clientInfo.IPAddress.ToString();
clientProfile.Version = ProductVersion.GetVersion();
clientProfile.OperatingSystem = cmdInfo.clientInfo.OperationSystem;
clientProfile.Memory = cmdInfo.clientInfo.Memory;
clientManager.ClientProfile = clientProfile;
if (cmdInfo.clientInfo != null && cmdInfo.clientInfo.AppName != null && cmdInfo.clientInfo.AppName.Contains(FeatureUsageCollector.FeatureTag))
{
FeatureUsageCollector.Instance.GetClientFeature(cmdInfo.clientInfo.AppName).UpdateUsageTime();
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Avalonia.Utilities
{
/// <summary>
/// Provides utilities for working with types at runtime.
/// </summary>
public static class TypeUtilities
{
private static int[] Conversions =
{
0b101111111111101, // Boolean
0b100001111111110, // Char
0b101111111111111, // SByte
0b101111111111111, // Byte
0b101111111111111, // Int16
0b101111111111111, // UInt16
0b101111111111111, // Int32
0b101111111111111, // UInt32
0b101111111111111, // Int64
0b101111111111111, // UInt64
0b101111111111101, // Single
0b101111111111101, // Double
0b101111111111101, // Decimal
0b110000000000000, // DateTime
0b111111111111111, // String
};
private static int[] ImplicitConversions =
{
0b000000000000001, // Boolean
0b001110111100010, // Char
0b001110101010100, // SByte
0b001111111111000, // Byte
0b001110101010000, // Int16
0b001111111100000, // UInt16
0b001110101000000, // Int32
0b001111110000000, // UInt32
0b001110100000000, // Int64
0b001111000000000, // UInt64
0b000110000000000, // Single
0b000100000000000, // Double
0b001000000000000, // Decimal
0b010000000000000, // DateTime
0b100000000000000, // String
};
private static Type[] InbuiltTypes =
{
typeof(Boolean),
typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(String),
};
private static readonly Type[] NumericTypes = new[]
{
typeof(Byte),
typeof(Decimal),
typeof(Double),
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(SByte),
typeof(Single),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
};
/// <summary>
/// Returns a value indicating whether null can be assigned to the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>True if the type accepts null values; otherwise false.</returns>
public static bool AcceptsNull(Type type)
{
var t = type.GetTypeInfo();
return !t.IsValueType || (t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(Nullable<>)));
}
/// <summary>
/// Try to convert a value to a type by any means possible.
/// </summary>
/// <param name="to">The type to cast to.</param>
/// <param name="value">The value to cast.</param>
/// <param name="culture">The culture to use.</param>
/// <param name="result">If sucessful, contains the cast value.</param>
/// <returns>True if the cast was sucessful, otherwise false.</returns>
public static bool TryConvert(Type to, object value, CultureInfo culture, out object result)
{
if (value == null)
{
result = null;
return AcceptsNull(to);
}
if (value == AvaloniaProperty.UnsetValue)
{
result = value;
return true;
}
var from = value.GetType();
var fromTypeInfo = from.GetTypeInfo();
var toTypeInfo = to.GetTypeInfo();
if (toTypeInfo.IsAssignableFrom(fromTypeInfo))
{
result = value;
return true;
}
if (to == typeof(string))
{
result = Convert.ToString(value);
return true;
}
if (toTypeInfo.IsEnum && from == typeof(string))
{
if (Enum.IsDefined(to, (string)value))
{
result = Enum.Parse(to, (string)value);
return true;
}
}
if (!fromTypeInfo.IsEnum && toTypeInfo.IsEnum)
{
result = null;
if (TryConvert(Enum.GetUnderlyingType(to), value, culture, out object enumValue))
{
result = Enum.ToObject(to, enumValue);
return true;
}
}
if (fromTypeInfo.IsEnum && IsNumeric(to))
{
try
{
result = Convert.ChangeType((int)value, to, culture);
return true;
}
catch
{
result = null;
return false;
}
}
var convertableFrom = Array.IndexOf(InbuiltTypes, from);
var convertableTo = Array.IndexOf(InbuiltTypes, to);
if (convertableFrom != -1 && convertableTo != -1)
{
if ((Conversions[convertableFrom] & 1 << convertableTo) != 0)
{
try
{
result = Convert.ChangeType(value, to, culture);
return true;
}
catch
{
result = null;
return false;
}
}
}
var cast = from.GetRuntimeMethods()
.FirstOrDefault(m => (m.Name == "op_Implicit" || m.Name == "op_Explicit") && m.ReturnType == to);
if (cast != null)
{
result = cast.Invoke(null, new[] { value });
return true;
}
result = null;
return false;
}
/// <summary>
/// Try to convert a value to a type using the implicit conversions allowed by the C#
/// language.
/// </summary>
/// <param name="to">The type to cast to.</param>
/// <param name="value">The value to cast.</param>
/// <param name="result">If sucessful, contains the cast value.</param>
/// <returns>True if the cast was sucessful, otherwise false.</returns>
public static bool TryConvertImplicit(Type to, object value, out object result)
{
if (value == null)
{
result = null;
return AcceptsNull(to);
}
if (value == AvaloniaProperty.UnsetValue)
{
result = value;
return true;
}
var from = value.GetType();
var fromTypeInfo = from.GetTypeInfo();
var toTypeInfo = to.GetTypeInfo();
if (toTypeInfo.IsAssignableFrom(fromTypeInfo))
{
result = value;
return true;
}
var convertableFrom = Array.IndexOf(InbuiltTypes, from);
var convertableTo = Array.IndexOf(InbuiltTypes, to);
if (convertableFrom != -1 && convertableTo != -1)
{
if ((ImplicitConversions[convertableFrom] & 1 << convertableTo) != 0)
{
try
{
result = Convert.ChangeType(value, to, CultureInfo.InvariantCulture);
return true;
}
catch
{
result = null;
return false;
}
}
}
var cast = from.GetRuntimeMethods()
.FirstOrDefault(m => m.Name == "op_Implicit" && m.ReturnType == to);
if (cast != null)
{
result = cast.Invoke(null, new[] { value });
return true;
}
result = null;
return false;
}
/// <summary>
/// Convert a value to a type by any means possible, returning the default for that type
/// if the value could not be converted.
/// </summary>
/// <param name="value">The value to cast.</param>
/// <param name="type">The type to cast to..</param>
/// <param name="culture">The culture to use.</param>
/// <returns>A value of <paramref name="type"/>.</returns>
public static object ConvertOrDefault(object value, Type type, CultureInfo culture)
{
return TryConvert(type, value, culture, out object result) ? result : Default(type);
}
/// <summary>
/// Convert a value to a type using the implicit conversions allowed by the C# language or
/// return the default for the type if the value could not be converted.
/// </summary>
/// <param name="value">The value to cast.</param>
/// <param name="type">The type to cast to..</param>
/// <returns>A value of <paramref name="type"/>.</returns>
public static object ConvertImplicitOrDefault(object value, Type type)
{
return TryConvertImplicit(type, value, out object result) ? result : Default(type);
}
/// <summary>
/// Gets the default value for the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The default value.</returns>
public static object Default(Type type)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsValueType)
{
return Activator.CreateInstance(type);
}
else
{
return null;
}
}
/// <summary>
/// Determines if a type is numeric. Nullable numeric types are considered numeric.
/// </summary>
/// <returns>
/// True if the type is numberic; otherwise false.
/// </returns>
/// <remarks>
/// Boolean is not considered numeric.
/// </remarks>
public static bool IsNumeric(Type type)
{
if (type == null)
{
return false;
}
if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return IsNumeric(Nullable.GetUnderlyingType(type));
}
else
{
return NumericTypes.Contains(type);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine.EventSystems;
namespace UnityEngine.UI
{
[AddComponentMenu("Event/Graphic Raycaster")]
[RequireComponent(typeof(Canvas))]
public class GraphicRaycaster : BaseRaycaster
{
protected const int kNoEventMaskSet = -1;
public enum BlockingObjects
{
None = 0,
TwoD = 1,
ThreeD = 2,
All = 3,
}
public override int sortOrderPriority
{
get
{
// We need to return the sorting order here as distance will all be 0 for overlay.
if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
return canvas.sortingOrder;
return base.sortOrderPriority;
}
}
public override int renderOrderPriority
{
get
{
// We need to return the sorting order here as distance will all be 0 for overlay.
if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
return canvas.renderOrder;
return base.renderOrderPriority;
}
}
public bool ignoreReversedGraphics = true;
public BlockingObjects blockingObjects = BlockingObjects.None;
[SerializeField]
protected LayerMask m_BlockingMask = kNoEventMaskSet;
private Canvas m_Canvas;
protected GraphicRaycaster()
{ }
private Canvas canvas
{
get
{
if (m_Canvas != null)
return m_Canvas;
m_Canvas = GetComponent<Canvas>();
return m_Canvas;
}
}
[NonSerialized] private List<Graphic> m_RaycastResults = new List<Graphic>();
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (canvas == null)
return;
// Convert to view space
Vector2 pos;
if (eventCamera == null)
pos = new Vector2(eventData.position.x / Screen.width, eventData.position.y / Screen.height);
else
pos = eventCamera.ScreenToViewportPoint(eventData.position);
// If it's outside the camera's viewport, do nothing
if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f)
return;
float hitDistance = float.MaxValue;
if (canvas.renderMode != RenderMode.ScreenSpaceOverlay && blockingObjects != BlockingObjects.None)
{
var ray = eventCamera.ScreenPointToRay(eventData.position);
float dist = eventCamera.farClipPlane - eventCamera.nearClipPlane;
if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
{
var hits = Physics.RaycastAll(ray, dist, m_BlockingMask);
if (hits.Length > 0 && hits[0].distance < hitDistance)
{
hitDistance = hits[0].distance;
}
}
if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
{
var hits = Physics2D.GetRayIntersectionAll(ray, dist, m_BlockingMask);
if (hits.Length > 0 && hits[0].fraction * dist < hitDistance)
{
hitDistance = hits[0].fraction * dist;
}
}
}
m_RaycastResults.Clear();
Raycast(canvas, eventCamera, eventData.position, m_RaycastResults);
for (var index = 0; index < m_RaycastResults.Count; index++)
{
var go = m_RaycastResults[index].gameObject;
bool appendGraphic = true;
if (ignoreReversedGraphics)
{
if (eventCamera == null)
{
// If we dont have a camera we know that we should always be facing forward
var dir = go.transform.rotation * Vector3.forward;
appendGraphic = Vector3.Dot(Vector3.forward, dir) > 0;
}
else
{
// If we have a camera compare the direction against the cameras forward.
var cameraFoward = eventCamera.transform.rotation * Vector3.forward;
var dir = go.transform.rotation * Vector3.forward;
appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
}
}
if (appendGraphic)
{
float distance = (eventCamera == null || canvas.renderMode == RenderMode.ScreenSpaceOverlay) ? 0 : Vector3.Distance(eventCamera.transform.position, canvas.transform.position);
if (distance >= hitDistance)
continue;
var castResult = new RaycastResult
{
gameObject = go,
module = this,
distance = distance,
index = resultAppendList.Count,
depth = m_RaycastResults[index].depth
};
resultAppendList.Add(castResult);
}
}
}
public override Camera eventCamera
{
get
{
if (canvas.renderMode == RenderMode.ScreenSpaceOverlay
|| (canvas.renderMode == RenderMode.ScreenSpaceCamera && canvas.worldCamera == null))
return null;
return canvas.worldCamera != null ? canvas.worldCamera : Camera.main;
}
}
/// <summary>
/// Perform a raycast into the screen and collect all graphics underneath it.
/// </summary>
[NonSerialized] static readonly List<Graphic> s_SortedGraphics = new List<Graphic>();
private static void Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results)
{
// Debug.Log("ttt" + pointerPoision + ":::" + camera);
// Necessary for the event system
var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
s_SortedGraphics.Clear();
for (int i = 0; i < foundGraphics.Count; ++i)
{
Graphic graphic = foundGraphics[i];
// -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
if (graphic.depth == -1)
continue;
if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, pointerPosition, eventCamera))
continue;
if (graphic.Raycast(pointerPosition, eventCamera))
{
s_SortedGraphics.Add(graphic);
}
}
s_SortedGraphics.Sort((g1, g2) => g2.depth.CompareTo(g1.depth));
// StringBuilder cast = new StringBuilder();
for (int i = 0; i < s_SortedGraphics.Count; ++i)
results.Add(s_SortedGraphics[i]);
// Debug.Log (cast.ToString());
}
}
}
| |
// Copyright 2011 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;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NodaTime.Properties;
using NodaTime.Text;
using NodaTime.Text.Patterns;
using NUnit.Framework;
namespace NodaTime.Test.Text
{
[TestFixture]
public partial class LocalTimePatternTest : PatternTestBase<LocalTime>
{
private static readonly DateTime SampleDateTime = new DateTime(2000, 1, 1, 21, 13, 34, 123, DateTimeKind.Unspecified).AddTicks(4567);
private static readonly LocalTime SampleLocalTime = new LocalTime(21, 13, 34, 123, 4567);
// Characters we expect to work the same in Noda Time as in the BCL.
private const string ExpectedCharacters = "hHms.:fFtT ";
private static readonly CultureInfo AmOnlyCulture = CreateCustomAmPmCulture("am", "");
private static readonly CultureInfo PmOnlyCulture = CreateCustomAmPmCulture("", "pm");
private static readonly CultureInfo NoAmOrPmCulture = CreateCustomAmPmCulture("", "");
internal static readonly Data[] InvalidPatternData = {
new Data { Pattern = "!", Message = Messages.Parse_UnknownStandardFormat, Parameters = {'!', typeof(LocalTime).FullName}},
new Data { Pattern = "%", Message = Messages.Parse_UnknownStandardFormat, Parameters = { '%', typeof(LocalTime).FullName } },
new Data { Pattern = "\\", Message = Messages.Parse_UnknownStandardFormat, Parameters = { '\\', typeof(LocalTime).FullName } },
new Data { Pattern = "%%", Message = Messages.Parse_PercentDoubled },
new Data { Pattern = "%\\", Message = Messages.Parse_EscapeAtEndOfString },
new Data { Pattern = "ffffffffff", Message = Messages.Parse_RepeatCountExceeded, Parameters = { 'f', 9 } },
new Data { Pattern = "FFFFFFFFFF", Message = Messages.Parse_RepeatCountExceeded, Parameters = { 'F', 9 } },
new Data { Pattern = "H%", Message = Messages.Parse_PercentAtEndOfString },
new Data { Pattern = "HHH", Message = Messages.Parse_RepeatCountExceeded, Parameters = { 'H', 2 } },
new Data { Pattern = "mmm", Message = Messages.Parse_RepeatCountExceeded, Parameters = { 'm', 2 } },
new Data { Pattern = "mmmmmmmmmmmmmmmmmmm", Message = Messages.Parse_RepeatCountExceeded, Parameters = { 'm', 2 } },
new Data { Pattern = "'qwe", Message = Messages.Parse_MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "'qwe\\", Message = Messages.Parse_EscapeAtEndOfString },
new Data { Pattern = "'qwe\\'", Message = Messages.Parse_MissingEndQuote, Parameters = { '\'' } },
new Data { Pattern = "sss", Message = Messages.Parse_RepeatCountExceeded, Parameters = { 's', 2 } },
// T isn't valid in a time pattern
new Data { Pattern = "1970-01-01THH:mm:ss", Message = Messages.Parse_UnquotedLiteral, Parameters = { 'T' } }
};
internal static Data[] ParseFailureData = {
new Data { Text = "17 6", Pattern = "HH h", Message = Messages.Parse_InconsistentValues2, Parameters = {'H', 'h', typeof(LocalTime).FullName}},
new Data { Text = "17 AM", Pattern = "HH tt", Message = Messages.Parse_InconsistentValues2, Parameters = {'H', 't', typeof(LocalTime).FullName}},
new Data { Text = "04.", Pattern = "ss.FF", Message = Messages.Parse_MismatchedNumber, Parameters = { "FF" } },
new Data { Text = "04.", Pattern = "ss.ff", Message = Messages.Parse_MismatchedNumber, Parameters = { "ff" } },
};
internal static Data[] ParseOnlyData = {
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%f", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%F", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "FF", },
new Data(0, 0, 0, 400) { Text = "40", Pattern = "FF", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "FFF", },
new Data(0, 0, 0, 400) { Text = "40", Pattern = "FFF" },
new Data(0, 0, 0, 400) { Text = "400", Pattern = "FFF" },
new Data(0, 0, 0, 400) { Text = "40", Pattern = "ff", },
new Data(0, 0, 0, 400) { Text = "400", Pattern = "fff", },
new Data(0, 0, 0, 400) { Text = "4000", Pattern = "ffff", },
new Data(0, 0, 0, 400) { Text = "40000", Pattern = "fffff", },
new Data(0, 0, 0, 400) { Text = "400000", Pattern = "ffffff", },
new Data(0, 0, 0, 400) { Text = "4000000", Pattern = "fffffff", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%f", },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%F", },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "ff" },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "FF" },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "FFF" },
new Data(0, 0, 0, 450) { Text = "450", Pattern = "fff" },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%f" },
new Data(0, 0, 0, 400) { Text = "4", Pattern = "%F" },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "ff" },
new Data(0, 0, 0, 450) { Text = "45", Pattern = "FF" },
new Data(0, 0, 0, 456) { Text = "456", Pattern = "fff" },
new Data(0, 0, 0, 456) { Text = "456", Pattern = "FFF" },
new Data(0, 0, 0, 0) { Text = "0", Pattern = "%f" },
new Data(0, 0, 0, 0) { Text = "00", Pattern = "ff" },
new Data(0, 0, 0, 8) { Text = "008", Pattern = "fff" },
new Data(0, 0, 0, 8) { Text = "008", Pattern = "FFF" },
new Data(5, 0, 0, 0) { Text = "05", Pattern = "HH" },
new Data(0, 6, 0, 0) { Text = "06", Pattern = "mm" },
new Data(0, 0, 7, 0) { Text = "07", Pattern = "ss" },
new Data(5, 0, 0, 0) { Text = "5", Pattern = "%H" },
new Data(0, 6, 0, 0) { Text = "6", Pattern = "%m" },
new Data(0, 0, 7, 0) { Text = "7", Pattern = "%s" },
// AM/PM designator is case-insensitive for both short and long forms
new Data(17, 0, 0, 0) { Text = "5 p", Pattern = "h t" },
new Data(17, 0, 0, 0) { Text = "5 pm", Pattern = "h tt" },
// Parsing using the semi-colon "comma dot" specifier
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;fff", Text = "16:05:20,352" },
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF", Text = "16:05:20,352" },
// Empty fractional section
new Data(0,0,4,0) { Text = "04", Pattern = "ssFF" },
new Data(0,0,4,0) { Text = "040", Pattern = "ssFF" },
new Data(0,0,4,0) { Text = "040", Pattern = "ssFFF" },
new Data(0,0,4,0) { Text = "04", Pattern = "ss.FF"},
};
internal static Data[] FormatOnlyData = {
new Data(5, 6, 7, 8) { Text = "", Pattern = "%F" },
new Data(5, 6, 7, 8) { Text = "", Pattern = "FF" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "%f" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "%F" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "FF" },
new Data(1, 1, 1, 400) { Text = "4", Pattern = "FFF" },
new Data(1, 1, 1, 400) { Text = "40", Pattern = "ff" },
new Data(1, 1, 1, 400) { Text = "400", Pattern = "fff" },
new Data(1, 1, 1, 400) { Text = "4000", Pattern = "ffff" },
new Data(1, 1, 1, 400) { Text = "40000", Pattern = "fffff" },
new Data(1, 1, 1, 400) { Text = "400000", Pattern = "ffffff" },
new Data(1, 1, 1, 400) { Text = "4000000", Pattern = "fffffff" },
new Data(1, 1, 1, 450) { Text = "4", Pattern = "%f" },
new Data(1, 1, 1, 450) { Text = "4", Pattern = "%F" },
new Data(1, 1, 1, 450) { Text = "45", Pattern = "ff" },
new Data(1, 1, 1, 450) { Text = "45", Pattern = "FF" },
new Data(1, 1, 1, 450) { Text = "45", Pattern = "FFF" },
new Data(1, 1, 1, 450) { Text = "450", Pattern = "fff" },
new Data(1, 1, 1, 456) { Text = "4", Pattern = "%f" },
new Data(1, 1, 1, 456) { Text = "4", Pattern = "%F" },
new Data(1, 1, 1, 456) { Text = "45", Pattern = "ff" },
new Data(1, 1, 1, 456) { Text = "45", Pattern = "FF" },
new Data(1, 1, 1, 456) { Text = "456", Pattern = "fff" },
new Data(1, 1, 1, 456) { Text = "456", Pattern = "FFF" },
new Data(0,0,0,0) {Text = "", Pattern = "FF" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "0", Pattern = "%f" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "00", Pattern = "ff" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "008", Pattern = "fff" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "008", Pattern = "FFF" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "05", Pattern = "HH" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "06", Pattern = "mm" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "07", Pattern = "ss" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "5", Pattern = "%H" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "6", Pattern = "%m" },
new Data(5, 6, 7, 8) { Culture = Cultures.EnUs, Text = "7", Pattern = "%s" },
};
internal static Data[] DefaultPatternData = {
// Invariant culture uses HH:mm:ss for the "long" pattern
new Data(5, 0, 0, 0) { Text = "05:00:00" },
new Data(5, 12, 0, 0) { Text = "05:12:00" },
new Data(5, 12, 34, 0) { Text = "05:12:34" },
// US uses hh:mm:ss tt for the "long" pattern
new Data(17, 0, 0, 0) { Culture = Cultures.EnUs, Text = "5:00:00 PM" },
new Data(5, 0, 0, 0) { Culture = Cultures.EnUs, Text = "5:00:00 AM" },
new Data(5, 12, 0, 0) { Culture = Cultures.EnUs, Text = "5:12:00 AM" },
new Data(5, 12, 34, 0) { Culture = Cultures.EnUs, Text = "5:12:34 AM" },
};
internal static readonly Data[] TemplateValueData = {
// Pattern specifies nothing - template value is passed through
new Data(new LocalTime(1, 2, 3, 4, 5)) { Culture = Cultures.EnUs, Text = "X", Pattern = "'X'", Template = new LocalTime(1, 2, 3, 4, 5) },
// Tests for each individual field being propagated
new Data(new LocalTime(1, 6, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "mm:ss.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 2, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:ss.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 7, 8, 4, 5)) { Culture = Cultures.EnUs, Text = "06:07:08", Pattern = "HH:mm:ss", Template = new LocalTime(1, 2, 3, 4, 5) },
// Hours are tricky because of the ways they can be specified
new Data(new LocalTime(6, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(1, 2, 3) },
new Data(new LocalTime(18, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(17, 2, 3)) { Culture = Cultures.EnUs, Text = "5 PM", Pattern = "h tt", Template = new LocalTime(1, 2, 3) },
};
/// <summary>
/// Common test data for both formatting and parsing. A test should be placed here unless is truly
/// cannot be run both ways. This ensures that as many round-trip type tests are performed as possible.
/// </summary>
internal static readonly Data[] FormatAndParseData = {
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = ".", Pattern = "%." },
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = ":", Pattern = "%:" },
new Data(LocalTime.Midnight) { Culture = Cultures.ItIt, Text = ".", Pattern = "%." },
new Data(LocalTime.Midnight) { Culture = Cultures.ItIt, Text = ".", Pattern = "%:" },
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = "H", Pattern = "\\H" },
new Data(LocalTime.Midnight) { Culture = Cultures.EnUs, Text = "HHss", Pattern = "'HHss'" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "%f" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "%F" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FF" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FFF" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "100000000", Pattern = "fffffffff" },
new Data(0, 0, 0, 100) { Culture = Cultures.EnUs, Text = "1", Pattern = "FFFFFFFFF" },
new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "ff" },
new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "FF" },
new Data(0, 0, 0, 120) { Culture = Cultures.EnUs, Text = "12", Pattern = "FFF" },
new Data(0, 0, 0, 123) { Culture = Cultures.EnUs, Text = "123", Pattern = "fff" },
new Data(0, 0, 0, 123) { Culture = Cultures.EnUs, Text = "123", Pattern = "FFF" },
new Data(0, 0, 0, 123, 4000) { Culture = Cultures.EnUs, Text = "1234", Pattern = "ffff" },
new Data(0, 0, 0, 123, 4000) { Culture = Cultures.EnUs, Text = "1234", Pattern = "FFFF" },
new Data(0, 0, 0, 123, 4500) { Culture = Cultures.EnUs, Text = "12345", Pattern = "fffff" },
new Data(0, 0, 0, 123, 4500) { Culture = Cultures.EnUs, Text = "12345", Pattern = "FFFFF" },
new Data(0, 0, 0, 123, 4560) { Culture = Cultures.EnUs, Text = "123456", Pattern = "ffffff" },
new Data(0, 0, 0, 123, 4560) { Culture = Cultures.EnUs, Text = "123456", Pattern = "FFFFFF" },
new Data(0, 0, 0, 123, 4567) { Culture = Cultures.EnUs, Text = "1234567", Pattern = "fffffff" },
new Data(0, 0, 0, 123, 4567) { Culture = Cultures.EnUs, Text = "1234567", Pattern = "FFFFFFF" },
new Data(0, 0, 0, 123456780L) { Culture = Cultures.EnUs, Text = "12345678", Pattern = "ffffffff" },
new Data(0, 0, 0, 123456780L) { Culture = Cultures.EnUs, Text = "12345678", Pattern = "FFFFFFFF" },
new Data(0, 0, 0, 123456789L) { Culture = Cultures.EnUs, Text = "123456789", Pattern = "fffffffff" },
new Data(0, 0, 0, 123456789L) { Culture = Cultures.EnUs, Text = "123456789", Pattern = "FFFFFFFFF" },
new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".f" },
new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".F" },
new Data(0, 0, 0, 600) { Culture = Cultures.EnUs, Text = ".6", Pattern = ".FFF" }, // Elided fraction
new Data(0, 0, 0, 678) { Culture = Cultures.EnUs, Text = ".678", Pattern = ".fff" },
new Data(0, 0, 0, 678) { Culture = Cultures.EnUs, Text = ".678", Pattern = ".FFF" },
new Data(0, 0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%s" },
new Data(0, 0, 12, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "ss" },
new Data(0, 0, 2, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%s" },
new Data(0, 12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%m" },
new Data(0, 12, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "mm" },
new Data(0, 2, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%m" },
new Data(1, 0, 0, 0) { Culture = Cultures.EnUs, Text = "1", Pattern = "H.FFF" }, // Missing fraction
new Data(12, 0, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "%H" },
new Data(12, 0, 0, 0) { Culture = Cultures.EnUs, Text = "12", Pattern = "HH" },
new Data(2, 0, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%H" },
new Data(2, 0, 0, 0) { Culture = Cultures.EnUs, Text = "2", Pattern = "%H" },
new Data(0, 0, 12, 340) { Culture = Cultures.EnUs, Text = "12.34", Pattern = "ss.FFF" },
new Data(14, 15, 16) { Culture = Cultures.EnUs, Text = "14:15:16", Pattern = "r" },
new Data(14, 15, 16, 700) { Culture = Cultures.EnUs, Text = "14:15:16.7", Pattern = "r" },
new Data(14, 15, 16, 780) { Culture = Cultures.EnUs, Text = "14:15:16.78", Pattern = "r" },
new Data(14, 15, 16, 789) { Culture = Cultures.EnUs, Text = "14:15:16.789", Pattern = "r" },
new Data(14, 15, 16, 789, 1000) { Culture = Cultures.EnUs, Text = "14:15:16.7891", Pattern = "r" },
new Data(14, 15, 16, 789, 1200) { Culture = Cultures.EnUs, Text = "14:15:16.78912", Pattern = "r" },
new Data(14, 15, 16, 789, 1230) { Culture = Cultures.EnUs, Text = "14:15:16.789123", Pattern = "r" },
new Data(14, 15, 16, 789, 1234) { Culture = Cultures.EnUs, Text = "14:15:16.7891234", Pattern = "r" },
new Data(14, 15, 16, 700) { Culture = Cultures.ItIt, Text = "14.15.16.7", Pattern = "r" },
new Data(14, 15, 16, 780) { Culture = Cultures.ItIt, Text = "14.15.16.78", Pattern = "r" },
new Data(14, 15, 16, 789) { Culture = Cultures.ItIt, Text = "14.15.16.789", Pattern = "r" },
new Data(14, 15, 16, 789, 1000) { Culture = Cultures.ItIt, Text = "14.15.16.7891", Pattern = "r" },
new Data(14, 15, 16, 789, 1200) { Culture = Cultures.ItIt, Text = "14.15.16.78912", Pattern = "r" },
new Data(14, 15, 16, 789, 1230) { Culture = Cultures.ItIt, Text = "14.15.16.789123", Pattern = "r" },
new Data(14, 15, 16, 789, 1234) { Culture = Cultures.ItIt, Text = "14.15.16.7891234", Pattern = "r" },
new Data(14, 15, 16, 789123456L) { Culture = Cultures.ItIt, Text = "14.15.16.789123456", Pattern = "r" },
// ------------ Template value tests ----------
// Mixtures of 12 and 24 hour times
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 6 PM", Pattern = "HH h tt" },
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 6", Pattern = "HH h" },
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "18 PM", Pattern = "HH tt" },
new Data(18, 0, 0) { Culture = Cultures.EnUs, Text = "6 PM", Pattern = "h tt" },
new Data(6, 0, 0) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h" },
new Data(0, 0, 0) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt" },
new Data(12, 0, 0) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt" },
// Pattern specifies nothing - template value is passed through
new Data(new LocalTime(1, 2, 3, 4, 5)) { Culture = Cultures.EnUs, Text = "*", Pattern = "%*", Template = new LocalTime(1, 2, 3, 4, 5) },
// Tests for each individual field being propagated
new Data(new LocalTime(1, 6, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "mm:ss.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 2, 7, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:ss.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 7, 3, 8, 9)) { Culture = Cultures.EnUs, Text = "06:07.0080009", Pattern = "HH:mm.FFFFFFF", Template = new LocalTime(1, 2, 3, 4, 5) },
new Data(new LocalTime(6, 7, 8, 4, 5)) { Culture = Cultures.EnUs, Text = "06:07:08", Pattern = "HH:mm:ss", Template = new LocalTime(1, 2, 3, 4, 5) },
// Hours are tricky because of the ways they can be specified
new Data(new LocalTime(6, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(1, 2, 3) },
new Data(new LocalTime(18, 2, 3)) { Culture = Cultures.EnUs, Text = "6", Pattern = "%h", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(14, 2, 3) },
new Data(new LocalTime(2, 2, 3)) { Culture = Cultures.EnUs, Text = "AM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(14, 2, 3)) { Culture = Cultures.EnUs, Text = "PM", Pattern = "tt", Template = new LocalTime(2, 2, 3) },
new Data(new LocalTime(17, 2, 3)) { Culture = Cultures.EnUs, Text = "5 PM", Pattern = "h tt", Template = new LocalTime(1, 2, 3) },
// --------------- end of template value tests ----------------------
// Only one of the AM/PM designator is present. We should still be able to work out what is meant, by the presence
// or absense of the non-empty one.
new Data(5, 0, 0) { Culture = AmOnlyCulture, Text = "5 am", Pattern = "h tt" },
new Data(15, 0, 0) { Culture = AmOnlyCulture, Text = "3 ", Pattern = "h tt", Description = "Implicit PM" },
new Data(5, 0, 0) { Culture = AmOnlyCulture, Text = "5 a", Pattern = "h t" },
new Data(15, 0, 0) { Culture = AmOnlyCulture, Text = "3 ", Pattern = "h t", Description = "Implicit PM"},
new Data(5, 0, 0) { Culture = PmOnlyCulture, Text = "5 ", Pattern = "h tt" },
new Data(15, 0, 0) { Culture = PmOnlyCulture, Text = "3 pm", Pattern = "h tt" },
new Data(5, 0, 0) { Culture = PmOnlyCulture, Text = "5 ", Pattern = "h t" },
new Data(15, 0, 0) { Culture = PmOnlyCulture, Text = "3 p", Pattern = "h t" },
// AM / PM designators are both empty strings. The parsing side relies on the AM/PM value being correct on the
// template value. (The template value is for the wrong actual hour, but in the right side of noon.)
new Data(5, 0, 0) { Culture = NoAmOrPmCulture, Text = "5 ", Pattern = "h tt", Template = new LocalTime(2, 0, 0) },
new Data(15, 0, 0) { Culture = NoAmOrPmCulture, Text = "3 ", Pattern = "h tt", Template = new LocalTime(14, 0, 0) },
new Data(5, 0, 0) { Culture = NoAmOrPmCulture, Text = "5 ", Pattern = "h t", Template = new LocalTime(2, 0, 0) },
new Data(15, 0, 0) { Culture = NoAmOrPmCulture, Text = "3 ", Pattern = "h t", Template = new LocalTime(14, 0, 0) },
// Use of the semi-colon "comma dot" specifier
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;fff", Text = "16:05:20.352" },
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF", Text = "16:05:20.352" },
new Data(16, 05, 20, 352) { Pattern = "HH:mm:ss;FFF 'end'", Text = "16:05:20.352 end" },
new Data(16, 05, 20) { Pattern = "HH:mm:ss;FFF 'end'", Text = "16:05:20 end" },
};
internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData);
internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData);
private static CultureInfo CreateCustomAmPmCulture(string amDesignator, string pmDesignator)
{
CultureInfo clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.DateTimeFormat.AMDesignator = amDesignator;
clone.DateTimeFormat.PMDesignator = pmDesignator;
return CultureInfo.ReadOnly(clone);
}
// Fails on Mono: https://github.com/nodatime/nodatime/issues/98
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCulturesOrEmptyOnMono))]
public void BclLongTimePatternIsValidNodaPattern(CultureInfo culture)
{
AssertValidNodaPattern(culture, culture.DateTimeFormat.LongTimePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclShortTimePatternIsValidNodaPattern(CultureInfo culture)
{
AssertValidNodaPattern(culture, culture.DateTimeFormat.ShortTimePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclLongTimePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.LongTimePattern);
}
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void BclShortTimePatternGivesSameResultsInNoda(CultureInfo culture)
{
AssertBclNodaEquality(culture, culture.DateTimeFormat.ShortTimePattern);
}
[Test]
public void CreateWithInvariantCulture_NullPatternText()
{
Assert.Throws<ArgumentNullException>(() => LocalTimePattern.CreateWithInvariantCulture(null));
}
[Test]
public void Create_NullFormatInfo()
{
Assert.Throws<ArgumentNullException>(() => LocalTimePattern.Create("HH", null));
}
[Test]
public void TemplateValue_DefaultsToMidnight()
{
var pattern = LocalTimePattern.CreateWithInvariantCulture("HH");
Assert.AreEqual(LocalTime.Midnight, pattern.TemplateValue);
}
[Test]
public void WithTemplateValue_PropertyFetch()
{
LocalTime newValue = new LocalTime(1, 23, 45);
var pattern = LocalTimePattern.CreateWithInvariantCulture("HH").WithTemplateValue(newValue);
Assert.AreEqual(newValue, pattern.TemplateValue);
}
private void AssertBclNodaEquality(CultureInfo culture, string patternText)
{
// On Mono, some general patterns include an offset at the end.
// https://github.com/nodatime/nodatime/issues/98
// For the moment, ignore them.
// TODO(V1.2): Work out what to do in such cases...
if (patternText.EndsWith("z"))
{
return;
}
var pattern = LocalTimePattern.Create(patternText, culture);
Assert.AreEqual(SampleDateTime.ToString(patternText, culture), pattern.Format(SampleLocalTime));
}
private static void AssertValidNodaPattern(CultureInfo culture, string pattern)
{
PatternCursor cursor = new PatternCursor(pattern);
while (cursor.MoveNext())
{
if (cursor.Current == '\'')
{
cursor.GetQuotedString('\'');
}
else
{
// We'll never do anything "special" with non-ascii characters anyway,
// so we don't mind if they're not quoted.
if (cursor.Current < '\u0080')
{
Assert.IsTrue(ExpectedCharacters.Contains(cursor.Current),
"Pattern '" + pattern + "' contains unquoted, unexpected characters");
}
}
}
// Check that the pattern parses
LocalTimePattern.Create(pattern, culture);
}
/// <summary>
/// A container for test data for formatting and parsing <see cref="LocalTime" /> objects.
/// </summary>
public sealed class Data : PatternTestData<LocalTime>
{
// Default to midnight
protected override LocalTime DefaultTemplate => LocalTime.Midnight;
public Data(LocalTime value) : base(value)
{
}
public Data(int hours, int minutes, int seconds)
: this(new LocalTime(hours, minutes, seconds))
{
}
public Data(int hours, int minutes, int seconds, int milliseconds)
: this(new LocalTime(hours, minutes, seconds, milliseconds))
{
}
public Data(int hours, int minutes, int seconds, int milliseconds, int ticksWithinMillisecond)
: this(new LocalTime(hours, minutes, seconds, milliseconds, ticksWithinMillisecond))
{
}
public Data(int hours, int minutes, int seconds, long nanoOfSecond)
: this(new LocalTime(hours, minutes, seconds).PlusNanoseconds(nanoOfSecond))
{
}
public Data() : this(LocalTime.Midnight)
{
}
internal override IPattern<LocalTime> CreatePattern() =>
LocalTimePattern.CreateWithInvariantCulture(Pattern)
.WithTemplateValue(Template)
.WithCulture(Culture);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using SunLine.Community.Entities.Core;
using SunLine.Community.Entities.Dict;
using SunLine.Community.Repositories.Core;
using SunLine.Community.Repositories.Dict;
using SunLine.Community.Services.Infrastructure;
namespace SunLine.Community.Services.Core
{
[BusinessLogic]
public class MessageService : IMessageService
{
private readonly IMessageRepository _messageRepository;
private readonly IMessageStateRepository _messageStateRepository;
private readonly IUserRepository _userRepository;
private readonly IMessageUrlService _messageUrlService;
private readonly IFileRepository _fileRepository;
private readonly IDatabaseTransactionService _databaseTransactionService;
public MessageService(
IMessageRepository messageRepository,
IMessageStateRepository messageStateRepository,
IUserRepository userRepository,
IMessageUrlService messageUrlService,
IFileRepository fileRepository,
IDatabaseTransactionService databaseTransactionService)
{
_messageRepository = messageRepository;
_messageStateRepository = messageStateRepository;
_userRepository = userRepository;
_messageUrlService = messageUrlService;
_fileRepository = fileRepository;
_databaseTransactionService = databaseTransactionService;
}
public Message CreateQuote(string mind, Guid userId, Guid quotedMessageId)
{
Message quotedMessage = _messageRepository.FindById(quotedMessageId);
if(quotedMessage == null)
{
throw new ArgumentException(string.Format("Quoted message: '{0}' not exists.", userId));
}
Message createdMessage = CreateMessage(mind, null, userId, quotedMessage, null);
return createdMessage;
}
public Message CreateComment(string mind, Guid userId, Guid commentedMessageId)
{
Message commentedMessage = _messageRepository.FindById(commentedMessageId);
if(commentedMessage == null)
{
throw new ArgumentException(string.Format("Commented message: '{0}' not exists.", userId));
}
Message createdMessage = CreateMessage(mind, null, userId, null, commentedMessage);
return createdMessage;
}
public Message CreateMind(string mind, Guid userId, IList<Guid> fileIds = null)
{
Message createdMessage = CreateMessage(mind, null, userId, null, null);
ConnectMessageWithFiles(createdMessage, fileIds);
return createdMessage;
}
public Message CreateSpeech(string mind, string speech, Guid userId)
{
Message createdMessage = CreateMessage(mind, speech, userId, null, null);
return createdMessage;
}
public Message UpdateSpeech(Guid messageId, string mind, string speech)
{
Message message = _messageRepository.FindById(messageId);
if(message == null)
{
throw new ArgumentException(string.Format("Message '{0}' not exists", messageId));
}
IList<MessageUrl> messageUrls;
mind = _messageUrlService.ParseMindUrl(mind, out messageUrls);
if (!IsValidMind(mind))
{
return null;
}
message.Mind = mind;
message.Speech = speech;
_messageRepository.Update(message);
_messageUrlService.CreateMessageUrls(message, messageUrls);
return message;
}
private void ConnectMessageWithFiles(Message message, IList<Guid> fileIds)
{
if (fileIds != null)
{
foreach (var fileId in fileIds)
{
File file = _fileRepository.FindById(fileId);
if (file != null)
{
file.Messages.Add(message);
message.Files.Add(file);
_fileRepository.Update(file);
}
}
}
}
private Message CreateMessage(string mind, string speech, Guid userId, Message quotedMessage, Message commentedMessage)
{
User user = _userRepository.FindById(userId);
if(user == null)
{
throw new ArgumentException(string.Format("User: '{0}' not exists.", userId));
}
IList<MessageUrl> messageUrls;
mind = _messageUrlService.ParseMindUrl(mind, out messageUrls);
if (!IsValidMind(mind))
{
return null;
}
var message = new Message();
message.Mind = mind;
message.Speech = speech;
message.User = user;
message.Language = user.Language;
message.QuotedMessage = quotedMessage;
message.CommentedMessage = commentedMessage;
message.MessageState = _messageStateRepository.FindByEnum(MessageStateEnum.Draft);
message = _messageRepository.Create(message);
_messageUrlService.CreateMessageUrls(message, messageUrls);
return message;
}
public Message FindById(Guid id)
{
return _messageRepository.FindById(id);
}
public bool WasMessageQuotedByUser(Guid messageId, Guid userId)
{
return _messageRepository.WasMessageQuotedByUser(messageId, userId);
}
public bool WasMessageCommentedByUser(Guid messageId, Guid userId)
{
return _messageRepository.WasMessageCommentedByUser(messageId, userId);
}
public int AmountOfMessages(Guid userId, bool excludeComments)
{
return _messageRepository.AmountOfMessages(userId, excludeComments);
}
public IList<Message> FindLastCommentsToMessage(Guid messageId)
{
return _messageRepository.FindLastCommentsToMessage(messageId);
}
public bool HasRightToMessage(Guid userId, Guid messageId)
{
return _messageRepository.FindAll().Any(x => x.User.Id == userId && x.Id == messageId);
}
public void Delete(Guid messageId)
{
using (var databaseTransaction = _databaseTransactionService.BeginTransaction())
{
try
{
_messageRepository.DeleteMessage(messageId);
databaseTransaction.Commit();
}
catch (Exception)
{
databaseTransaction.Rollback();
throw;
}
}
}
public void ReloadMessage(Message message)
{
_messageRepository.ReloadEntity(message);
}
public IList<Message> FindAllSpeeches(Guid userId)
{
return _messageRepository.FindAll().Where(x => x.User.Id == userId && x.MessageState.MessageStateEnum != MessageStateEnum.Deleted
&& x.Speech != null).OrderByDescending(x => x.CreationDate).ToList();
}
private bool IsValidMind(string message)
{
return !string.IsNullOrWhiteSpace(message) && message.Length <= 200;
}
}
}
| |
// Copyright 2017 - Refael Ackermann
// Distributed under MIT style license
// See accompanying file LICENSE at https://github.com/node4good/windows-autoconf
// Usage:
// powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()"
// This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7.
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace VisualStudioConfiguration
{
[Flags]
public enum InstanceState : uint
{
None = 0,
Local = 1,
Registered = 2,
NoRebootRequired = 4,
NoErrors = 8,
Complete = 4294967295,
}
[Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IEnumSetupInstances
{
void Next([MarshalAs(UnmanagedType.U4), In] int celt,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface), Out] ISetupInstance[] rgelt,
[MarshalAs(UnmanagedType.U4)] out int pceltFetched);
void Skip([MarshalAs(UnmanagedType.U4), In] int celt);
void Reset();
[return: MarshalAs(UnmanagedType.Interface)]
IEnumSetupInstances Clone();
}
[Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupConfiguration
{
}
[Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupConfiguration2 : ISetupConfiguration
{
[return: MarshalAs(UnmanagedType.Interface)]
IEnumSetupInstances EnumInstances();
[return: MarshalAs(UnmanagedType.Interface)]
ISetupInstance GetInstanceForCurrentProcess();
[return: MarshalAs(UnmanagedType.Interface)]
ISetupInstance GetInstanceForPath([MarshalAs(UnmanagedType.LPWStr), In] string path);
[return: MarshalAs(UnmanagedType.Interface)]
IEnumSetupInstances EnumAllInstances();
}
[Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupInstance
{
}
[Guid("89143C9A-05AF-49B0-B717-72E218A2185C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupInstance2 : ISetupInstance
{
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstanceId();
[return: MarshalAs(UnmanagedType.Struct)]
System.Runtime.InteropServices.ComTypes.FILETIME GetInstallDate();
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstallationName();
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstallationPath();
[return: MarshalAs(UnmanagedType.BStr)]
string GetInstallationVersion();
[return: MarshalAs(UnmanagedType.BStr)]
string GetDisplayName([MarshalAs(UnmanagedType.U4), In] int lcid);
[return: MarshalAs(UnmanagedType.BStr)]
string GetDescription([MarshalAs(UnmanagedType.U4), In] int lcid);
[return: MarshalAs(UnmanagedType.BStr)]
string ResolvePath([MarshalAs(UnmanagedType.LPWStr), In] string pwszRelativePath);
[return: MarshalAs(UnmanagedType.U4)]
InstanceState GetState();
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
ISetupPackageReference[] GetPackages();
ISetupPackageReference GetProduct();
[return: MarshalAs(UnmanagedType.BStr)]
string GetProductPath();
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsLaunchable();
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsComplete();
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
ISetupPropertyStore GetProperties();
[return: MarshalAs(UnmanagedType.BStr)]
string GetEnginePath();
}
[Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupPackageReference
{
[return: MarshalAs(UnmanagedType.BStr)]
string GetId();
[return: MarshalAs(UnmanagedType.BStr)]
string GetVersion();
[return: MarshalAs(UnmanagedType.BStr)]
string GetChip();
[return: MarshalAs(UnmanagedType.BStr)]
string GetLanguage();
[return: MarshalAs(UnmanagedType.BStr)]
string GetBranch();
[return: MarshalAs(UnmanagedType.BStr)]
string GetType();
[return: MarshalAs(UnmanagedType.BStr)]
string GetUniqueId();
[return: MarshalAs(UnmanagedType.VariantBool)]
bool GetIsExtension();
}
[Guid("c601c175-a3be-44bc-91f6-4568d230fc83")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISetupPropertyStore
{
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)]
string[] GetNames();
object GetValue([MarshalAs(UnmanagedType.LPWStr), In] string pwszName);
}
[Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")]
[CoClass(typeof(SetupConfigurationClass))]
[ComImport]
public interface SetupConfiguration : ISetupConfiguration2, ISetupConfiguration
{
}
[Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")]
[ClassInterface(ClassInterfaceType.None)]
[ComImport]
public class SetupConfigurationClass
{
}
public static class Main
{
public static void PrintJson()
{
ISetupConfiguration query = new SetupConfiguration();
ISetupConfiguration2 query2 = (ISetupConfiguration2)query;
IEnumSetupInstances e = query2.EnumAllInstances();
int pceltFetched;
ISetupInstance2[] rgelt = new ISetupInstance2[1];
List<string> instances = new List<string>();
while (true)
{
e.Next(1, rgelt, out pceltFetched);
if (pceltFetched <= 0)
{
Console.WriteLine(String.Format("[{0}]", string.Join(",", instances.ToArray())));
return;
}
try
{
instances.Add(InstanceJson(rgelt[0]));
}
catch (COMException)
{
// Ignore instances that can't be queried.
}
}
}
private static string JsonString(string s)
{
return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
}
private static string InstanceJson(ISetupInstance2 setupInstance2)
{
// Visual Studio component directory:
// https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
StringBuilder json = new StringBuilder();
json.Append("{");
string path = JsonString(setupInstance2.GetInstallationPath());
json.Append(String.Format("\"path\":{0},", path));
string version = JsonString(setupInstance2.GetInstallationVersion());
json.Append(String.Format("\"version\":{0},", version));
List<string> packages = new List<string>();
foreach (ISetupPackageReference package in setupInstance2.GetPackages())
{
string id = JsonString(package.GetId());
packages.Add(id);
}
json.Append(String.Format("\"packages\":[{0}]", string.Join(",", packages.ToArray())));
json.Append("}");
return json.ToString();
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Represents logging target.
/// </summary>
[NLogConfigurationItem]
public abstract class Target : ISupportsInitialize, IDisposable
{
private object lockObject = new object();
private List<Layout> allLayouts;
private bool scannedForLayouts;
private Exception initializeException;
/// <summary>
/// Gets or sets the name of the target.
/// </summary>
/// <docgen category='General Options' order='10' />
public string Name { get; set; }
/// <summary>
/// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
/// </summary>
protected object SyncRoot
{
get { return this.lockObject; }
}
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Gets a value indicating whether the target has been initialized.
/// </summary>
protected bool IsInitialized { get; private set; }
/// <summary>
/// Get all used layouts in this target.
/// </summary>
/// <returns></returns>
internal List<Layout> GetAllLayouts()
{
if (!scannedForLayouts)
{
FindAllLayouts();
}
return allLayouts;
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
this.Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
this.Close();
}
/// <summary>
/// Closes the target.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
if (asyncContinuation == null)
{
throw new ArgumentNullException("asyncContinuation");
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
asyncContinuation(null);
return;
}
asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation);
try
{
this.FlushAsync(asyncContinuation);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
}
/// <summary>
/// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
/// used by this target.
/// </summary>
/// <param name="logEvent">
/// The log event.
/// </param>
public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (this.IsInitialized)
{
if (this.allLayouts != null)
{
foreach (Layout l in this.allLayouts)
{
l.Precalculate(logEvent);
}
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var targetAttribute = (TargetAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TargetAttribute));
if (targetAttribute != null)
{
return targetAttribute.Name + " Target[" + (this.Name ?? "(unnamed)") + "]";
}
return this.GetType().Name;
}
/// <summary>
/// Writes the log to the target.
/// </summary>
/// <param name="logEvent">Log event to write.</param>
public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
logEvent.Continuation(null);
return;
}
if (this.initializeException != null)
{
logEvent.Continuation(this.CreateInitException());
return;
}
var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation);
try
{
this.Write(logEvent.LogEvent.WithContinuation(wrappedContinuation));
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
wrappedContinuation(exception);
}
}
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
{
if (logEvents == null || logEvents.Length == 0)
{
return;
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
foreach (var ev in logEvents)
{
ev.Continuation(null);
}
return;
}
if (this.initializeException != null)
{
foreach (var ev in logEvents)
{
ev.Continuation(this.CreateInitException());
}
return;
}
var wrappedEvents = new AsyncLogEventInfo[logEvents.Length];
for (int i = 0; i < logEvents.Length; ++i)
{
wrappedEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation));
}
try
{
this.Write(wrappedEvents);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// in case of synchronous failure, assume that nothing is running asynchronously
foreach (var ev in wrappedEvents)
{
ev.Continuation(exception);
}
}
}
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = configuration;
if (!this.IsInitialized)
{
PropertyHelper.CheckRequiredParameters(this);
this.IsInitialized = true;
try
{
this.InitializeTarget();
this.initializeException = null;
if (this.allLayouts == null)
{
throw new NLogRuntimeException("{0}.allLayouts is null. Call base.InitializeTarget() in {0}", this.GetType());
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error initializing target '{0}'.", this);
this.initializeException = exception;
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = null;
if (this.IsInitialized)
{
this.IsInitialized = false;
try
{
if (this.initializeException == null)
{
// if Init succeeded, call Close()
this.CloseTarget();
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error closing target '{0}'.", this);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
internal void WriteAsyncLogEvents(AsyncLogEventInfo[] logEventInfos, AsyncContinuation continuation)
{
if (logEventInfos.Length == 0)
{
continuation(null);
}
else
{
var wrappedLogEventInfos = new AsyncLogEventInfo[logEventInfos.Length];
int remaining = logEventInfos.Length;
for (int i = 0; i < logEventInfos.Length; ++i)
{
AsyncContinuation originalContinuation = logEventInfos[i].Continuation;
AsyncContinuation wrappedContinuation = ex =>
{
originalContinuation(ex);
if (0 == Interlocked.Decrement(ref remaining))
{
continuation(null);
}
};
wrappedLogEventInfos[i] = logEventInfos[i].LogEvent.WithContinuation(wrappedContinuation);
}
this.WriteAsyncLogEvents(wrappedLogEventInfos);
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.CloseTarget();
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected virtual void InitializeTarget()
{
//rescan as amount layouts can be changed.
FindAllLayouts();
}
private void FindAllLayouts()
{
this.allLayouts = new List<Layout>(ObjectGraphScanner.FindReachableObjects<Layout>(this));
InternalLogger.Trace("{0} has {1} layouts", this, this.allLayouts.Count);
this.scannedForLayouts = true;
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected virtual void CloseTarget()
{
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
{
asyncContinuation(null);
}
/// <summary>
/// Writes logging event to the log target.
/// classes.
/// </summary>
/// <param name="logEvent">
/// Logging event to be written out.
/// </param>
protected virtual void Write(LogEventInfo logEvent)
{
// do nothing
}
/// <summary>
/// Writes log event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void Write(AsyncLogEventInfo logEvent)
{
try
{
this.MergeEventProperties(logEvent.LogEvent);
this.Write(logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void Write(AsyncLogEventInfo[] logEvents)
{
for (int i = 0; i < logEvents.Length; ++i)
{
this.Write(logEvents[i]);
}
}
private Exception CreateInitException()
{
return new NLogRuntimeException("Target " + this + " failed to initialize.", this.initializeException);
}
/// <summary>
/// Merges (copies) the event context properties from any event info object stored in
/// parameters of the given event info object.
/// </summary>
/// <param name="logEvent">The event info object to perform the merge to.</param>
protected void MergeEventProperties(LogEventInfo logEvent)
{
if (logEvent.Parameters == null)
{
return;
}
foreach (var item in logEvent.Parameters)
{
var logEventParameter = item as LogEventInfo;
if (logEventParameter != null)
{
foreach (var key in logEventParameter.Properties.Keys)
{
logEvent.Properties.Add(key, logEventParameter.Properties[key]);
}
logEventParameter.Properties.Clear();
}
}
}
}
}
| |
using System.Collections.Generic;
using Esprima.Net;
namespace Esprima.NET.Nodes
{
public class Node //= Node.prototype = {
{
public Node right { get; set; }
public Node left { get; set; }
public string type { get; set; }
public bool generator { get; set; }
public bool shorthand { get; set; }
public bool method { get; set; }
public string kind { get; set; }
public Node value { get; set; }
public bool computed { get; set; }
public Node key { get; set; }
public object defaults { get; set; }
public Node expression { get; set; }
public string @operator { get; set; }
public object arguments { get; set; }
public object callee { get; set; }
public List<Node> elements { get; set; }
public object alternate { get; set; }
public object consequent { get; set; }
public object test { get; set; }
public bool each { get; set; }
public Node id { get; set; }
public Node param { get; set; }
public Node superClass { get; set; }
public object @object { get; set; }
public List<Node> body { get; set; }
public object init { get; set; }
public object update { get; set; }
public object label { get; set; }
public List<Node> @params { get; set; }
public string name { get; set; }
public object property { get; set; }
public List<Node> properties { get; set; }
public object cases { get; set; }
public object quasi { get; set; }
public Node local { get; set; }
public string source { get; set; }
public List<Node> specifiers { get; set; }
public object imported { get; set; }
public object declaration { get; set; }
public Node exported { get; set; }
public bool? @delegate { get; set; }
public object tag { get; set; }
public object tail { get; set; }
public object discriminant { get; set; }
public List<Node> expressions { get; set; }
public object meta { get; set; }
public object finalizer { get; set; }
public object handler { get; set; }
public List<object> handlers { get; set; }
public List<object> guardedHandlers { get; set; }
public object block { get; set; }
public object declarations { get; set; }
public bool prefix { get; set; }
public object sourceType { get; set; }
public Range range { get; set; }
public List<Comment> trailingComments { get; set; }
public List<Comment> leadingComments { get; set; }
public object quasis { get; set; }
public Node argument { get; set; }
public override string ToString()
{
return base.ToString() + ": " + this.type;
}
public Node()
{
if (Esprima.extra != null)
{
if (Esprima.extra.range)
{
this.range = new Range() { Start = Esprima.startIndex, End = 0 };
}
if (Esprima.extra.loc != null)
{
this.loc = new Loc();
}
}
}
public Node(Token startToken)
{
if (Esprima.extra != null)
{
//if (extra.range)
//{
this.range = new Range() { Start = startToken.start, End = 0 };
// }
if (Esprima.extra.loc != null)
{
this.loc = Esprima.WrappingSourceLocation(startToken);
}
}
}
public Loc loc { get; set; }
public void processComment()
{
Extra lastChild = null;
List<Comment> leadingComments = null;
List<Comment> trailingComments = null;
var bottomRight = Esprima.extra.bottomRightStack;
int i;
Comment comment;
var last = bottomRight[bottomRight.Count - 1];
if (this.type == Syntax.Program)
{
if (this.body.Count > 0)
{
return;
}
}
if (Esprima.extra.trailingComments.Count > 0)
{
trailingComments = new List<Comment>();
for (i = Esprima.extra.trailingComments.Count - 1; i >= 0; --i)
{
comment = Esprima.extra.trailingComments[i];
//if (comment.range[0] >= this.range[1])
//{
trailingComments.Insert(0, comment);
Esprima.extra.trailingComments.RemoveRange(i, 1);
//}
}
Esprima.extra.trailingComments = new List<Comment>();
}
else
{
//if (last != null && last.trailingComments != null &&
// last.trailingComments[0].range[0] >= this.range[1])
//{
// trailingComments = last.trailingComments;
// last.trailingComments.Clear();
//}
}
// Eating the stack.
//while (last && last.range[0] >= this.range[0])
//{
// // lastChild = bottomRight.pop();
// last = bottomRight.Last();
//}
if (lastChild != null)
{
if (lastChild.leadingComments != null)
{
leadingComments = new List<Comment>();
for (i = lastChild.leadingComments.Count - 1; i >= 0; --i)
{
comment = lastChild.leadingComments[i];
//if (comment.range[1] <= this.range[0])
//{
// leadingComments.Insert(0, comment);
// lastChild.leadingComments.RemoveRange(i, 1);
//}
}
//if (lastChild.leadingComments== null) {
// lastChild.leadingComments = undefined;
//}
}
}
else if (Esprima.extra.leadingComments.Count > 0)
{
leadingComments = new List<Comment>();
for (i = Esprima.extra.leadingComments.Count - 1; i >= 0; --i)
{
comment = Esprima.extra.leadingComments[i];
//if (comment.range[1] <= this.range[0])
//{
// leadingComments.Insert(0, comment);
// extra.leadingComments.RemoveRange(i, 1);
//}
}
}
if (leadingComments != null && leadingComments.Count > 0)
{
this.leadingComments = leadingComments;
}
if (trailingComments != null && trailingComments.Count > 0)
{
this.trailingComments = trailingComments;
}
// bottomRight.Add(this);
}
public void finish()
{
if (Esprima.extra.range)
{
this.range.End = Esprima.lastIndex;
}
if (Esprima.extra.loc != null)
{
this.loc.end = new Loc.Position()
{
line = Esprima.lastLineNumber,
column = Esprima.lastIndex - Esprima.lastLineStart
};
if (Esprima.extra.source != null)
{
this.loc.source = Esprima.extra.source;
}
}
if (Esprima.extra.attachComment)
{
this.processComment();
}
}
public Node finishArrayExpression(List<Node> elements)
{
this.type = Syntax.ArrayExpression;
this.elements = elements;
this.finish();
return this;
}
public Node finishArrayPattern(List<Node> elements)
{
this.type = Syntax.ArrayPattern;
this.elements = elements;
this.finish();
return this;
}
public Node finishArrowFunctionExpression(List<Node> @params, object defaults, List<Node> body, Node expression)
{
this.type = Syntax.ArrowFunctionExpression;
this.id = null;
this.@params = @params;
this.defaults = defaults;
this.body = body;
this.generator = false;
this.expression = expression;
this.finish();
return this;
}
public Node finishAssignmentExpression(string @operator, Node left, Node right)
{
this.type = Syntax.AssignmentExpression;
this.@operator = @operator;
this.left = left;
this.right = right;
this.finish();
return this;
}
public Node finishAssignmentPattern(Node left, Node right)
{
this.type = Syntax.AssignmentPattern;
this.left = left;
this.right = right;
this.finish();
return this;
}
public Node finishBinaryExpression(string @operator, Node left, Node right)
{
this.type = (@operator == "||" || @operator == "&&")
? Syntax.LogicalExpression
: Syntax.BinaryExpression;
this.@operator = @operator;
this.left = left;
this.right = right;
this.finish();
return this;
}
public Node finishBlockStatement(List<Node> body)
{
this.type = Syntax.BlockStatement;
this.body = body;
this.finish();
return this;
}
public Node finishBreakStatement(object label)
{
this.type = Syntax.BreakStatement;
this.label = label;
this.finish();
return this;
}
public Node finishCallExpression(object callee, object args)
{
this.type = Syntax.CallExpression;
this.callee = callee;
this.arguments = args;
this.finish();
return this;
}
public Node finishCatchClause(Node param, List<Node> body)
{
this.type = Syntax.CatchClause;
this.param = param;
this.body = body;
this.finish();
return this;
}
public Node finishClassBody(List<Node> body)
{
this.type = Syntax.ClassBody;
this.body = body;
this.finish();
return this;
}
public Node finishClassDeclaration(Node id, Node superClass, List<Node> body)
{
this.type = Syntax.ClassDeclaration;
this.id = id;
this.superClass = superClass;
this.body = body;
this.finish();
return this;
}
public Node finishClassExpression(Node id, Node superClass, List<Node> body)
{
this.type = Syntax.ClassExpression;
this.id = id;
this.superClass = superClass;
this.body = body;
this.finish();
return this;
}
public Node finishConditionalExpression(object test, object consequent, object alternate)
{
this.type = Syntax.ConditionalExpression;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
this.finish();
return this;
}
public Node finishContinueStatement(object label)
{
this.type = Syntax.ContinueStatement;
this.label = label;
this.finish();
return this;
}
public Node finishDebuggerStatement()
{
this.type = Syntax.DebuggerStatement;
this.finish();
return this;
}
public Node finishDoWhileStatement(List<Node> body, object test)
{
this.type = Syntax.DoWhileStatement;
this.body = body;
this.test = test;
this.finish();
return this;
}
public Node finishEmptyStatement()
{
this.type = Syntax.EmptyStatement;
this.finish();
return this;
}
public Node finishExpressionStatement(Node expression)
{
this.type = Syntax.ExpressionStatement;
this.expression = expression;
this.finish();
return this;
}
public Node finishForStatement(object init, object test, object update, List<Node> body)
{
this.type = Syntax.ForStatement;
this.init = init;
this.test = test;
this.update = update;
this.body = body;
this.finish();
return this;
}
public Node finishForOfStatement(Node left, Node right, List<Node> body)
{
this.type = Syntax.ForOfStatement;
this.left = left;
this.right = right;
this.body = body;
this.finish();
return this;
}
public Node finishForInStatement(Node left, Node right, List<Node> body)
{
this.type = Syntax.ForInStatement;
this.left = left;
this.right = right;
this.body = body;
this.each = false;
this.finish();
return this;
}
public Node finishFunctionDeclaration(Node id, List<Node> @params, object defaults, List<Node> body,
bool generator)
{
this.type = Syntax.FunctionDeclaration;
this.id = id;
this.@params = @params;
this.defaults = defaults;
this.body = body;
this.generator = generator;
this.expression = null;
this.finish();
return this;
}
public Node finishFunctionExpression(Node id, List<Node> @params, object defaults, List<Node> body,
bool generator)
{
this.type = Syntax.FunctionExpression;
this.id = id;
this.@params = @params;
this.defaults = defaults;
this.body = body;
this.generator = generator;
this.expression = null;
this.finish();
return this;
}
public Node finishIdentifier(string name)
{
this.type = Syntax.Identifier;
this.name = name;
this.finish();
return this;
}
public Node finishIfStatement(object test, object consequent, object alternate)
{
this.type = Syntax.IfStatement;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
this.finish();
return this;
}
public Node finishLabeledStatement(object label, List<Node> body)
{
this.type = Syntax.LabeledStatement;
this.label = label;
this.body = body;
this.finish();
return this;
}
public Node finishLiteral(Token token)
{
this.type = Syntax.Literal;
// this.value = ;
this.raw = token.value;// source.Substring(token.start, token.end - token.start);
if (token.regex != null)
{
this.regex = token.regex;
}
this.finish();
return this;
}
public Regex regex { get; set; }
public string raw { get; set; }
public Node finishMemberExpression(string accessor, object @object, object property)
{
this.type = Syntax.MemberExpression;
this.computed = accessor == "[";
this.@object = @object;
this.property = property;
this.finish();
return this;
}
public Node finishMetaProperty(object meta, object property)
{
this.type = Syntax.MetaProperty;
this.meta = meta;
this.property = property;
this.finish();
return this;
}
public Node finishNewExpression(object callee, object args)
{
this.type = Syntax.NewExpression;
this.callee = callee;
this.arguments = args;
this.finish();
return this;
}
public Node finishObjectExpression(List<Node> properties)
{
this.type = Syntax.ObjectExpression;
this.properties = properties;
this.finish();
return this;
}
public Node finishObjectPattern(List<Node> properties)
{
this.type = Syntax.ObjectPattern;
this.properties = properties;
this.finish();
return this;
}
public Node finishPostfixExpression(string @operator, Node argument)
{
this.type = Syntax.UpdateExpression;
this.@operator = @operator;
this.argument = argument;
this.prefix = false;
this.finish();
return this;
}
public Node finishProgram(List<Node> body, object sourceType)
{
this.type = Syntax.Program;
this.body = body;
this.sourceType = sourceType;
this.finish();
return this;
}
public Node finishProperty(string kind, Node key, bool computed, Node value, bool method, bool shorthand)
{
this.type = Syntax.Property;
this.key = key;
this.computed = computed;
this.value = value;
this.kind = kind;
this.method = method;
this.shorthand = shorthand;
this.finish();
return this;
}
public Node finishRestElement(Node argument)
{
this.type = Syntax.RestElement;
this.argument = argument;
this.finish();
return this;
}
public Node finishReturnStatement(Node argument)
{
this.type = Syntax.ReturnStatement;
this.argument = argument;
this.finish();
return this;
}
public Node finishSequenceExpression(List<Node> expressions)
{
this.type = Syntax.SequenceExpression;
this.expressions = expressions;
this.finish();
return this;
}
public Node finishSpreadElement(Node argument)
{
this.type = Syntax.SpreadElement;
this.argument = argument;
this.finish();
return this;
}
public Node finishSwitchCase(object test, object consequent)
{
this.type = Syntax.SwitchCase;
this.test = test;
this.consequent = consequent;
this.finish();
return this;
}
public Node finishSuper()
{
this.type = Syntax.Super;
this.finish();
return this;
}
public Node finishSwitchStatement(object discriminant, object cases)
{
this.type = Syntax.SwitchStatement;
this.discriminant = discriminant;
this.cases = cases;
this.finish();
return this;
}
public Node finishTaggedTemplateExpression(object tag, object quasi)
{
this.type = Syntax.TaggedTemplateExpression;
this.tag = tag;
this.quasi = quasi;
this.finish();
return this;
}
public Node finishTemplateElement(Node value, object tail)
{
this.type = Syntax.TemplateElement;
this.value = value;
this.tail = tail;
this.finish();
return this;
}
public Node finishTemplateLiteral(object quasis, List<Node> expressions)
{
this.type = Syntax.TemplateLiteral;
this.quasis = quasis;
this.expressions = expressions;
this.finish();
return this;
}
public Node finishThisExpression()
{
this.type = Syntax.ThisExpression;
this.finish();
return this;
}
public Node finishThrowStatement(Node argument)
{
this.type = Syntax.ThrowStatement;
this.argument = argument;
this.finish();
return this;
}
public Node finishTryStatement(Node block, Node handler, Node finalizer)
{
this.type = Syntax.TryStatement;
this.block = block;
this.guardedHandlers = new List<object>();
this.handlers = handler != null ? new List<object>() { handler } : new List<object>();
this.handler = handler;
this.finalizer = finalizer;
this.finish();
return this;
}
public Node finishUnaryExpression(string @operator, Node argument)
{
this.type = (@operator == "++" || @operator == "--") ? Syntax.UpdateExpression : Syntax.UnaryExpression;
this.@operator = @operator;
this.argument = argument;
this.prefix = true;
this.finish();
return this;
}
public Node finishVariableDeclaration(object declarations)
{
this.type = Syntax.VariableDeclaration;
this.declarations = declarations;
this.kind = "var";
this.finish();
return this;
}
public Node finishLexicalDeclaration(object declarations, string kind)
{
this.type = Syntax.VariableDeclaration;
this.declarations = declarations;
this.kind = kind;
this.finish();
return this;
}
public Node finishVariableDeclarator(Node id, object init)
{
this.type = Syntax.VariableDeclarator;
this.id = id;
this.init = init;
this.finish();
return this;
}
public Node finishWhileStatement(object test, List<Node> body)
{
this.type = Syntax.WhileStatement;
this.test = test;
this.body = body;
this.finish();
return this;
}
public Node finishWithStatement(object @object, List<Node> body)
{
this.type = Syntax.WithStatement;
this.@object = @object;
this.body = body;
this.finish();
return this;
}
public Node finishExportSpecifier(Node local, Node exported)
{
this.type = Syntax.ExportSpecifier;
this.exported = exported ?? local;
this.local = local;
this.finish();
return this;
}
public Node finishImportDefaultSpecifier(Node local)
{
this.type = Syntax.ImportDefaultSpecifier;
this.local = local;
this.finish();
return this;
}
public Node finishImportNamespaceSpecifier(Node local)
{
this.type = Syntax.ImportNamespaceSpecifier;
this.local = local;
this.finish();
return this;
}
public Node finishExportNamedDeclaration(object declaration, List<Node> specifiers, string src)
{
this.type = Syntax.ExportNamedDeclaration;
this.declaration = declaration;
this.specifiers = specifiers;
this.source = src;
this.finish();
return this;
}
public Node finishExportDefaultDeclaration(object declaration)
{
this.type = Syntax.ExportDefaultDeclaration;
this.declaration = declaration;
this.finish();
return this;
}
public Node finishExportAllDeclaration(string src)
{
this.type = Syntax.ExportAllDeclaration;
this.source = src;
this.finish();
return this;
}
public Node finishImportSpecifier(Node local, Node imported)
{
this.type = Syntax.ImportSpecifier;
this.local = local ?? imported;
this.imported = imported;
this.finish();
return this;
}
public Node finishImportDeclaration(List<Node> specifiers, string src)
{
this.type = Syntax.ImportDeclaration;
this.specifiers = specifiers;
this.source = src;
this.finish();
return this;
}
public Node finishYieldExpression(Node argument, bool @delegate)
{
this.type = Syntax.YieldExpression;
this.argument = argument;
this.@delegate = @delegate;
this.finish();
return this;
}
};
}
| |
// 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;
internal unsafe class testout1
{
public struct VT_0_1_1_1_1_1
{
public int a1_0_1_1_1_1_1;
public VT_0_1_1_1_1_1(int i)
{
a1_0_1_1_1_1_1 = 1;
}
}
public struct VT_0_1_1_1_1
{
public uint a1_0_1_1_1_1;
public VT_0_1_1_1_1(int i)
{
a1_0_1_1_1_1 = 1;
}
}
public struct VT_0_1_1
{
public int[] arr1d_0_1_1;
public VT_0_1_1(int i)
{
arr1d_0_1_1 = new int[9];
}
}
public struct VT_0_1
{
public int a1_0_1;
public VT_0_1(int i)
{
a1_0_1 = 1;
}
}
public class CL_0_1
{
public int a2_0_1 = 2111165575;
}
private static double[] s_arr1d_0_1_1_1_1_1_1_1_1_1 = new double[9];
private static float[,] s_arr2d_0_1_1_1_1_1_1_1_1 = new float[3, 9];
private static long[,] s_arr2d_0_1_1_1_1_1_1 = new long[3, 9];
private static int[,] s_arr2d_0_1_1_1_1_1 = new int[3, 9];
private static long[,,] s_arr3d_0_1_1_1_1 = new long[5, 9, 4];
private static double[] s_arr1d_0_1_1_1 = new double[9];
public static VT_0_1_1 vtstatic_0_1_1 = new VT_0_1_1(1);
public static VT_0_1 vtstatic_0_1 = new VT_0_1(1);
private static Decimal[,,] s_arr3d_0 = new Decimal[5, 9, 4];
private static long s_a1_0 = 512L;
private static ushort s_a2_0 = 54198;
public static float Func_0_1_1_1_1_1_1_1_1_1()
{
double* a1_0_1_1_1_1_1_1_1_1_1 = stackalloc double[1];
*a1_0_1_1_1_1_1_1_1_1_1 = 4.420911011650241E-09;
double* a3_0_1_1_1_1_1_1_1_1_1 = stackalloc double[1];
*a3_0_1_1_1_1_1_1_1_1_1 = 3.7252902984619141E-09;
s_arr1d_0_1_1_1_1_1_1_1_1_1[0] = 16384.0;
double asgop0 = s_arr1d_0_1_1_1_1_1_1_1_1_1[0];
asgop0 += ((s_arr1d_0_1_1_1_1_1_1_1_1_1[0] + -32512.0));
(*a3_0_1_1_1_1_1_1_1_1_1) *= ((206158430208.0));
if ((asgop0) >= ((*a1_0_1_1_1_1_1_1_1_1_1)))
{
float if0_0retval_0_1_1_1_1_1_1_1_1_1 = Convert.ToSingle(Convert.ToSingle((Convert.ToInt32((Convert.ToInt32(1218424101 * 0.37129554777249107)) * ((*a1_0_1_1_1_1_1_1_1_1_1)))) * (asgop0 + (*a3_0_1_1_1_1_1_1_1_1_1))));
return if0_0retval_0_1_1_1_1_1_1_1_1_1;
}
return Convert.ToSingle(Convert.ToSingle((Convert.ToInt32((Convert.ToInt32(1218424101 * 0.37129554777249107)) * ((*a1_0_1_1_1_1_1_1_1_1_1)))) * (asgop0 + (*a3_0_1_1_1_1_1_1_1_1_1))));
}
public static double Func_0_1_1_1_1_1_1_1_1()
{
double a2_0_1_1_1_1_1_1_1_1 = 2.0524928800798607E-08;
s_arr2d_0_1_1_1_1_1_1_1_1[2, 0] = -1920.0F;
float val_0_1_1_1_1_1_1_1_1_1 = Func_0_1_1_1_1_1_1_1_1_1();
double retval_0_1_1_1_1_1_1_1_1 = Convert.ToDouble((Convert.ToUInt16(val_0_1_1_1_1_1_1_1_1_1 + s_arr2d_0_1_1_1_1_1_1_1_1[2, 0]) / (29637 * (4.6566128730773926E-10 + a2_0_1_1_1_1_1_1_1_1))));
return retval_0_1_1_1_1_1_1_1_1;
}
public static ushort Func_0_1_1_1_1_1_1_1()
{
ulong[] arr1d_0_1_1_1_1_1_1_1 = new ulong[9];
arr1d_0_1_1_1_1_1_1_1[0] = 10247887074558758525UL;
double val_0_1_1_1_1_1_1_1_1 = Func_0_1_1_1_1_1_1_1_1();
if ((arr1d_0_1_1_1_1_1_1_1[0]) <= (10247887076011802624UL))
{
ushort if0_0retval_0_1_1_1_1_1_1_1 = Convert.ToUInt16((Convert.ToUInt16(Convert.ToInt32(Convert.ToUInt64(10247887076011802624UL) - Convert.ToUInt64(arr1d_0_1_1_1_1_1_1_1[0])) / val_0_1_1_1_1_1_1_1_1)));
return if0_0retval_0_1_1_1_1_1_1_1;
}
ushort retval_0_1_1_1_1_1_1_1 = Convert.ToUInt16((Convert.ToUInt16(Convert.ToInt32(Convert.ToUInt64(10247887076011802624UL) - Convert.ToUInt64(arr1d_0_1_1_1_1_1_1_1[0])) / val_0_1_1_1_1_1_1_1_1)));
return retval_0_1_1_1_1_1_1_1;
}
public static long Func_0_1_1_1_1_1_1()
{
short* a2_0_1_1_1_1_1_1 = stackalloc short[1];
*a2_0_1_1_1_1_1_1 = 4375;
s_arr2d_0_1_1_1_1_1_1[2, 0] = -8828430758416264124L;
ushort val_0_1_1_1_1_1_1_1 = Func_0_1_1_1_1_1_1_1();
if ((s_arr2d_0_1_1_1_1_1_1[2, 0]) > (Convert.ToInt64(Convert.ToInt16(((*a2_0_1_1_1_1_1_1))) + Convert.ToInt64(s_arr2d_0_1_1_1_1_1_1[2, 0]))))
Console.WriteLine("Func_0_1_1_1_1_1_1: > true");
long retval_0_1_1_1_1_1_1 = Convert.ToInt64(Convert.ToInt64(Convert.ToUInt16(val_0_1_1_1_1_1_1_1) + Convert.ToInt64(Convert.ToInt64(Convert.ToInt16(((*a2_0_1_1_1_1_1_1))) + Convert.ToInt64(s_arr2d_0_1_1_1_1_1_1[2, 0])))));
return retval_0_1_1_1_1_1_1;
}
public static long Func_0_1_1_1_1_1()
{
VT_0_1_1_1_1_1 vt_0_1_1_1_1_1 = new VT_0_1_1_1_1_1(1);
vt_0_1_1_1_1_1.a1_0_1_1_1_1_1 = 1977572086;
float[] arr1d_0_1_1_1_1_1 = new float[9];
arr1d_0_1_1_1_1_1[0] = 0.5699924F;
s_arr2d_0_1_1_1_1_1[2, 2] = 708678031;
long val_0_1_1_1_1_1_1 = Func_0_1_1_1_1_1_1();
int asgop0 = vt_0_1_1_1_1_1.a1_0_1_1_1_1_1;
asgop0 %= (Convert.ToInt32((Convert.ToInt32((Convert.ToInt32(((Convert.ToInt32(64462) + 1977507624) - 1268894055)))))));
if ((arr1d_0_1_1_1_1_1[0]) <= 10)
{
if ((arr1d_0_1_1_1_1_1[0]) == 10)
{
long if1_0retval_0_1_1_1_1_1 = Convert.ToInt64(Convert.ToInt64(Convert.ToUInt32(Convert.ToUInt32(asgop0 / Convert.ToSingle(arr1d_0_1_1_1_1_1[0]))) - Convert.ToInt64(Convert.ToInt64(Convert.ToInt32(s_arr2d_0_1_1_1_1_1[2, 2]) + Convert.ToInt64(val_0_1_1_1_1_1_1)))));
return if1_0retval_0_1_1_1_1_1;
}
}
else
{
long else0_0retval_0_1_1_1_1_1 = Convert.ToInt64(Convert.ToInt64(Convert.ToUInt32(Convert.ToUInt32(asgop0 / Convert.ToSingle(arr1d_0_1_1_1_1_1[0]))) - Convert.ToInt64(Convert.ToInt64(Convert.ToInt32(s_arr2d_0_1_1_1_1_1[2, 2]) + Convert.ToInt64(val_0_1_1_1_1_1_1)))));
return else0_0retval_0_1_1_1_1_1;
}
long retval_0_1_1_1_1_1 = Convert.ToInt64(Convert.ToInt64(Convert.ToUInt32(Convert.ToUInt32(asgop0 / Convert.ToSingle(arr1d_0_1_1_1_1_1[0]))) - Convert.ToInt64(Convert.ToInt64(Convert.ToInt32(s_arr2d_0_1_1_1_1_1[2, 2]) + Convert.ToInt64(val_0_1_1_1_1_1_1)))));
return retval_0_1_1_1_1_1;
}
public static long Func_0_1_1_1_1()
{
VT_0_1_1_1_1 vt_0_1_1_1_1 = new VT_0_1_1_1_1(1);
vt_0_1_1_1_1.a1_0_1_1_1_1 = 2399073536U;
double* a2_0_1_1_1_1 = stackalloc double[1];
*a2_0_1_1_1_1 = 1.0000000000002376;
s_arr3d_0_1_1_1_1[4, 0, 3] = -2399073472L;
long val_0_1_1_1_1_1 = Func_0_1_1_1_1_1();
if ((Convert.ToInt64(Convert.ToDouble(8828430758690422784L) * ((*a2_0_1_1_1_1)))) < (8828430758690422784L))
{
return Convert.ToInt64((Convert.ToInt64((Convert.ToInt64(Convert.ToDouble(8828430758690422784L) * ((*a2_0_1_1_1_1))) - val_0_1_1_1_1_1) / (Convert.ToInt64((Convert.ToInt64(vt_0_1_1_1_1.a1_0_1_1_1_1) + s_arr3d_0_1_1_1_1[4, 0, 3]) / (Convert.ToInt64(Convert.ToInt64(Convert.ToDouble(s_arr3d_0_1_1_1_1[4, 0, 3]) * -8.3365516869005671E-10)) * Convert.ToInt64((Convert.ToInt64(s_arr3d_0_1_1_1_1[4, 0, 3] / s_arr3d_0_1_1_1_1[4, 0, 3])))))))));
}
return Convert.ToInt64((Convert.ToInt64((Convert.ToInt64(Convert.ToDouble(8828430758690422784L) * ((*a2_0_1_1_1_1))) - val_0_1_1_1_1_1) / (Convert.ToInt64((Convert.ToInt64(vt_0_1_1_1_1.a1_0_1_1_1_1) + s_arr3d_0_1_1_1_1[4, 0, 3]) / (Convert.ToInt64(Convert.ToInt64(Convert.ToDouble(s_arr3d_0_1_1_1_1[4, 0, 3]) * -8.3365516869005671E-10)) * Convert.ToInt64((Convert.ToInt64(s_arr3d_0_1_1_1_1[4, 0, 3] / s_arr3d_0_1_1_1_1[4, 0, 3])))))))));
}
public static short Func_0_1_1_1()
{
s_arr1d_0_1_1_1[0] = -4.0;
long val_0_1_1_1_1 = Func_0_1_1_1_1();
double asgop0 = -1.798828125;
asgop0 -= ((-5.798828125));
double asgop1 = -5.798828125;
asgop1 -= ((s_arr1d_0_1_1_1[0]));
return Convert.ToInt16((Convert.ToInt16((val_0_1_1_1_1 / asgop0) - ((Convert.ToDouble(8192UL * asgop1))))));
}
public static ushort Func_0_1_1()
{
double[,,] arr3d_0_1_1 = new double[5, 9, 4];
vtstatic_0_1_1.arr1d_0_1_1[1] = 1335221039;
arr3d_0_1_1[4, 0, 3] = 5.339914645886728E-10;
arr3d_0_1_1[4, 2, 3] = 1.2023524862987123;
short val_0_1_1_1 = Func_0_1_1_1();
if ((arr3d_0_1_1[4, 0, 3]) >= (arr3d_0_1_1[4, 2, 3]))
{
if ((val_0_1_1_1) >= (Convert.ToInt16((Convert.ToInt16(val_0_1_1_1)) % (Convert.ToInt16(15783)))))
{
return Convert.ToUInt16(Convert.ToUInt16(Convert.ToInt16((Convert.ToInt16(val_0_1_1_1)) % (Convert.ToInt16(15783))) * Convert.ToSingle(Convert.ToSingle(Convert.ToUInt32(vtstatic_0_1_1.arr1d_0_1_1[1] * arr3d_0_1_1[4, 2, 3]) * arr3d_0_1_1[4, 0, 3]))));
}
else
{
if ((val_0_1_1_1) > (Convert.ToInt16((Convert.ToInt16(val_0_1_1_1)) % (Convert.ToInt16(15783)))))
Console.WriteLine("Func_0_1_1: > true");
else
{
return Convert.ToUInt16(Convert.ToUInt16(Convert.ToInt16((Convert.ToInt16(val_0_1_1_1)) % (Convert.ToInt16(15783))) * Convert.ToSingle(Convert.ToSingle(Convert.ToUInt32(vtstatic_0_1_1.arr1d_0_1_1[1] * arr3d_0_1_1[4, 2, 3]) * arr3d_0_1_1[4, 0, 3]))));
}
}
}
return Convert.ToUInt16(Convert.ToUInt16(Convert.ToInt16((Convert.ToInt16(val_0_1_1_1)) % (Convert.ToInt16(15783))) * Convert.ToSingle(Convert.ToSingle(Convert.ToUInt32(vtstatic_0_1_1.arr1d_0_1_1[1] * arr3d_0_1_1[4, 2, 3]) * arr3d_0_1_1[4, 0, 3]))));
}
public static int Func_0_1()
{
CL_0_1 cl_0_1 = new CL_0_1();
long[,] arr2d_0_1 = new long[3, 9];
vtstatic_0_1.a1_0_1 = 2111178723;
arr2d_0_1[2, 0] = 3029300220748914301L;
ushort val_0_1_1 = Func_0_1_1();
int asgop0 = vtstatic_0_1.a1_0_1;
asgop0 += ((Convert.ToInt32(Convert.ToInt64(3029300219813560320L) - Convert.ToInt64(arr2d_0_1[2, 0]))));
return Convert.ToInt32((Convert.ToInt32((Convert.ToInt32((Convert.ToInt32(val_0_1_1) + cl_0_1.a2_0_1))) % (Convert.ToInt32(asgop0)))));
}
public static int Func_0()
{
s_arr3d_0[4, 0, 3] = 112.75552824827484409018782981M;
int val_0_1 = Func_0_1();
int retval_0 = Convert.ToInt32(Convert.ToInt32(Convert.ToDecimal((Convert.ToInt32(val_0_1 * (s_a2_0 / 41477.078575715459)))) / (Convert.ToDecimal(Convert.ToInt64(Convert.ToDouble(s_a1_0) * 0.00390625) * (Convert.ToDecimal(s_a2_0) * s_arr3d_0[4, 0, 3])))));
return retval_0;
}
public static int Main()
{
s_arr3d_0[4, 0, 3] = 112.75552824827484409018782981M;
int retval;
retval = Convert.ToInt32(Func_0());
if ((retval >= 99) && (retval < 100))
retval = 100;
if ((retval > 100) && (retval <= 101))
retval = 100;
Console.WriteLine(retval);
return retval;
}
}
| |
// 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 Microsoft.CSharp.RuntimeBinder;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// enum identifying all predefined methods used in the C# compiler
//
// Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Method>
// if methods can only be disambiguated by signature, then follow the
// above with _ <argument types>
//
// Keep this list sorted by containing type and name.
internal enum PREDEFMETH
{
PM_FIRST = 0,
PM_ARRAY_GETLENGTH,
PM_DECIMAL_OPDECREMENT,
PM_DECIMAL_OPDIVISION,
PM_DECIMAL_OPEQUALITY,
PM_DECIMAL_OPGREATERTHAN,
PM_DECIMAL_OPGREATERTHANOREQUAL,
PM_DECIMAL_OPINCREMENT,
PM_DECIMAL_OPINEQUALITY,
PM_DECIMAL_OPLESSTHAN,
PM_DECIMAL_OPLESSTHANOREQUAL,
PM_DECIMAL_OPMINUS,
PM_DECIMAL_OPMODULUS,
PM_DECIMAL_OPMULTIPLY,
PM_DECIMAL_OPPLUS,
PM_DECIMAL_OPUNARYMINUS,
PM_DECIMAL_OPUNARYPLUS,
PM_DELEGATE_COMBINE,
PM_DELEGATE_OPEQUALITY,
PM_DELEGATE_OPINEQUALITY,
PM_DELEGATE_REMOVE,
PM_EXPRESSION_ADD,
PM_EXPRESSION_ADD_USER_DEFINED,
PM_EXPRESSION_ADDCHECKED,
PM_EXPRESSION_ADDCHECKED_USER_DEFINED,
PM_EXPRESSION_AND,
PM_EXPRESSION_AND_USER_DEFINED,
PM_EXPRESSION_ANDALSO,
PM_EXPRESSION_ANDALSO_USER_DEFINED,
PM_EXPRESSION_ARRAYINDEX,
PM_EXPRESSION_ARRAYINDEX2,
PM_EXPRESSION_ASSIGN,
PM_EXPRESSION_CONDITION,
PM_EXPRESSION_CONSTANT_OBJECT_TYPE,
PM_EXPRESSION_CONVERT,
PM_EXPRESSION_CONVERT_USER_DEFINED,
PM_EXPRESSION_CONVERTCHECKED,
PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED,
PM_EXPRESSION_DIVIDE,
PM_EXPRESSION_DIVIDE_USER_DEFINED,
PM_EXPRESSION_EQUAL,
PM_EXPRESSION_EQUAL_USER_DEFINED,
PM_EXPRESSION_EXCLUSIVEOR,
PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED,
PM_EXPRESSION_FIELD,
PM_EXPRESSION_GREATERTHAN,
PM_EXPRESSION_GREATERTHAN_USER_DEFINED,
PM_EXPRESSION_GREATERTHANOREQUAL,
PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED,
PM_EXPRESSION_LAMBDA,
PM_EXPRESSION_LEFTSHIFT,
PM_EXPRESSION_LEFTSHIFT_USER_DEFINED,
PM_EXPRESSION_LESSTHAN,
PM_EXPRESSION_LESSTHAN_USER_DEFINED,
PM_EXPRESSION_LESSTHANOREQUAL,
PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED,
PM_EXPRESSION_MODULO,
PM_EXPRESSION_MODULO_USER_DEFINED,
PM_EXPRESSION_MULTIPLY,
PM_EXPRESSION_MULTIPLY_USER_DEFINED,
PM_EXPRESSION_MULTIPLYCHECKED,
PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED,
PM_EXPRESSION_NOTEQUAL,
PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
PM_EXPRESSION_OR,
PM_EXPRESSION_OR_USER_DEFINED,
PM_EXPRESSION_ORELSE,
PM_EXPRESSION_ORELSE_USER_DEFINED,
PM_EXPRESSION_PARAMETER,
PM_EXPRESSION_RIGHTSHIFT,
PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED,
PM_EXPRESSION_SUBTRACT,
PM_EXPRESSION_SUBTRACT_USER_DEFINED,
PM_EXPRESSION_SUBTRACTCHECKED,
PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED,
PM_EXPRESSION_UNARYPLUS_USER_DEFINED,
PM_EXPRESSION_NEGATE,
PM_EXPRESSION_NEGATE_USER_DEFINED,
PM_EXPRESSION_NEGATECHECKED,
PM_EXPRESSION_NEGATECHECKED_USER_DEFINED,
PM_EXPRESSION_CALL,
PM_EXPRESSION_NEW,
PM_EXPRESSION_NEW_MEMBERS,
PM_EXPRESSION_NEW_TYPE,
PM_EXPRESSION_QUOTE,
PM_EXPRESSION_ARRAYLENGTH,
PM_EXPRESSION_NOT,
PM_EXPRESSION_NOT_USER_DEFINED,
PM_EXPRESSION_NEWARRAYINIT,
PM_EXPRESSION_PROPERTY,
PM_EXPRESSION_INVOKE,
PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT,
PM_G_OPTIONAL_CTOR,
PM_G_OPTIONAL_GETHASVALUE,
PM_G_OPTIONAL_GETVALUE,
PM_G_OPTIONAL_GET_VALUE_OR_DEF,
PM_STRING_CONCAT_OBJECT_1, // NOTE: these 3 must be sequential. See RealizeConcats
PM_STRING_CONCAT_OBJECT_2,
PM_STRING_CONCAT_OBJECT_3,
PM_STRING_CONCAT_STRING_1, // NOTE: these 4 must be sequential. See RealizeConcats
PM_STRING_CONCAT_STRING_2,
PM_STRING_CONCAT_STRING_3,
PM_STRING_CONCAT_STRING_4,
PM_STRING_CONCAT_SZ_OBJECT,
PM_STRING_CONCAT_SZ_STRING,
PM_STRING_GETCHARS,
PM_STRING_GETLENGTH,
PM_STRING_OPEQUALITY,
PM_STRING_OPINEQUALITY,
PM_COUNT
}
// enum identifying all predefined properties used in the C# compiler
// Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Property>
// Keep this list sorted by containing type and name.
internal enum PREDEFPROP
{
PP_FIRST = 0,
PP_ARRAY_LENGTH,
PP_G_OPTIONAL_VALUE,
PP_COUNT,
};
internal enum MethodRequiredEnum
{
Required,
Optional
}
internal enum MethodCallingConventionEnum
{
Static,
Virtual,
Instance
}
// Enum used to encode a method signature
// A signature is encoded as a sequence of int values.
// The grammar for signatures is:
//
// signature
// return_type count_of_parameters parameter_types
//
// type
// any predefined type (ex: PredefinedType.PT_OBJECT, PredefinedType.PT_VOID) type_args
// MethodSignatureEnum.SIG_CLASS_TYVAR index_of_class_tyvar
// MethodSignatureEnum.SIG_METH_TYVAR index_of_method_tyvar
// MethodSignatureEnum.SIG_SZ_ARRAY type
// MethodSignatureEnum.SIG_REF type
// MethodSignatureEnum.SIG_OUT type
//
internal enum MethodSignatureEnum
{
// Values 0 to PredefinedType.PT_VOID are reserved for predefined types in signatures
// start next value at PredefinedType.PT_VOID + 1,
SIG_CLASS_TYVAR = (int)PredefinedType.PT_VOID + 1, // next element in signature is index of class tyvar
SIG_METH_TYVAR, // next element in signature is index of method tyvar
SIG_SZ_ARRAY, // must be followed by signature type of array elements
SIG_REF, // must be followed by signature of ref type
SIG_OUT, // must be followed by signature of out type
}
// A description of a method the compiler uses while compiling.
internal class PredefinedMethodInfo
{
public PREDEFMETH method;
public PredefinedType type;
public PredefinedName name;
public MethodCallingConventionEnum callingConvention;
public ACCESS access; // ACCESS.ACC_UNKNOWN means any accessibility is ok
public int cTypeVars;
public int[] signature; // Size 8. expand this if a new method has a signature which doesn't fit in the current space
public PredefinedMethodInfo(PREDEFMETH method, MethodRequiredEnum required, PredefinedType type, PredefinedName name, MethodCallingConventionEnum callingConvention, ACCESS access, int cTypeVars, int[] signature)
{
this.method = method;
this.type = type;
this.name = name;
this.callingConvention = callingConvention;
this.access = access;
this.cTypeVars = cTypeVars;
this.signature = signature;
}
}
// A description of a method the compiler uses while compiling.
internal class PredefinedPropertyInfo
{
public PREDEFPROP property;
public PredefinedName name;
public PREDEFMETH getter;
public PREDEFMETH setter;
public PredefinedPropertyInfo(PREDEFPROP property, MethodRequiredEnum required, PredefinedName name, PREDEFMETH getter, PREDEFMETH setter)
{
this.property = property;
this.name = name;
this.getter = getter;
this.setter = setter;
}
};
// Loads and caches predefined members.
// Also finds constructors on delegate types.
internal class PredefinedMembers
{
protected static void RETAILVERIFY(bool f)
{
if (!f)
Debug.Assert(false, "panic!");
}
private SymbolLoader _loader;
internal SymbolTable RuntimeBinderSymbolTable;
private MethodSymbol[] _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT];
private PropertySymbol[] _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT];
private Name GetMethName(PREDEFMETH method)
{
return GetPredefName(GetMethPredefName(method));
}
private AggregateSymbol GetMethParent(PREDEFMETH method)
{
return GetOptPredefAgg(GetMethPredefType(method));
}
// delegate specific helpers
private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, int[] signature)
{
Debug.Assert(delegateType != null && delegateType.IsDelegate());
Debug.Assert(signature != null);
return LoadMethod(
delegateType,
signature,
0, // meth ty vars
GetPredefName(PredefinedName.PN_CTOR),
ACCESS.ACC_PUBLIC,
false, // MethodCallingConventionEnum.Static
false); // MethodCallingConventionEnum.Virtual
}
private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType)
{
Debug.Assert(delegateType != null && delegateType.IsDelegate());
MethodSymbol ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature1);
if (ctor == null)
{
ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature2);
}
return ctor;
}
public MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, bool fReportErrors)
{
MethodSymbol ctor = FindDelegateConstructor(delegateType);
if (ctor == null && fReportErrors)
{
GetErrorContext().Error(ErrorCode.ERR_BadDelegateConstructor, delegateType);
}
return ctor;
}
// property specific helpers
private PropertySymbol EnsureProperty(PREDEFPROP property)
{
RETAILVERIFY((int)property > (int)PREDEFMETH.PM_FIRST && (int)property < (int)PREDEFMETH.PM_COUNT);
if (_properties[(int)property] == null)
{
_properties[(int)property] = LoadProperty(property);
}
return _properties[(int)property];
}
private PropertySymbol LoadProperty(PREDEFPROP property)
{
return LoadProperty(
property,
GetPropName(property),
GetPropGetter(property),
GetPropSetter(property));
}
private Name GetPropName(PREDEFPROP property)
{
return GetPredefName(GetPropPredefName(property));
}
private PropertySymbol LoadProperty(
PREDEFPROP predefProp,
Name propertyName,
PREDEFMETH propertyGetter,
PREDEFMETH propertySetter)
{
Debug.Assert(propertyName != null);
Debug.Assert(propertyGetter > PREDEFMETH.PM_FIRST && propertyGetter < PREDEFMETH.PM_COUNT);
Debug.Assert(propertySetter > PREDEFMETH.PM_FIRST && propertySetter <= PREDEFMETH.PM_COUNT);
MethodSymbol getter = GetOptionalMethod(propertyGetter);
MethodSymbol setter = null;
if (propertySetter != PREDEFMETH.PM_COUNT)
{
setter = GetOptionalMethod(propertySetter);
}
if (getter == null && setter == null)
{
RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName);
getter = GetOptionalMethod(propertyGetter);
if (propertySetter != PREDEFMETH.PM_COUNT)
{
setter = GetOptionalMethod(propertySetter);
}
}
if (setter != null)
{
setter.SetMethKind(MethodKindEnum.PropAccessor);
}
PropertySymbol property = null;
if (getter != null)
{
getter.SetMethKind(MethodKindEnum.PropAccessor);
property = getter.getProperty();
// Didn't find it, so load it.
if (property == null)
{
RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName);
}
property = getter.getProperty();
Debug.Assert(property != null);
if (property.name != propertyName ||
(propertySetter != PREDEFMETH.PM_COUNT &&
(setter == null ||
!setter.isPropertyAccessor() ||
setter.getProperty() != property)) ||
property.getBogus())
{
property = null;
}
}
return property;
}
private SymbolLoader GetSymbolLoader()
{
Debug.Assert(_loader != null);
return _loader;
}
private ErrorHandling GetErrorContext()
{
return GetSymbolLoader().GetErrorContext();
}
private NameManager GetNameManager()
{
return GetSymbolLoader().GetNameManager();
}
private TypeManager GetTypeManager()
{
return GetSymbolLoader().GetTypeManager();
}
private BSYMMGR getBSymmgr()
{
return GetSymbolLoader().getBSymmgr();
}
private Name GetPredefName(PredefinedName pn)
{
return GetNameManager().GetPredefName(pn);
}
private AggregateSymbol GetOptPredefAgg(PredefinedType pt)
{
return GetSymbolLoader().GetOptPredefAgg(pt);
}
private CType LoadTypeFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars)
{
Debug.Assert(signature != null);
MethodSignatureEnum current = (MethodSignatureEnum)signature[indexIntoSignatures];
indexIntoSignatures++;
switch (current)
{
case MethodSignatureEnum.SIG_REF:
{
CType refType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars);
if (refType == null)
{
return null;
}
return GetTypeManager().GetParameterModifier(refType, false);
}
case MethodSignatureEnum.SIG_OUT:
{
CType outType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars);
if (outType == null)
{
return null;
}
return GetTypeManager().GetParameterModifier(outType, true);
}
case MethodSignatureEnum.SIG_SZ_ARRAY:
{
CType elementType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars);
if (elementType == null)
{
return null;
}
return GetTypeManager().GetArray(elementType, 1);
}
case MethodSignatureEnum.SIG_METH_TYVAR:
{
int index = signature[indexIntoSignatures];
indexIntoSignatures++;
return GetTypeManager().GetStdMethTypeVar(index);
}
case MethodSignatureEnum.SIG_CLASS_TYVAR:
{
int index = signature[indexIntoSignatures];
indexIntoSignatures++;
return classTyVars.Item(index);
}
case (MethodSignatureEnum)PredefinedType.PT_VOID:
return GetTypeManager().GetVoid();
default:
{
Debug.Assert(current >= 0 && (int)current < (int)PredefinedType.PT_COUNT);
AggregateSymbol agg = GetOptPredefAgg((PredefinedType)current);
if (agg != null)
{
CType[] typeArgs = new CType[agg.GetTypeVars().size];
for (int iTypeArg = 0; iTypeArg < agg.GetTypeVars().size; iTypeArg++)
{
typeArgs[iTypeArg] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars);
if (typeArgs[iTypeArg] == null)
{
return null;
}
}
AggregateType type = GetTypeManager().GetAggregate(agg, getBSymmgr().AllocParams(agg.GetTypeVars().size, typeArgs));
if (type.isPredefType(PredefinedType.PT_G_OPTIONAL))
{
return GetTypeManager().GetNubFromNullable(type);
}
return type;
}
}
break;
}
return null;
}
private TypeArray LoadTypeArrayFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars)
{
Debug.Assert(signature != null);
int count = signature[indexIntoSignatures];
indexIntoSignatures++;
Debug.Assert(count >= 0);
CType[] ptypes = new CType[count];
for (int i = 0; i < count; i++)
{
ptypes[i] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars);
if (ptypes[i] == null)
{
return null;
}
}
return getBSymmgr().AllocParams(count, ptypes);
}
public PredefinedMembers(SymbolLoader loader)
{
_loader = loader;
Debug.Assert(_loader != null);
_methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT];
_properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT];
#if DEBUG
// validate the tables
for (int i = (int)PREDEFMETH.PM_FIRST + 1; i < (int)PREDEFMETH.PM_COUNT; i++)
{
Debug.Assert((int)GetMethInfo((PREDEFMETH)i).method == i);
}
for (int i = (int)PREDEFPROP.PP_FIRST + 1; i < (int)PREDEFPROP.PP_COUNT; i++)
{
Debug.Assert((int)GetPropInfo((PREDEFPROP)i).property == i);
}
#endif
}
public PropertySymbol GetProperty(PREDEFPROP property) // Reports an error if the property is not found.
{
PropertySymbol result = EnsureProperty(property);
if (result == null)
{
ReportError(property);
}
return result;
}
public MethodSymbol GetMethod(PREDEFMETH method)
{
MethodSymbol result = EnsureMethod(method);
if (result == null)
{
ReportError(method);
}
return result;
}
public MethodSymbol GetOptionalMethod(PREDEFMETH method)
{
return EnsureMethod(method);
}
private MethodSymbol EnsureMethod(PREDEFMETH method)
{
RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT);
if (_methods[(int)method] == null)
{
_methods[(int)method] = LoadMethod(method);
}
return _methods[(int)method];
}
private MethodSymbol LoadMethod(
AggregateSymbol type,
int[] signature,
int cMethodTyVars,
Name methodName,
ACCESS methodAccess,
bool isStatic,
bool isVirtual
)
{
Debug.Assert(signature != null);
Debug.Assert(cMethodTyVars >= 0);
Debug.Assert(methodName != null);
if (type == null)
{
return null;
}
TypeArray classTyVars = type.GetTypeVarsAll();
int index = 0;
CType returnType = LoadTypeFromSignature(signature, ref index, classTyVars);
if (returnType == null)
{
return null;
}
TypeArray argumentTypes = LoadTypeArrayFromSignature(signature, ref index, classTyVars);
if (argumentTypes == null)
{
return null;
}
TypeArray standardMethodTyVars = GetTypeManager().GetStdMethTyVarArray(cMethodTyVars);
MethodSymbol ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes);
if (ret == null)
{
RuntimeBinderSymbolTable.AddPredefinedMethodToSymbolTable(type, methodName);
ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes);
}
return ret;
}
private MethodSymbol LookupMethodWhileLoading(AggregateSymbol type, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual, CType returnType, TypeArray argumentTypes)
{
for (Symbol sym = GetSymbolLoader().LookupAggMember(methodName, type, symbmask_t.MASK_ALL);
sym != null;
sym = GetSymbolLoader().LookupNextSym(sym, type, symbmask_t.MASK_ALL))
{
if (sym.IsMethodSymbol())
{
MethodSymbol methsym = sym.AsMethodSymbol();
if ((methsym.GetAccess() == methodAccess || methodAccess == ACCESS.ACC_UNKNOWN) &&
methsym.isStatic == isStatic &&
methsym.isVirtual == isVirtual &&
methsym.typeVars.size == cMethodTyVars &&
GetTypeManager().SubstEqualTypes(methsym.RetType, returnType, null, methsym.typeVars, SubstTypeFlags.DenormMeth) &&
GetTypeManager().SubstEqualTypeArrays(methsym.Params, argumentTypes, (TypeArray)null,
methsym.typeVars, SubstTypeFlags.DenormMeth) &&
!methsym.getBogus())
{
return methsym;
}
}
}
return null;
}
private MethodSymbol LoadMethod(PREDEFMETH method)
{
return LoadMethod(
GetMethParent(method),
GetMethSignature(method),
GetMethTyVars(method),
GetMethName(method),
GetMethAccess(method),
IsMethStatic(method),
IsMethVirtual(method));
}
private void ReportError(PREDEFMETH method)
{
ReportError(GetMethPredefType(method), GetMethPredefName(method));
}
private void ReportError(PredefinedType type, PredefinedName name)
{
GetErrorContext().Error(ErrorCode.ERR_MissingPredefinedMember, PredefinedTypes.GetFullName(type), GetPredefName(name));
}
private static int[] s_DelegateCtorSignature1 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_INTPTR };
private static int[] s_DelegateCtorSignature2 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_UINTPTR };
private static PredefinedName GetPropPredefName(PREDEFPROP property)
{
return GetPropInfo(property).name;
}
private static PREDEFMETH GetPropGetter(PREDEFPROP property)
{
PREDEFMETH result = GetPropInfo(property).getter;
// getters are MethodRequiredEnum.Required
Debug.Assert(result > PREDEFMETH.PM_FIRST && result < PREDEFMETH.PM_COUNT);
return result;
}
private static PredefinedType GetPropPredefType(PREDEFPROP property)
{
return GetMethInfo(GetPropGetter(property)).type;
}
private static PREDEFMETH GetPropSetter(PREDEFPROP property)
{
PREDEFMETH result = GetPropInfo(property).setter;
// setters are not MethodRequiredEnum.Required
Debug.Assert(result > PREDEFMETH.PM_FIRST && result <= PREDEFMETH.PM_COUNT);
return GetPropInfo(property).setter;
}
private void ReportError(PREDEFPROP property)
{
ReportError(GetPropPredefType(property), GetPropPredefName(property));
}
// the list of predefined property definitions.
// This list must be in the same order as the PREDEFPROP enum.
private static PredefinedPropertyInfo[] s_predefinedProperties = {
new PredefinedPropertyInfo( PREDEFPROP.PP_FIRST, MethodRequiredEnum.Optional, PredefinedName.PN_COUNT, PREDEFMETH.PM_COUNT, PREDEFMETH.PM_COUNT ),
new PredefinedPropertyInfo( PREDEFPROP.PP_ARRAY_LENGTH, MethodRequiredEnum.Optional, PredefinedName.PN_LENGTH, PREDEFMETH.PM_ARRAY_GETLENGTH, PREDEFMETH.PM_COUNT ),
new PredefinedPropertyInfo( PREDEFPROP.PP_G_OPTIONAL_VALUE, MethodRequiredEnum.Optional, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PREDEFMETH.PM_COUNT ),
};
public static PredefinedPropertyInfo GetPropInfo(PREDEFPROP property)
{
RETAILVERIFY(property > PREDEFPROP.PP_FIRST && property < PREDEFPROP.PP_COUNT);
RETAILVERIFY(s_predefinedProperties[(int)property].property == property);
return s_predefinedProperties[(int)property];
}
public static PredefinedMethodInfo GetMethInfo(PREDEFMETH method)
{
RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT);
RETAILVERIFY(s_predefinedMethods[(int)method].method == method);
return s_predefinedMethods[(int)method];
}
private static PredefinedName GetMethPredefName(PREDEFMETH method)
{
return GetMethInfo(method).name;
}
private static PredefinedType GetMethPredefType(PREDEFMETH method)
{
return GetMethInfo(method).type;
}
private static bool IsMethStatic(PREDEFMETH method)
{
return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Static;
}
private static bool IsMethVirtual(PREDEFMETH method)
{
return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Virtual;
}
private static ACCESS GetMethAccess(PREDEFMETH method)
{
return GetMethInfo(method).access;
}
private static int GetMethTyVars(PREDEFMETH method)
{
return GetMethInfo(method).cTypeVars;
}
private static int[] GetMethSignature(PREDEFMETH method)
{
return GetMethInfo(method).signature;
}
// the list of predefined method definitions.
// This list must be in the same order as the PREDEFMETH enum.
private static PredefinedMethodInfo[] s_predefinedMethods = new PredefinedMethodInfo[(int)PREDEFMETH.PM_COUNT] {
new PredefinedMethodInfo( PREDEFMETH.PM_FIRST, MethodRequiredEnum.Optional, PredefinedType.PT_COUNT, PredefinedName.PN_COUNT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 0 }),
new PredefinedMethodInfo( PREDEFMETH.PM_ARRAY_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_ARRAY, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0 }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDECREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDIVISION, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDIVISION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINCREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMODULUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMODULUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_COMBINE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_REMOVE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_REMOVE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ASSIGN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ASSIGN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONDITION, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONDITION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONDITIONALEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONSTANT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONSTANTEXPRESSION, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_TYPE }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_FIELD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CAP_FIELD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_FIELDINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LAMBDA, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LAMBDA, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 1, new int[] { (int)PredefinedType.PT_G_EXPRESSION, (int)MethodSignatureEnum.SIG_METH_TYVAR, 0, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_PARAMETEREXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PARAMETER, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PARAMETER, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_PARAMETEREXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PLUS , MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CALL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CALL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 2, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 3, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)PredefinedType.PT_G_IENUMERABLE, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_MEMBERINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 1, (int)PredefinedType.PT_TYPE }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_QUOTE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_QUOTE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYLENGTH, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEWARRAYINIT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWARRAYEXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PROPERTY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXPRESSION_PROPERTY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_PROPERTYINFO }),
new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_INVOKE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_INVOKE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INVOCATIONEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
new PredefinedMethodInfo( PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_METHODINFO, PredefinedName.PN_CREATEDELEGATE, MethodCallingConventionEnum.Virtual, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_OBJECT}),
new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_CTOR, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 1, (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0 }),
new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETHASVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETHASVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 0 }),
new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }),
new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GET_VALUE_OR_DEF, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GET_VALUE_OR_DEF, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_OBJECT }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_4, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 4, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_OBJECT }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_STRING, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETCHARS, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETCHARS, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CHAR, 1, (int)PredefinedType.PT_INT }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0, }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
};
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
public abstract class PoolableMemoryPoolProviderBase<TContract> : IProvider
{
public PoolableMemoryPoolProviderBase(
DiContainer container, Guid poolId)
{
Container = container;
PoolId = poolId;
}
public bool IsCached
{
get { return false; }
}
protected Guid PoolId
{
get;
private set;
}
protected DiContainer Container
{
get;
private set;
}
public bool TypeVariesBasedOnMemberType
{
get { return false; }
}
public Type GetInstanceType(InjectContext context)
{
return typeof(TContract);
}
public abstract List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction);
}
// Zero parameters
public class PoolableMemoryPoolProvider<TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<IMemoryPool>
where TMemoryPool : MemoryPool<IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.That(args.IsEmpty());
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn(_pool) };
}
}
// One parameters
public class PoolableMemoryPoolProvider<TParam1, TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<TParam1, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.IsEqual(args.Count, 1);
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn((TParam1)args[0].Value, _pool) };
}
}
// Two parameters
public class PoolableMemoryPoolProvider<TParam1, TParam2, TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<TParam1, TParam2, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, TParam2, IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.IsEqual(args.Count, 2);
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
_pool) };
}
}
// Three parameters
public class PoolableMemoryPoolProvider<TParam1, TParam2, TParam3, TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<TParam1, TParam2, TParam3, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, TParam2, TParam3, IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.IsEqual(args.Count, 3);
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
_pool) };
}
}
// Four parameters
public class PoolableMemoryPoolProvider<TParam1, TParam2, TParam3, TParam4, TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<TParam1, TParam2, TParam3, TParam4, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, TParam2, TParam3, TParam4, IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.IsEqual(args.Count, 4);
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value,
_pool) };
}
}
// Five parameters
public class PoolableMemoryPoolProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<TParam1, TParam2, TParam3, TParam4, TParam5, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.IsEqual(args.Count, 5);
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>());
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value,
(TParam5)args[4].Value,
_pool) };
}
}
// Six parameters
public class PoolableMemoryPoolProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TContract, TMemoryPool> : PoolableMemoryPoolProviderBase<TContract>, IValidatable
where TContract : IPoolable<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, IMemoryPool>
where TMemoryPool : MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, IMemoryPool, TContract>
{
TMemoryPool _pool;
public PoolableMemoryPoolProvider(
DiContainer container, Guid poolId)
: base(container, poolId)
{
}
public void Validate()
{
Container.ResolveId<TMemoryPool>(PoolId);
}
public override List<object> GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction)
{
Assert.IsEqual(args.Count, 6);
Assert.IsNotNull(context);
Assert.That(typeof(TContract).DerivesFromOrEqual(context.MemberType));
Assert.That(args[0].Type.DerivesFromOrEqual<TParam1>());
Assert.That(args[1].Type.DerivesFromOrEqual<TParam2>());
Assert.That(args[2].Type.DerivesFromOrEqual<TParam3>());
Assert.That(args[3].Type.DerivesFromOrEqual<TParam4>());
Assert.That(args[4].Type.DerivesFromOrEqual<TParam5>());
Assert.That(args[5].Type.DerivesFromOrEqual<TParam6>());
injectAction = null;
if (_pool == null)
{
_pool = Container.ResolveId<TMemoryPool>(PoolId);
}
return new List<object>() { _pool.Spawn(
(TParam1)args[0].Value,
(TParam2)args[1].Value,
(TParam3)args[2].Value,
(TParam4)args[3].Value,
(TParam5)args[4].Value,
(TParam6)args[5].Value,
_pool) };
}
}
}
| |
// Copyright Bastian Eicher
// Licensed under the MIT License
using System.Runtime.Versioning;
using NanoByte.Common.Tasks;
namespace NanoByte.Common.Native;
/// <summary>
/// Provides an interface to the Windows Restart Manager. Supported on Windows Vista or newer.
/// </summary>
/// <remarks>
/// See https://msdn.microsoft.com/en-us/library/windows/desktop/cc948910
/// </remarks>
[SupportedOSPlatform("windows6.0")]
public sealed partial class WindowsRestartManager : MarshalByRefObject, IDisposable
{
#region Win32 Error Codes
private const int Win32ErrorFailNoactionReboot = 350;
private const int Win32ErrorFailShutdown = 351;
private const int Win32ErrorFailRestart = 352;
/// <summary>
/// Builds a suitable <see cref="Exception"/> for a given <see cref="Win32Exception.NativeErrorCode"/>.
/// </summary>
private Exception BuildException(int error)
{
switch (error)
{
case Win32ErrorFailNoactionReboot:
case Win32ErrorFailShutdown:
case Win32ErrorFailRestart:
string message = new Win32Exception(error).Message + Environment.NewLine + StringUtils.Join(Environment.NewLine, ListAppProblems(out bool permissionDenied));
if (permissionDenied) return new UnauthorizedAccessException(message);
else return new IOException(message);
default:
return WindowsUtils.BuildException(error);
}
}
#endregion
#region Session
private readonly IntPtr _sessionHandle;
/// <summary>
/// Starts a new Restart Manager session.
/// </summary>
/// <exception cref="Win32Exception">The Restart Manager API returned an error.</exception>
/// <exception cref="PlatformNotSupportedException">The current platform does not support the Restart Manager. Needs Windows Vista or newer.</exception>
public WindowsRestartManager()
{
if (!WindowsUtils.IsWindowsVista) throw new PlatformNotSupportedException();
int ret = NativeMethods.RmStartSession(out _sessionHandle, 0, Guid.NewGuid().ToString());
if (ret != 0) throw BuildException(ret);
}
/// <summary>
/// Ends the Restart Manager session.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
DisposeNative();
}
/// <inheritdoc/>
~WindowsRestartManager()
{
DisposeNative();
}
private void DisposeNative()
{
int ret = NativeMethods.RmEndSession(_sessionHandle);
if (ret != 0) Log.Debug(BuildException(ret));
}
private void CancellationCallback() => NativeMethods.RmCancelCurrentTask(_sessionHandle);
#endregion
#region Resources
/// <summary>
/// Registers resources to the Restart Manager session. The Restart Manager uses the list of resources registered with the session to determine which applications and services must be shut down and restarted.
/// </summary>
/// <param name="files">An array of full filename paths.</param>
/// <exception cref="Win32Exception">The Restart Manager API returned an error.</exception>
public void RegisterResources(params string[] files)
{
#region Sanity checks
if (files == null) throw new ArgumentNullException(nameof(files));
#endregion
int ret = NativeMethods.RmRegisterResources(_sessionHandle, (uint)files.Length, files, 0, new NativeMethods.RM_UNIQUE_PROCESS[0], 0, new string[0]);
if (ret != 0) throw BuildException(ret);
}
#endregion
#region List
/// <summary>
/// Gets a list of all applications that are currently using resources that have been registered with <see cref="RegisterResources"/>.
/// </summary>
/// <param name="cancellationToken">Used to signal cancellation requests.</param>
/// <exception cref="IOException">The Restart Manager could not access the registry.</exception>
/// <exception cref="TimeoutException">The Restart Manager could not obtain a Registry write mutex in the allotted time. A system restart is recommended.</exception>
/// <exception cref="Win32Exception">The Restart Manager API returned an error.</exception>
public string[] ListApps(CancellationToken cancellationToken = default)
{
Log.Debug(Resources.SearchingFileReferences);
using (cancellationToken.Register(CancellationCallback))
{
var apps = ListAppsInternal(out uint arrayLength, out _);
string[] names = new string[arrayLength];
for (int i = 0; i < arrayLength; i++)
names[i] = apps[i].strAppName;
return names;
}
}
/// <summary>
/// Gets a list of all applications that have caused problems with <see cref="ShutdownApps"/> or <see cref="RestartApps"/>.
/// </summary>
/// <param name="permissionDenied">Indicates whether trying again as administrator may help.</param>
/// <exception cref="Win32Exception">The Restart Manager API returned an error.</exception>
private IEnumerable<string> ListAppProblems(out bool permissionDenied)
{
var apps = ListAppsInternal(out uint arrayLength, out var rebootReasons);
permissionDenied = rebootReasons == NativeMethods.RM_REBOOT_REASON.RmRebootReasonPermissionDenied;
var names = new List<string>();
for (int i = 0; i < arrayLength; i++)
{
if (apps[i].AppStatus == NativeMethods.RM_APP_STATUS.RmStatusErrorOnStop || apps[i].AppStatus == NativeMethods.RM_APP_STATUS.RmStatusErrorOnRestart)
names.Add(apps[i].strAppName);
}
return names;
}
private NativeMethods.RM_PROCESS_INFO[] ListAppsInternal(out uint arrayLength, out NativeMethods.RM_REBOOT_REASON rebootReasons)
{
int ret;
uint arrayLengthNeeded = 1;
NativeMethods.RM_PROCESS_INFO[] processInfo;
do
{
arrayLength = arrayLengthNeeded;
processInfo = new NativeMethods.RM_PROCESS_INFO[arrayLength];
ret = NativeMethods.RmGetList(_sessionHandle, out arrayLengthNeeded, ref arrayLength, processInfo, out rebootReasons);
} while (ret == WindowsUtils.Win32ErrorMoreData);
if (ret != 0) throw BuildException(ret);
return processInfo;
}
#endregion
#region Shutdown
/// <summary>
/// Initiates the shutdown of applications that are currently using resources that have been registered with <see cref="RegisterResources"/>.
/// </summary>
/// <param name="handler">A callback object used to report progress to the user and allow cancellation.</param>
/// <exception cref="UnauthorizedAccessException">One or more applications could not be shut down. Trying again as administrator may help.</exception>
/// <exception cref="IOException">One or more applications could not be shut down. A system reboot may be required.</exception>
/// <exception cref="Win32Exception">The Restart Manager API returned an error.</exception>
public void ShutdownApps(ITaskHandler handler)
{
#region Sanity checks
if (handler == null) throw new ArgumentNullException(nameof(handler));
#endregion
handler.RunTask(new SimplePercentTask(Resources.ShuttingDownApps, ShutdownAppsWork, CancellationCallback));
}
private void ShutdownAppsWork(PercentProgressCallback progressCallback)
=> ExceptionUtils.Retry<IOException>(lastAttempt =>
{
int ret = NativeMethods.RmShutdown(_sessionHandle, lastAttempt ? NativeMethods.RM_SHUTDOWN_TYPE.RmForceShutdown : 0, progressCallback);
if (ret != 0) throw BuildException(ret);
}, maxRetries: 3);
#endregion
#region Restart
/// <summary>
/// Restarts applications that have been shut down by <see cref="ShutdownApps"/> and that have been registered to be restarted.
/// </summary>
/// <param name="handler">A callback object used to report progress to the user and allow cancellation.</param>
/// <exception cref="IOException">One or more applications could not be automatically restarted.</exception>
/// <exception cref="Win32Exception">The Restart Manager API returned an error.</exception>
public void RestartApps(ITaskHandler handler)
{
#region Sanity checks
if (handler == null) throw new ArgumentNullException(nameof(handler));
#endregion
handler.RunTask(new SimplePercentTask(Resources.RestartingApps, RestartAppsWork, CancellationCallback));
}
private void RestartAppsWork(PercentProgressCallback progressCallback)
{
int ret = NativeMethods.RmRestart(_sessionHandle, 0, progressCallback);
if (ret != 0) throw BuildException(ret);
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Xunit;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class RepositoryBranchesClientTests
{
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new RepositoryBranchesClient(null));
}
}
public class TheGetAllMethod
{
[Fact]
public async Task RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.GetAll("owner", "name");
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions);
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.GetAll(1);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions);
}
[Fact]
public async Task RequestsTheCorrectUrlWithApiOptions()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var options = new ApiOptions
{
PageCount = 1,
StartPage = 1,
PageSize = 1
};
await client.GetAll("owner", "name", options);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", options);
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var options = new ApiOptions
{
PageCount = 1,
StartPage = 1,
PageSize = 1
};
await client.GetAll(1, options);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", options);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name", ApiOptions.None));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null, ApiOptions.None));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "name", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name", ApiOptions.None));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "", ApiOptions.None));
}
}
public class TheGetMethod
{
[Fact]
public async Task RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.Get("owner", "repo", "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json");
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.Get(1, "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.loki-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", ""));
}
}
public class TheGetBranchProtectectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetBranchProtection("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetBranchProtection(1, "branch");
connection.Received()
.Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection(1, ""));
}
}
public class TheUpdateBranchProtectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateBranchProtection("owner", "repo", "branch", update);
connection.Received()
.Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateBranchProtection(1, "branch", update);
connection.Received()
.Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection(1, "", update));
}
}
public class TheDeleteBranchProtectectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteBranchProtection("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteBranchProtection(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection(1, ""));
}
}
public class TheGetRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetRequiredStatusChecks("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetRequiredStatusChecks(1, "branch");
connection.Received()
.Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks(1, ""));
}
}
public class TheUpdateRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecks("owner", "repo", "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecks(1, "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks(1, "", update));
}
}
public class TheDeleteRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecks("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecks(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks(1, ""));
}
}
public class TheGetAllRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAllRequiredStatusChecksContexts("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAllRequiredStatusChecksContexts(1, "branch");
connection.Received()
.Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts(1, ""));
}
}
public class TheUpdateRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", update);
connection.Received()
.Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecksContexts(1, "branch", update);
connection.Received()
.Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts(1, "", update));
}
}
public class TheAddRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newContexts = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddRequiredStatusChecksContexts("owner", "repo", "branch", newContexts);
connection.Received()
.Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newContexts = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddRequiredStatusChecksContexts(1, "branch", newContexts);
connection.Received()
.Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newContexts = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(null, "repo", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", null, "branch", newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", null, newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, null, newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("", "repo", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts(1, "", newContexts));
}
}
public class TheDeleteRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var contextsToRemove = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", contextsToRemove);
connection.Received()
.Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var contextsToRemove = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecksContexts(1, "branch", contextsToRemove);
connection.Received()
.Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var contextsToRemove = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(null, "repo", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", null, "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", null, contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, null, contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("", "repo", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts(1, "", contextsToRemove));
}
}
public class TheGetReviewEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetReviewEnforcement("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetReviewEnforcement(1, "branch");
connection.Received()
.Get<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement(1, ""));
}
}
public class TheUpdateReviewEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredReviewsUpdate(false, false);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateReviewEnforcement("owner", "repo", "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), Arg.Any<BranchProtectionRequiredReviewsUpdate>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredReviewsUpdate(false, false);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateReviewEnforcement(1, "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), Arg.Any<BranchProtectionRequiredReviewsUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionRequiredReviewsUpdate(false, false);
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement(1, "", update));
}
}
public class TheRemoveReviewEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.RemoveReviewEnforcement("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.RemoveReviewEnforcement(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement(1, ""));
}
}
public class TheGetAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAdminEnforcement("owner", "repo", "branch");
connection.Received()
.Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAdminEnforcement(1, "branch");
connection.Received()
.Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement(1, ""));
}
}
public class TheAddAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddAdminEnforcement("owner", "repo", "branch");
connection.Received()
.Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddAdminEnforcement(1, "branch");
connection.Received()
.Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement(1, ""));
}
}
public class TheRemoveAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.RemoveAdminEnforcement("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.RemoveAdminEnforcement(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement(1, ""));
}
}
public class TheGetProtectedBranchRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchRestrictions("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchRestrictions(1, "branch");
connection.Received()
.Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions(1, ""));
}
}
public class TheDeleteProtectedBranchRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchRestrictions("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchRestrictions(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions(1, ""));
}
}
public class TheGetAllProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAllProtectedBranchTeamRestrictions("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAllProtectedBranchTeamRestrictions(1, "branch");
connection.Received()
.Get<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions(1, ""));
}
}
public class TheSetProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams);
connection.Received()
.Put<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchTeamRestrictions(1, "branch", newTeams);
connection.Received()
.Put<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newTeams = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", null, "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("", "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "", newTeams));
}
}
public class TheAddProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams);
connection.Received()
.Post<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchTeamRestrictions(1, "branch", newTeams);
connection.Received()
.Post<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newTeams = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", null, "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("", "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions(1, "", newTeams));
}
}
public class TheDeleteProtectedBranchTeamRestrictions
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", teamsToRemove);
connection.Received()
.Delete<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchTeamRestrictions(1, "branch", teamsToRemove);
connection.Received()
.Delete<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(null, "repo", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", null, "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", null, teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, null, teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("", "repo", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "", teamsToRemove));
}
}
public class TheGetAllProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAllProtectedBranchUserRestrictions("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAllProtectedBranchUserRestrictions(1, "branch");
connection.Received()
.Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions(1, ""));
}
}
public class TheSetProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers);
connection.Received()
.Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchUserRestrictions(1, "branch", newUsers);
connection.Received()
.Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newUsers = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(null, "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", null, "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("", "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions(1, "", newUsers));
}
}
public class TheAddProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers);
connection.Received()
.Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchUserRestrictions(1, "branch", newUsers);
connection.Received()
.Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newUsers = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(null, "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", null, "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("", "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions(1, "", newUsers));
}
}
public class TheDeleteProtectedBranchUserRestrictions
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var usersToRemove = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", usersToRemove);
connection.Received()
.Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var usersToRemove = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchUserRestrictions(1, "branch", usersToRemove);
connection.Received()
.Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var usersToRemove = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(null, "repo", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", null, "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", null, usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, null, usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("", "repo", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions(1, "", usersToRemove));
}
}
}
}
| |
//
// FieldDefinition.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using ScriptSharp.Collections.Generic;
namespace ScriptSharp.Importer.IL {
internal /* public */ sealed class FieldDefinition : FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider {
ushort attributes;
Collection<CustomAttribute> custom_attributes;
int offset = Mixin.NotResolvedMarker;
internal int rva = Mixin.NotResolvedMarker;
byte [] initial_value;
object constant = Mixin.NotResolved;
MarshalInfo marshal_info;
void ResolveLayout ()
{
if (offset != Mixin.NotResolvedMarker)
return;
if (!HasImage) {
offset = Mixin.NoDataMarker;
return;
}
offset = Module.Read (this, (field, reader) => reader.ReadFieldLayout (field));
}
public bool HasLayoutInfo {
get {
if (offset >= 0)
return true;
ResolveLayout ();
return offset >= 0;
}
}
public int Offset {
get {
if (offset >= 0)
return offset;
ResolveLayout ();
return offset >= 0 ? offset : -1;
}
set { offset = value; }
}
void ResolveRVA ()
{
if (rva != Mixin.NotResolvedMarker)
return;
if (!HasImage)
return;
rva = Module.Read (this, (field, reader) => reader.ReadFieldRVA (field));
}
public int RVA {
get {
if (rva > 0)
return rva;
ResolveRVA ();
return rva > 0 ? rva : 0;
}
}
public byte [] InitialValue {
get {
if (initial_value != null)
return initial_value;
ResolveRVA ();
if (initial_value == null)
initial_value = Empty<byte>.Array;
return initial_value;
}
set { initial_value = value; }
}
public FieldAttributes Attributes {
get { return (FieldAttributes) attributes; }
set { attributes = (ushort) value; }
}
public bool HasConstant {
get {
ResolveConstant ();
return constant != Mixin.NoValue;
}
set { if (!value) constant = Mixin.NoValue; }
}
public object Constant {
get { return HasConstant ? constant : null; }
set { constant = value; }
}
void ResolveConstant ()
{
if (constant != Mixin.NotResolved)
return;
this.ResolveConstant (ref constant, Module);
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
}
public bool HasMarshalInfo {
get {
if (marshal_info != null)
return true;
return this.GetHasMarshalInfo (Module);
}
}
public MarshalInfo MarshalInfo {
get { return marshal_info ?? (marshal_info = this.GetMarshalInfo (Module)); }
set { marshal_info = value; }
}
#region FieldAttributes
public bool IsCompilerControlled {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled, value); }
}
public bool IsPrivate {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private, value); }
}
public bool IsFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem, value); }
}
public bool IsAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly, value); }
}
public bool IsFamily {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family, value); }
}
public bool IsFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public, value); }
}
public bool IsStatic {
get { return attributes.GetAttributes ((ushort) FieldAttributes.Static); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Static, value); }
}
public bool IsInitOnly {
get { return attributes.GetAttributes ((ushort) FieldAttributes.InitOnly); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.InitOnly, value); }
}
public bool IsLiteral {
get { return attributes.GetAttributes ((ushort) FieldAttributes.Literal); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Literal, value); }
}
public bool IsNotSerialized {
get { return attributes.GetAttributes ((ushort) FieldAttributes.NotSerialized); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.NotSerialized, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((ushort) FieldAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.SpecialName, value); }
}
public bool IsPInvokeImpl {
get { return attributes.GetAttributes ((ushort) FieldAttributes.PInvokeImpl); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.PInvokeImpl, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((ushort) FieldAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.RTSpecialName, value); }
}
public bool HasDefault {
get { return attributes.GetAttributes ((ushort) FieldAttributes.HasDefault); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.HasDefault, value); }
}
#endregion
public override bool IsDefinition {
get { return true; }
}
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public FieldDefinition (string name, FieldAttributes attributes, TypeReference fieldType)
: base (name, fieldType)
{
this.attributes = (ushort) attributes;
}
public override FieldDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public const int NotResolvedMarker = -2;
public const int NoDataMarker = -1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Bridge.ClientTest.Collections.Generic.Base;
using Bridge.Test.NUnit;
namespace Bridge.ClientTest.Collections.Generic
{
/// <summary>
/// Contains tests that ensure the correctness of the LinkedList class.
/// </summary>
public abstract partial class LinkedList_Generic_Tests<T> : TestBase<T>
{
#region ICollection<T> Helper Methods
protected ICollection<T> GenericICollectionFactory()
{
return GenericLinkedListFactory();
}
protected Type ICollection_Generic_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException);
#endregion
#region LinkedList<T> Helper Methods
protected virtual LinkedList<T> GenericLinkedListFactory()
{
return new LinkedList<T>();
}
/// <summary>
/// Tests the items in the list to make sure they are the same.
/// </summary>
protected void InitialItems_Tests(LinkedList<T> collection, T[] expectedItems)
{
VerifyState(collection, expectedItems);
VerifyGenericEnumerator(collection, expectedItems);
VerifyEnumerator(collection, expectedItems);
}
/// <summary>
/// Verifies that the tail/head properties are valid and
/// can iterate through the list (backwards and forwards) to
/// verify the contents of the list.
/// </summary>
internal static void VerifyState(LinkedList<T> linkedList, T[] expectedItems)
{
T[] tempArray;
int index;
LinkedListNode<T> currentNode, previousNode, nextNode;
//[] Verify Count
Assert.AreEqual(expectedItems.Length, linkedList.Count); //"Err_0821279 List.Count"
//[] Verify Head/Tail
if (expectedItems.Length == 0)
{
Assert.Null(linkedList.First); //"Err_48928ahid Expected Head to be null\n"
Assert.Null(linkedList.Last); //"Err_56418ahjidi Expected Tail to be null\n"
}
else if (expectedItems.Length == 1)
{
VerifyLinkedListNode(linkedList.First, expectedItems[0], linkedList, null, null);
VerifyLinkedListNode(linkedList.Last, expectedItems[0], linkedList, null, null);
}
else
{
VerifyLinkedListNode(linkedList.First, expectedItems[0], linkedList, true, false);
VerifyLinkedListNode(linkedList.Last, expectedItems[expectedItems.Length - 1], linkedList, false, true);
}
//[] Moving forward through he collection starting at head
currentNode = linkedList.First;
previousNode = null;
index = 0;
while (currentNode != null)
{
nextNode = currentNode.Next;
VerifyLinkedListNode(currentNode, expectedItems[index], linkedList, previousNode, nextNode);
previousNode = currentNode;
currentNode = currentNode.Next;
++index;
}
//[] Moving backward through he collection starting at Tail
currentNode = linkedList.Last;
nextNode = null;
index = 0;
while (currentNode != null)
{
previousNode = currentNode.Previous;
VerifyLinkedListNode(currentNode, expectedItems[expectedItems.Length - 1 - index], linkedList, previousNode, nextNode);
nextNode = currentNode;
currentNode = currentNode.Previous;
++index;
}
//[] Verify Contains
for (int i = 0; i < expectedItems.Length; i++)
{
Assert.True(linkedList.Contains(expectedItems[i]), "Err_9872haid Expected Contains with item=" + expectedItems[i] + " to return true");
}
//[] Verify CopyTo
tempArray = new T[expectedItems.Length];
linkedList.CopyTo(tempArray, 0);
for (int i = 0; i < expectedItems.Length; i++)
{
Assert.AreEqual(expectedItems[i], tempArray[i]); //"Err_0310auazp After CopyTo index=" + i.ToString()
}
//[] Verify Enumerator()
index = 0;
foreach (T item in linkedList)
{
Assert.AreEqual(expectedItems[index], item); //"Err_0310auazp Enumerator index=" + index.ToString()
++index;
}
}
/// <summary>
/// Verifies that the contents of a linkedlistnode are correct.
/// </summary>
internal static void VerifyLinkedListNode(LinkedListNode<T> node, T expectedValue, LinkedList<T> expectedList,
LinkedListNode<T> expectedPrevious, LinkedListNode<T> expectedNext)
{
Assert.AreEqual(expectedValue, node.Value); //"Err_548ajoid Node Value"
Assert.AreEqual(expectedList, node.List); //"Err_0821279 Node List"
Assert.AreEqual(expectedPrevious, node.Previous); //"Err_8548ajhiod Previous Node"
Assert.AreEqual(expectedNext, node.Next); //"Err_4688anmjod Next Node"
}
/// <summary>
/// verifies that the contents of a linkedlist node are correct.
/// </summary>
internal static void VerifyLinkedListNode(LinkedListNode<T> node, T expectedValue, LinkedList<T> expectedList,
bool expectedPreviousNull, bool expectedNextNull)
{
Assert.AreEqual(expectedValue, node.Value); //"Err_548ajoid Expected Node Value"
Assert.AreEqual(expectedList, node.List); //"Err_0821279 Expected Node List"
if (expectedPreviousNull)
{
Assert.Null(node.Previous); //"Expected node.Previous to be null."
}
else
{
Assert.NotNull(node.Previous); //"Expected node.Previous not to be null"
}
if (expectedNextNull)
{
Assert.Null(node.Next); //"Expected node.Next to be null."
}
else
{
Assert.NotNull(node.Next); //"Expected node.Next not to be null"
}
}
/// <summary>
/// Verifies that the generic enumerator retrieves the correct items.
/// </summary>
protected void VerifyGenericEnumerator(ICollection<T> collection, T[] expectedItems)
{
IEnumerator<T> enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
//[] Verify non deterministic behavior of current every time it is called before a call to MoveNext() has been made
for (int i = 0; i < 3; i++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (Exception) { }
}
// There is a sequential order to the collection, so we're testing for that.
while ((iterations < expectedCount) && enumerator.MoveNext())
{
T currentItem = enumerator.Current;
T tempItem;
//[] Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) than are in the expectedElements(" + expectedCount + " items)");
//[] Verify Current returned the correct value
Assert.AreEqual(currentItem, expectedItems[iterations]); //"Err_1432pauy Current returned unexpected value at index: " + iterations
//[] Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.AreEqual(currentItem, tempItem); //"Err_8776phaw Current is returning inconsistent results"
}
iterations++;
}
Assert.AreEqual(expectedCount, iterations); //"Err_658805eauz Number of items to iterate through"
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext()); //"Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"
}
//[] Verify non deterministic behavior of current every time it is called after the enumerator is positioned after the last item
for (int i = 0; i < 3; i++)
{
try
{
T tempCurrent = enumerator.Current;
}
catch (Exception) { }
}
enumerator.Dispose();
}
/// <summary>
/// Verifies that the non-generic enumerator retrieves the correct items.
/// </summary>
protected void VerifyEnumerator(ICollection<T> collection, T[] expectedItems)
{
IEnumerator enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
//[] Verify non deterministic behavior of current every time it is called before a call to MoveNext() has been made
for (int i = 0; i < 3; i++)
{
try
{
object tempCurrent = enumerator.Current;
}
catch (Exception) { }
}
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
object currentItem = enumerator.Current;
object tempItem;
//[] Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
//[] Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (itemsVisited[i])
{
continue;
}
if ((expectedItems[i] == null && currentItem == null)
|| (expectedItems[i] != null && expectedItems[i].Equals(currentItem)))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
//[] Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.AreEqual(currentItem, tempItem, "Current is returning inconsistent results Current."); //"Err_8776phaw Current is returning inconsistent results Current."
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.AreEqual(expectedCount, iterations, "Number of items to iterate through"); //"Err_658805eauz Number of items to iterate through"
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Expected MoveNext to return false"); //"Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"
}
//[] Verify non deterministic behavior of current every time it is called after the enumerator is positioned after the last item
for (int i = 0; i < 3; i++)
{
try
{
object tempCurrent = enumerator.Current;
}
catch (Exception) { }
}
}
protected void VerifyContains(LinkedList<T> linkedList, T[] expectedItems)
{
//[] Verify Contains
for (int i = 0; i < expectedItems.Length; i++)
{
Assert.True(linkedList.Contains(expectedItems[i]),
"Err_9872haid Expected Contains with item=" + expectedItems[i] + " to return true");
}
}
protected void VerifyFindLastDuplicates(LinkedList<T> linkedList, T[] expectedItems)
{
LinkedListNode<T> previousNode, currentNode = null, nextNode;
LinkedListNode<T>[] nodes = new LinkedListNode<T>[expectedItems.Length];
int index = 0;
currentNode = linkedList.First;
while (currentNode != null)
{
nodes[index] = currentNode;
currentNode = currentNode.Next;
++index;
}
for (int i = 0; i < expectedItems.Length; ++i)
{
currentNode = linkedList.FindLast(expectedItems[i]);
index = Array.LastIndexOf(expectedItems, expectedItems[i]);
previousNode = 0 < index ? nodes[index - 1] : null;
nextNode = nodes.Length - 1 > index ? nodes[index + 1] : null;
Assert.AreEqual(nodes[index], currentNode); //"Node returned from FindLast index=" + i.ToString()
VerifyLinkedListNode(currentNode, expectedItems[i], linkedList, previousNode, nextNode);
}
}
protected void VerifyFindDuplicates(LinkedList<T> linkedList, T[] expectedItems)
{
LinkedListNode<T> previousNode, currentNode = null, nextNode;
LinkedListNode<T>[] nodes = new LinkedListNode<T>[expectedItems.Length];
int index = 0;
currentNode = linkedList.First;
while (currentNode != null)
{
nodes[index] = currentNode;
currentNode = currentNode.Next;
++index;
}
for (int i = 0; i < expectedItems.Length; ++i)
{
currentNode = linkedList.Find(expectedItems[i]);
index = Array.IndexOf(expectedItems, expectedItems[i]);
previousNode = 0 < index ? nodes[index - 1] : null;
nextNode = nodes.Length - 1 > index ? nodes[index + 1] : null;
Assert.AreEqual(nodes[index], currentNode); //"Node returned from Find index=" + i.ToString()
VerifyLinkedListNode(currentNode, expectedItems[i], linkedList, previousNode, nextNode);
}
}
protected void VerifyFindLast(LinkedList<T> linkedList, T[] expectedItems)
{
LinkedListNode<T> previousNode, currentNode, nextNode;
currentNode = null;
for (int i = 0; i < expectedItems.Length; ++i)
{
previousNode = currentNode;
currentNode = linkedList.FindLast(expectedItems[i]);
nextNode = currentNode.Next;
VerifyLinkedListNode(currentNode, expectedItems[i], linkedList, previousNode, nextNode);
}
currentNode = null;
for (int i = expectedItems.Length - 1; 0 <= i; --i)
{
nextNode = currentNode;
currentNode = linkedList.FindLast(expectedItems[i]);
previousNode = currentNode.Previous;
VerifyLinkedListNode(currentNode, expectedItems[i], linkedList, previousNode, nextNode);
}
}
protected void VerifyFind(LinkedList<T> linkedList, T[] expectedItems)
{
LinkedListNode<T> previousNode, currentNode, nextNode;
currentNode = null;
for (int i = 0; i < expectedItems.Length; ++i)
{
previousNode = currentNode;
currentNode = linkedList.Find(expectedItems[i]);
nextNode = currentNode.Next;
VerifyLinkedListNode(currentNode, expectedItems[i], linkedList, previousNode, nextNode);
}
currentNode = null;
for (int i = expectedItems.Length - 1; 0 <= i; --i)
{
nextNode = currentNode;
currentNode = linkedList.Find(expectedItems[i]);
previousNode = currentNode.Previous;
VerifyLinkedListNode(currentNode, expectedItems[i], linkedList, previousNode, nextNode);
}
}
protected void VerifyRemovedNode(LinkedListNode<T> node, T expectedValue)
{
LinkedList<T> tempLinkedList = new LinkedList<T>();
LinkedListNode<T> headNode, tailNode;
tempLinkedList.AddLast(default(T));
tempLinkedList.AddLast(default(T));
headNode = tempLinkedList.First;
tailNode = tempLinkedList.Last;
Assert.Null(node.List); //"Err_298298anied Node.LinkedList returned non null"
Assert.Null(node.Previous); //"Err_298298anied Node.Previous returned non null"
Assert.Null(node.Next); //"Err_298298anied Node.Next returned non null"
Assert.AreEqual(expectedValue, node.Value); //"Err_969518aheoia Node.Value"
tempLinkedList.AddAfter(tempLinkedList.First, node);
Assert.AreEqual(tempLinkedList, node.List); //"Err_7894ahioed Node.LinkedList"
Assert.AreEqual(headNode, node.Previous); //"Err_14520aheoak Node.Previous"
Assert.AreEqual(tailNode, node.Next); //"Err_42358aujea Node.Next"
Assert.AreEqual(expectedValue, node.Value); //"Err_64888joqaxz Node.Value"
InitialItems_Tests(tempLinkedList, new T[] { default(T), expectedValue, default(T) });
}
protected void VerifyRemovedNode(LinkedList<T> linkedList, LinkedListNode<T> node, T expectedValue)
{
LinkedListNode<T> tailNode = linkedList.Last;
Assert.Null(node.List); //"Err_564898ajid Node.LinkedList returned non null"
Assert.Null(node.Previous); //"Err_30808wia Node.Previous returned non null"
Assert.Null(node.Next); //"Err_78280aoiea Node.Next returned non null"
Assert.AreEqual(expectedValue, node.Value); //"Err_98234aued Node.Value"
linkedList.AddLast(node);
Assert.AreEqual(linkedList, node.List); //"Err_038369aihead Node.LinkedList"
Assert.AreEqual(tailNode, node.Previous); //"Err_789108aiea Node.Previous"
Assert.Null(node.Next); //"Err_37896riad Node.Next returned non null"
linkedList.RemoveLast();
}
protected void VerifyRemovedNode(LinkedList<T> linkedList, T[] linkedListValues, LinkedListNode<T> node, T expectedValue)
{
LinkedListNode<T> tailNode = linkedList.Last;
Assert.Null(node.List); //"Err_564898ajid Node.LinkedList returned non null"
Assert.Null(node.Previous); //"Err_30808wia Node.Previous returned non null"
Assert.Null(node.Next); //"Err_78280aoiea Node.Next returned non null"
Assert.AreEqual(expectedValue, node.Value); //"Err_98234aued Node.Value"
linkedList.AddLast(node);
Assert.AreEqual(linkedList, node.List); //"Err_038369aihead Node.LinkedList"
Assert.AreEqual(tailNode, node.Previous); //"Err_789108aiea Node.Previous"
Assert.Null(node.Next); //"Err_37896riad Node.Next returned non null"
Assert.AreEqual(expectedValue, node.Value); //"Err_823902jaied Node.Value"
T[] expected = new T[linkedListValues.Length + 1];
Array.Copy(linkedListValues, 0, expected, 0, linkedListValues.Length);
expected[linkedListValues.Length] = expectedValue;
InitialItems_Tests(linkedList, expected);
linkedList.RemoveLast();
}
#endregion
}
}
| |
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using ReMi.Api.Insfrastructure.Notifications;
using ReMi.Api.Insfrastructure.Notifications.Filters;
using ReMi.BusinessEntities.Auth;
using ReMi.Common.Constants.ReleaseCalendar;
using ReMi.Common.WebApi.Notifications;
using ReMi.Contracts.Cqrs.Events;
using ReMi.TestUtils.UnitTests;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;
namespace ReMi.Api.Tests.Infrastructure.Notifications
{
public class NotificationFilterApplyingTests : TestClassFor<NotificationFilterApplying>
{
private Mock<IDependencyResolver> _dependencyResolverMock;
protected override NotificationFilterApplying ConstructSystemUnderTest()
{
return new NotificationFilterApplying
{
DependencyResolver = _dependencyResolverMock.Object
};
}
protected override void TestInitialize()
{
_dependencyResolverMock = new Mock<IDependencyResolver>();
base.TestInitialize();
}
[Test]
public void Apply_ShouldReturnTrue_WhenNoFilterImplemented()
{
var account = Builder<Account>.CreateNew().Build();
var evnt = new TestEvent();
var subscriptuions = new List<Subscription> { new Subscription { EventName = evnt.GetType().Name } };
var result = Sut.Apply(evnt, account, subscriptuions);
Assert.IsTrue(result);
}
[Test]
public void Apply_ShouldReturnTrue_WhenSubscriptionDoesntHasFilter()
{
var account = Builder<Account>.CreateNew().Build();
var product = RandomData.RandomString(10);
var evnt = new TestEventWithProductFilter(new[] { product });
var subscriptuions = new List<Subscription> { new Subscription { EventName = evnt.GetType().Name } };
var result = Sut.Apply(evnt, account, subscriptuions);
Assert.IsTrue(result);
}
[Test]
public void Apply_ShouldReturnTrue_WhenFilterImplementationNotFound()
{
var account = Builder<Account>.CreateNew().Build();
var product = RandomData.RandomString(10);
var evnt = new TestEventWithProductFilter(new[] { product });
var subscriptuions = new List<Subscription>
{
new Subscription
{
EventName = evnt.GetType().Name,
Filters = new SubscriptionFilters
{
new SubscriptionFilter{ Property = "Products", Value = RandomData.RandomString(10)}
}
}
};
var result = Sut.Apply(evnt, account, subscriptuions);
Assert.IsTrue(result);
}
[Test]
public void Apply_ShouldReturnFalse_WhenFilterByProductNotEqual()
{
var account = Builder<Account>.CreateNew().Build();
var product = RandomData.RandomString(10);
var evnt = new TestEventWithProductFilter(new[] { product });
var subscriptuions = new List<Subscription>
{
new Subscription
{
EventName = evnt.GetType().Name,
Filters = new SubscriptionFilters
{
new SubscriptionFilter{ Property = "Products", Value = RandomData.RandomString(10)}
}
}
};
_dependencyResolverMock.Setup(
o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByProduct>)))
.Returns(new NotificationFilterByProductApplication());
var result = Sut.Apply(evnt, account, subscriptuions);
Assert.IsFalse(result);
}
[Test]
public void Apply_ShouldResolveOnlyFilterApplicationbyProduct_WhenInvoked()
{
var account = Builder<Account>.CreateNew().Build();
var product = RandomData.RandomString(10);
var evnt = new TestEventWithProductFilter(new[] { product });
var subscriptuions = new List<Subscription> { new Subscription { EventName = evnt.GetType().Name } };
Sut.Apply(evnt, account, subscriptuions);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByProduct>)), Times.Once);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowIdNotRequestor>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowId>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseType>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseTaskId>)), Times.Never);
}
[Test]
public void Apply_ShouldResolveOnlyFilterApplicationbyReleaseType_WhenInvoked()
{
var account = Builder<Account>.CreateNew().Build();
var releaseType = RandomData.RandomEnum<ReleaseType>();
var evnt = new TestEventWithReleaseTypeFilter(releaseType);
var subscriptuions = new List<Subscription> { new Subscription { EventName = evnt.GetType().Name } };
Sut.Apply(evnt, account, subscriptuions);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByProduct>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowIdNotRequestor>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowId>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseType>)), Times.Once);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseTaskId>)), Times.Never);
}
[Test]
public void Apply_ShouldResolveOnlyFilterApplicationByReleaseTypeAndProduct_WhenInvoked()
{
var account = Builder<Account>.CreateNew().Build();
var releaseType = RandomData.RandomEnum<ReleaseType>();
var product = RandomData.RandomString(10);
var evnt = new TestEventWithProductReleaesTypeFilter(new[] { product }, releaseType);
var subscriptuions = new List<Subscription> { new Subscription { EventName = evnt.GetType().Name } };
Sut.Apply(evnt, account, subscriptuions);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByProduct>)), Times.Once);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowId>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowIdNotRequestor>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseType>)), Times.Once);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseTaskId>)), Times.Never);
}
[Test]
public void Apply_ShouldResolveOnlyFilterApplicationByByReleaseWindowIdNotRequestor_WhenInvoked()
{
var account = Builder<Account>.CreateNew().Build();
var releaseWindowId = Guid.NewGuid();
var evnt = new TestEventWithReleaseWindowIdNotRequestorFilter(releaseWindowId, account);
var subscriptuions = new List<Subscription> { new Subscription { EventName = evnt.GetType().Name } };
Sut.Apply(evnt, account, subscriptuions);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByProduct>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowId>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseWindowIdNotRequestor>)), Times.Once);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseType>)), Times.Never);
_dependencyResolverMock.Verify(o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByReleaseTaskId>)), Times.Never);
}
[Test]
public void Apply_ShouldReturnTrue_WhenFilterByProductNotImplemented()
{
var account = Builder<Account>.CreateNew().Build();
var product = RandomData.RandomString(10);
var evnt = new TestEvent();
var subscriptuions = new List<Subscription>
{
new Subscription
{
EventName = evnt.GetType().Name,
Filters = new SubscriptionFilters
{
new SubscriptionFilter{ Property = "Products", Value = product}
}
}
};
_dependencyResolverMock.Setup(
o => o.GetService(typeof(INotificationFilterApplication<INotificationFilterByProduct>)))
.Returns(new NotificationFilterByProductApplication());
var result = Sut.Apply(evnt, account, subscriptuions);
Assert.IsTrue(result);
}
#region Events
private class TestEvent : IEvent
{
public EventContext Context { get; set; }
}
private class TestEventWithProductFilter : IEvent, INotificationFilterByProduct
{
public EventContext Context { get; set; }
public IEnumerable<string> Products { get; private set; }
public TestEventWithProductFilter(IEnumerable<string> products)
{
Products = products;
}
}
private class TestEventWithReleaseWindowIdNotRequestorFilter : IEvent, INotificationFilterByReleaseWindowIdNotRequestor
{
public EventContext Context { get; set; }
public Guid ReleaseWindowId { get; set; }
public Guid RequestorId { get { return Context.UserId; } }
public TestEventWithReleaseWindowIdNotRequestorFilter(Guid releaseWindowId, Account requestor)
{
Context = new EventContext { UserId = requestor.ExternalId };
ReleaseWindowId = releaseWindowId;
}
}
private class TestEventWithReleaseTypeFilter : IEvent, INotificationFilterByReleaseType
{
public EventContext Context { get; set; }
public TestEventWithReleaseTypeFilter(ReleaseType releaseType)
{
ReleaseType = releaseType;
}
public ReleaseType ReleaseType { get; private set; }
}
private class TestEventWithProductReleaesTypeFilter : IEvent, INotificationFilterByReleaseType, INotificationFilterByProduct
{
public EventContext Context { get; set; }
public TestEventWithProductReleaesTypeFilter(IEnumerable<string> products, ReleaseType releaseType)
{
Products = products;
ReleaseType = releaseType;
}
public ReleaseType ReleaseType { get; private set; }
public IEnumerable<string> Products { get; private set; }
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.IO;
using Nini.Config;
using log4net;
namespace OpenSim.Framework.Console
{
/// <summary>
/// A console that uses cursor control and color
/// </summary>
public class LocalConsole : CommandConsole
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_historyPath;
private bool m_historyEnable;
// private readonly object m_syncRoot = new object();
private const string LOGLEVEL_NONE = "(none)";
// Used to extract categories for colourization.
private Regex m_categoryRegex
= new Regex(
@"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)", RegexOptions.Singleline | RegexOptions.Compiled);
private int m_cursorYPosition = -1;
private int m_cursorXPosition = 0;
private StringBuilder m_commandLine = new StringBuilder();
private bool m_echo = true;
private List<string> m_history = new List<string>();
private static readonly ConsoleColor[] Colors = {
// the dark colors don't seem to be visible on some black background terminals like putty :(
//ConsoleColor.DarkBlue,
//ConsoleColor.DarkGreen,
//ConsoleColor.DarkCyan,
//ConsoleColor.DarkMagenta,
//ConsoleColor.DarkYellow,
ConsoleColor.Gray,
//ConsoleColor.DarkGray,
ConsoleColor.Blue,
ConsoleColor.Green,
ConsoleColor.Cyan,
ConsoleColor.Magenta,
ConsoleColor.Yellow
};
private static ConsoleColor DeriveColor(string input)
{
// it is important to do Abs, hash values can be negative
return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
}
public LocalConsole(string defaultPrompt, IConfig startupConfig = null) : base(defaultPrompt)
{
if (startupConfig == null) return;
m_historyEnable = startupConfig.GetBoolean("ConsoleHistoryFileEnabled", false);
if (!m_historyEnable)
{
m_log.Info("[LOCAL CONSOLE]: Persistent command line history from file is Disabled");
return;
}
string m_historyFile = startupConfig.GetString("ConsoleHistoryFile", "OpenSimConsoleHistory.txt");
int m_historySize = startupConfig.GetInt("ConsoleHistoryFileLines", 100);
m_historyPath = Path.GetFullPath(Path.Combine(Util.configDir(), m_historyFile));
m_log.InfoFormat("[LOCAL CONSOLE]: Persistent command line history is Enabled, up to {0} lines from file {1}", m_historySize, m_historyPath);
if (File.Exists(m_historyPath))
{
using (StreamReader history_file = new StreamReader(m_historyPath))
{
string line;
while ((line = history_file.ReadLine()) != null)
{
m_history.Add(line);
}
}
if (m_history.Count > m_historySize)
{
while (m_history.Count > m_historySize)
m_history.RemoveAt(0);
using (StreamWriter history_file = new StreamWriter(m_historyPath))
{
foreach (string line in m_history)
{
history_file.WriteLine(line);
}
}
}
m_log.InfoFormat("[LOCAL CONSOLE]: Read {0} lines of command line history from file {1}", m_history.Count, m_historyPath);
}
else
{
m_log.InfoFormat("[LOCAL CONSOLE]: Creating new empty command line history file {0}", m_historyPath);
File.Create(m_historyPath).Dispose();
}
}
private void AddToHistory(string text)
{
while (m_history.Count >= 100)
m_history.RemoveAt(0);
m_history.Add(text);
if (m_historyEnable)
{
File.AppendAllText(m_historyPath, text + Environment.NewLine);
}
}
/// <summary>
/// Set the cursor row.
/// </summary>
///
/// <param name="top">
/// Row to set. If this is below 0, then the row is set to 0. If it is equal to the buffer height or greater
/// then it is set to one less than the height.
/// </param>
/// <returns>
/// The new cursor row.
/// </returns>
private int SetCursorTop(int top)
{
// From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
// to set a cursor row position with a currently invalid column, mono will throw an exception.
// Therefore, we need to make sure that the column position is valid first.
int left = System.Console.CursorLeft;
if (left < 0)
{
System.Console.CursorLeft = 0;
}
else
{
int bufferWidth = System.Console.BufferWidth;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferWidth > 0 && left >= bufferWidth)
System.Console.CursorLeft = bufferWidth - 1;
}
if (top < 0)
{
top = 0;
}
else
{
int bufferHeight = System.Console.BufferHeight;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferHeight > 0 && top >= bufferHeight)
top = bufferHeight - 1;
}
System.Console.CursorTop = top;
return top;
}
/// <summary>
/// Set the cursor column.
/// </summary>
///
/// <param name="left">
/// Column to set. If this is below 0, then the column is set to 0. If it is equal to the buffer width or greater
/// then it is set to one less than the width.
/// </param>
/// <returns>
/// The new cursor column.
/// </returns>
private int SetCursorLeft(int left)
{
// From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
// to set a cursor column position with a currently invalid row, mono will throw an exception.
// Therefore, we need to make sure that the row position is valid first.
int top = System.Console.CursorTop;
if (top < 0)
{
System.Console.CursorTop = 0;
}
else
{
int bufferHeight = System.Console.BufferHeight;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferHeight > 0 && top >= bufferHeight)
System.Console.CursorTop = bufferHeight - 1;
}
if (left < 0)
{
left = 0;
}
else
{
int bufferWidth = System.Console.BufferWidth;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferWidth > 0 && left >= bufferWidth)
left = bufferWidth - 1;
}
System.Console.CursorLeft = left;
return left;
}
private void Show()
{
lock (m_commandLine)
{
if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
return;
int xc = prompt.Length + m_cursorXPosition;
int new_x = xc % System.Console.BufferWidth;
int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
if (end_y >= System.Console.BufferHeight) // wrap
{
m_cursorYPosition--;
new_y--;
SetCursorLeft(0);
SetCursorTop(System.Console.BufferHeight - 1);
System.Console.WriteLine(" ");
}
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
if (m_echo)
System.Console.Write("{0}{1}", prompt, m_commandLine);
else
System.Console.Write("{0}", prompt);
SetCursorTop(new_y);
SetCursorLeft(new_x);
}
}
public override void LockOutput()
{
Monitor.Enter(m_commandLine);
try
{
if (m_cursorYPosition != -1)
{
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
System.Console.CursorLeft = 0;
int count = m_commandLine.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
}
}
catch (Exception)
{
}
}
public override void UnlockOutput()
{
if (m_cursorYPosition != -1)
{
m_cursorYPosition = System.Console.CursorTop;
Show();
}
Monitor.Exit(m_commandLine);
}
private void WriteColorText(ConsoleColor color, string sender)
{
try
{
lock (this)
{
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
}
}
catch (ObjectDisposedException)
{
}
}
private void WriteLocalText(string text, string level)
{
string outText = text;
if (level != LOGLEVEL_NONE)
{
MatchCollection matches = m_categoryRegex.Matches(text);
if (matches.Count == 1)
{
outText = matches[0].Groups["End"].Value;
System.Console.Write(matches[0].Groups["Front"].Value);
System.Console.Write("[");
WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
matches[0].Groups["Category"].Value);
System.Console.Write("]:");
}
else
{
outText = outText.Trim();
}
}
if (level == "error")
WriteColorText(ConsoleColor.Red, outText);
else if (level == "warn")
WriteColorText(ConsoleColor.Yellow, outText);
else
System.Console.Write(outText);
System.Console.WriteLine();
}
public override void Output(string text)
{
Output(text, LOGLEVEL_NONE);
}
public override void Output(string text, string level)
{
FireOnOutput(text);
lock (m_commandLine)
{
if (m_cursorYPosition == -1)
{
WriteLocalText(text, level);
return;
}
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
int count = m_commandLine.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
WriteLocalText(text, level);
m_cursorYPosition = System.Console.CursorTop;
Show();
}
}
private bool ContextHelp()
{
string[] words = Parser.Parse(m_commandLine.ToString());
bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
// Allow ? through while typing a URI
//
if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
return false;
string[] opts = Commands.FindNextOption(words, trailingSpace);
if (opts[0].StartsWith("Command help:"))
Output(opts[0]);
else
Output(String.Format("Options: {0}", String.Join(" ", opts)));
return true;
}
public override string ReadLine(string p, bool isCommand, bool e)
{
m_cursorXPosition = 0;
prompt = p;
m_echo = e;
int historyLine = m_history.Count;
SetCursorLeft(0); // Needed for mono
System.Console.Write(" "); // Needed for mono
lock (m_commandLine)
{
m_cursorYPosition = System.Console.CursorTop;
m_commandLine.Remove(0, m_commandLine.Length);
}
while (true)
{
Show();
ConsoleKeyInfo key = System.Console.ReadKey(true);
char enteredChar = key.KeyChar;
if (!Char.IsControl(enteredChar))
{
if (m_cursorXPosition >= 318)
continue;
if (enteredChar == '?' && isCommand)
{
if (ContextHelp())
continue;
}
m_commandLine.Insert(m_cursorXPosition, enteredChar);
m_cursorXPosition++;
}
else
{
switch (key.Key)
{
case ConsoleKey.Backspace:
if (m_cursorXPosition == 0)
break;
m_commandLine.Remove(m_cursorXPosition-1, 1);
m_cursorXPosition--;
SetCursorLeft(0);
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
if (m_echo)
System.Console.Write("{0}{1} ", prompt, m_commandLine);
else
System.Console.Write("{0}", prompt);
break;
case ConsoleKey.Delete:
if (m_cursorXPosition == m_commandLine.Length)
break;
m_commandLine.Remove(m_cursorXPosition, 1);
SetCursorLeft(0);
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
if (m_echo)
System.Console.Write("{0}{1} ", prompt, m_commandLine);
else
System.Console.Write("{0}", prompt);
break;
case ConsoleKey.End:
m_cursorXPosition = m_commandLine.Length;
break;
case ConsoleKey.Home:
m_cursorXPosition = 0;
break;
case ConsoleKey.UpArrow:
if (historyLine < 1)
break;
historyLine--;
LockOutput();
m_commandLine.Remove(0, m_commandLine.Length);
m_commandLine.Append(m_history[historyLine]);
m_cursorXPosition = m_commandLine.Length;
UnlockOutput();
break;
case ConsoleKey.DownArrow:
if (historyLine >= m_history.Count)
break;
historyLine++;
LockOutput();
if (historyLine == m_history.Count)
{
m_commandLine.Remove(0, m_commandLine.Length);
}
else
{
m_commandLine.Remove(0, m_commandLine.Length);
m_commandLine.Append(m_history[historyLine]);
}
m_cursorXPosition = m_commandLine.Length;
UnlockOutput();
break;
case ConsoleKey.LeftArrow:
if (m_cursorXPosition > 0)
m_cursorXPosition--;
break;
case ConsoleKey.RightArrow:
if (m_cursorXPosition < m_commandLine.Length)
m_cursorXPosition++;
break;
case ConsoleKey.Enter:
SetCursorLeft(0);
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
System.Console.WriteLine();
//Show();
lock (m_commandLine)
{
m_cursorYPosition = -1;
}
string commandLine = m_commandLine.ToString();
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
if (cmd.Length != 0)
{
int index;
for (index=0 ; index < cmd.Length ; index++)
{
if (cmd[index].Contains(" "))
cmd[index] = "\"" + cmd[index] + "\"";
}
AddToHistory(String.Join(" ", cmd));
return String.Empty;
}
}
// If we're not echoing to screen (e.g. a password) then we probably don't want it in history
if (m_echo && commandLine != "")
AddToHistory(commandLine);
return commandLine;
default:
break;
}
}
}
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections;
using System.Runtime.CompilerServices;
namespace Encog.App.Quant.Loader.OpenQuant
{
// Fields
[Serializable]
public class DataArray : IEnumerable
{
protected double fDivisor;
protected ArrayList fList;
protected int fStopRecurant;
// Methods
[MethodImpl(MethodImplOptions.NoInlining)]
public DataArray()
{
fList = new ArrayList();
}
/// <summary>
/// Gets the number of object in the array.
/// </summary>
public int Count
{
[MethodImpl(MethodImplOptions.NoInlining)] get { return fList.Count; }
}
/// <summary>
/// Gets the <see cref="Encog.App.Quant.Loader.OpenQuant.Data.Data.IDataObject" /> at the specified index.
/// </summary>
public Data.Data.IDataObject this[int index]
{
[MethodImpl(MethodImplOptions.NoInlining)] get { return (fList[index] as Data.Data.IDataObject); }
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public IEnumerator GetEnumerator()
{
return fList.GetEnumerator();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void Add(Data.Data.IDataObject obj)
{
fList.Add(obj);
}
/// <summary>
/// Clears this instance.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Clear()
{
fList.Clear();
}
/// <summary>
/// Determines whether [contains] [the specified obj].
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified obj]; otherwise, <c>false</c>.
/// </returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public bool Contains(Data.Data.IDataObject obj)
{
return fList.Contains(obj);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public bool Contains(Data.Data.Bar bar)
{
return fList.Contains(bar);
}
/// <summary>
/// Gets the index for a certain datetime.
/// </summary>
/// <param name="datetime">The datetime.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public int GetIndex(DateTime datetime)
{
if (Count != 0)
{
DateTime dateTime = this[0].DateTime;
DateTime time2 = this[Count - 1].DateTime;
if ((dateTime <= datetime) && (time2 >= datetime))
{
return GetIndex(datetime, 0, Count - 1);
}
}
return -1;
}
/// <summary>
/// Gets the index for a certain date time.
/// </summary>
/// <param name="datetime">The datetime.</param>
/// <param name="index1">The index1.</param>
/// <param name="index2">The index2.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public int GetIndex(DateTime datetime, int index1, int index2)
{
int num4;
long ticks = this[index1].DateTime.Ticks;
long num2 = this[index2].DateTime.Ticks;
long num3 = datetime.Ticks;
if (num2 != ticks)
{
num4 = index1 + ((int) ((index2 - index1)*((num3 - ticks)/(num2 - ticks))));
}
else
{
num4 = (index1 + index2)/2;
}
Data.Data.IDataObject obj2 = this[num4];
if (obj2.DateTime == datetime)
{
return num4;
}
if (((index2 - num4) < fStopRecurant) || ((num4 - index1) < fStopRecurant))
{
for (int i = index2; i >= index1; i--)
{
obj2 = this[i];
if (obj2.DateTime < datetime)
{
return i;
}
}
return -1;
}
var num6 = (int) (((index2 - index1))/fDivisor);
int num7 = Math.Max(index1, num4 - num6);
obj2 = this[num7];
if (obj2.DateTime > datetime)
{
return GetIndex(datetime, index1, num7);
}
int num8 = Math.Min(index2, num4 + num6);
obj2 = this[num8];
if (obj2.DateTime < datetime)
{
return GetIndex(datetime, num8, index2);
}
return GetIndex(datetime, num7, num8);
}
/// <summary>
/// Inserts an item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="obj">The obj.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Insert(int index, Data.Data.IDataObject obj)
{
fList.Insert(index, obj);
}
/// <summary>
/// Inserts an item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="bar">The bar.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Insert(int index, Data.Data.Bar bar)
{
fList.Insert(index, bar);
}
/// <summary>
/// Removes the specified obj.
/// </summary>
/// <param name="obj">The obj.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Remove(Data.Data.IDataObject obj)
{
fList.Remove(obj);
}
/// <summary>
/// Removes the specified obj.
/// </summary>
/// <param name="obj">The obj.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public void Remove(Data.Data.Bar bar)
{
fList.Remove(bar);
}
/// <summary>
/// Removes an object at the specified index in the array of objects.
/// </summary>
/// <param name="index">The index.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public void RemoveAt(int index)
{
fList.RemoveAt(index);
}
// Properties
/// <summary>
/// Adds the specified bar.
/// </summary>
/// <param name="bar">The bar.</param>
public void Add(Data.Data.Bar bar)
{
Add(bar);
}
}
}
| |
// 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.DataFactory
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<DataFactoryManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(DataFactoryManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DataFactoryManagementClient
/// </summary>
public DataFactoryManagementClient Client { get; private set; }
/// <summary>
/// Lists the available Azure Data Factory API operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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>
/// <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<AzureOperationResponse<OperationListResponse>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.DataFactory/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// 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 (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_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 AzureOperationResponse<OperationListResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationListResponse>(_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;
}
}
}
| |
//
// IndexerClient.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Threading;
using Hyena;
using DBus;
using org.freedesktop.DBus;
using Banshee.Collection.Indexer;
namespace Banshee.Collection.Indexer.RemoteHelper
{
public abstract class IndexerClient
{
private const string application_bus_name = "org.bansheeproject.Banshee";
private const string indexer_bus_name = "org.bansheeproject.CollectionIndexer";
private const string service_interface = "org.bansheeproject.CollectionIndexer.Service";
private static ObjectPath service_path = new ObjectPath ("/org/bansheeproject/Banshee/CollectionIndexerService");
private IBus session_bus;
private bool listening;
private ICollectionIndexerService service;
private bool cleanup_and_shutdown;
private bool index_when_collection_changed = true;
public void Start ()
{
ShowDebugMessages = true;
Debug ("Acquiring org.freedesktop.DBus session instance");
session_bus = Bus.Session.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus"));
session_bus.NameOwnerChanged += OnBusNameOwnerChanged;
if (Bus.Session.NameHasOwner (indexer_bus_name)) {
Debug ("{0} is already started", indexer_bus_name);
ConnectToIndexerService ();
} else {
Debug ("Starting {0}", indexer_bus_name);
Bus.Session.StartServiceByName (indexer_bus_name);
}
}
private void OnBusNameOwnerChanged (string name, string oldOwner, string newOwner)
{
if (name == indexer_bus_name) {
Debug ("NameOwnerChanged: {0}, '{1}' => '{2}'", name, oldOwner, newOwner);
if (service == null && !String.IsNullOrEmpty (newOwner)) {
ConnectToIndexerService ();
}
}
}
private void Index ()
{
if (HasCollectionChanged) {
ICollectionIndexer indexer = CreateIndexer ();
indexer.IndexingFinished += delegate { _UpdateIndex (indexer); };
indexer.Index ();
}
}
private void _UpdateIndex (ICollectionIndexer indexer)
{
ThreadPool.QueueUserWorkItem (delegate {
Debug ("Running indexer");
try {
UpdateIndex (indexer);
} catch (Exception e) {
Console.Error.WriteLine (e);
}
Debug ("Indexer finished");
indexer.Dispose ();
if (!ApplicationAvailable || !listening) {
DisconnectFromIndexerService ();
}
});
}
private void ConnectToIndexerService ()
{
DisconnectFromIndexerService ();
ResolveIndexerService ();
if (service == null) {
Log.Error ("Failed to connect to {0}, bailing.", service_interface);
return;
} else {
Debug ("Connected to {0}", service_interface);
}
service.CleanupAndShutdown += OnCleanupAndShutdown;
if (ApplicationAvailable) {
Debug ("Listening to service's CollectionChanged signal (full-app is running)");
listening = true;
service.CollectionChanged += OnCollectionChanged;
}
Index ();
}
private void DisconnectFromIndexerService ()
{
if (service == null) {
return;
}
Debug ("Disconnecting from service");
if (listening) {
try {
listening = false;
service.CollectionChanged -= OnCollectionChanged;
} catch (Exception e) {
Debug (e.ToString ());
}
}
try {
service.CleanupAndShutdown -= OnCleanupAndShutdown;
} catch (Exception e) {
Debug (e.ToString ());
}
try {
service.Shutdown ();
} catch (Exception e) {
Debug (e.ToString ());
}
ResetInternalState ();
}
private void ResetInternalState ()
{
if (service == null) {
return;
}
Debug ("Resetting internal state - service is no longer available or not needed");
service = null;
listening = false;
cleanup_and_shutdown = false;
ResetState ();
}
private void ResolveIndexerService ()
{
int attempts = 0;
while (attempts++ < 4) {
try {
Debug ("Resolving {0} (attempt {1})", service_interface, attempts);
service = Bus.Session.GetObject<ICollectionIndexerService> (indexer_bus_name, service_path);
service.Hello ();
return;
} catch {
service = null;
System.Threading.Thread.Sleep (2000);
}
}
}
private void OnCollectionChanged ()
{
if (IndexWhenCollectionChanged) {
Index ();
}
}
private void OnCleanupAndShutdown ()
{
cleanup_and_shutdown = true;
}
protected void Debug (string message, params object [] args)
{
Log.DebugFormat (message, args);
}
protected abstract bool HasCollectionChanged { get; }
protected abstract void UpdateIndex (ICollectionIndexer indexer);
protected abstract void ResetState ();
protected ICollectionIndexer CreateIndexer ()
{
ObjectPath object_path = service.CreateIndexer ();
Debug ("Creating an ICollectionIndexer ({0})", object_path);
return Bus.Session.GetObject<ICollectionIndexer> (indexer_bus_name, object_path);
}
public bool ShowDebugMessages {
get { return Log.Debugging; }
set { Log.Debugging = value; }
}
protected bool CleanupAndShutdown {
get { return cleanup_and_shutdown; }
}
public bool IndexWhenCollectionChanged {
get { return index_when_collection_changed; }
set { index_when_collection_changed = value; }
}
protected ICollectionIndexerService Service {
get { return service; }
}
protected bool ApplicationAvailable {
get { return Bus.Session.NameHasOwner (application_bus_name); }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Security.Principal
{
//
// Identifier authorities
//
internal enum IdentifierAuthority : long
{
NullAuthority = 0,
WorldAuthority = 1,
LocalAuthority = 2,
CreatorAuthority = 3,
NonUniqueAuthority = 4,
NTAuthority = 5,
SiteServerAuthority = 6,
InternetSiteAuthority = 7,
ExchangeAuthority = 8,
ResourceManagerAuthority = 9,
}
//
// SID name usage
//
internal enum SidNameUse
{
User = 1,
Group = 2,
Domain = 3,
Alias = 4,
WellKnownGroup = 5,
DeletedAccount = 6,
Invalid = 7,
Unknown = 8,
Computer = 9,
}
//
// Well-known SID types
//
public enum WellKnownSidType
{
NullSid = 0,
WorldSid = 1,
LocalSid = 2,
CreatorOwnerSid = 3,
CreatorGroupSid = 4,
CreatorOwnerServerSid = 5,
CreatorGroupServerSid = 6,
NTAuthoritySid = 7,
DialupSid = 8,
NetworkSid = 9,
BatchSid = 10,
InteractiveSid = 11,
ServiceSid = 12,
AnonymousSid = 13,
ProxySid = 14,
EnterpriseControllersSid = 15,
SelfSid = 16,
AuthenticatedUserSid = 17,
RestrictedCodeSid = 18,
TerminalServerSid = 19,
RemoteLogonIdSid = 20,
LogonIdsSid = 21,
LocalSystemSid = 22,
LocalServiceSid = 23,
NetworkServiceSid = 24,
BuiltinDomainSid = 25,
BuiltinAdministratorsSid = 26,
BuiltinUsersSid = 27,
BuiltinGuestsSid = 28,
BuiltinPowerUsersSid = 29,
BuiltinAccountOperatorsSid = 30,
BuiltinSystemOperatorsSid = 31,
BuiltinPrintOperatorsSid = 32,
BuiltinBackupOperatorsSid = 33,
BuiltinReplicatorSid = 34,
BuiltinPreWindows2000CompatibleAccessSid = 35,
BuiltinRemoteDesktopUsersSid = 36,
BuiltinNetworkConfigurationOperatorsSid = 37,
AccountAdministratorSid = 38,
AccountGuestSid = 39,
AccountKrbtgtSid = 40,
AccountDomainAdminsSid = 41,
AccountDomainUsersSid = 42,
AccountDomainGuestsSid = 43,
AccountComputersSid = 44,
AccountControllersSid = 45,
AccountCertAdminsSid = 46,
AccountSchemaAdminsSid = 47,
AccountEnterpriseAdminsSid = 48,
AccountPolicyAdminsSid = 49,
AccountRasAndIasServersSid = 50,
NtlmAuthenticationSid = 51,
DigestAuthenticationSid = 52,
SChannelAuthenticationSid = 53,
ThisOrganizationSid = 54,
OtherOrganizationSid = 55,
BuiltinIncomingForestTrustBuildersSid = 56,
BuiltinPerformanceMonitoringUsersSid = 57,
BuiltinPerformanceLoggingUsersSid = 58,
BuiltinAuthorizationAccessSid = 59,
WinBuiltinTerminalServerLicenseServersSid = 60,
MaxDefined = WinBuiltinTerminalServerLicenseServersSid,
}
//
// This class implements revision 1 SIDs
// NOTE: The SecurityIdentifier class is immutable and must remain this way
//
public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier>
{
#region Public Constants
//
// Identifier authority must be at most six bytes long
//
internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF;
//
// Maximum number of subauthorities in a SID
//
internal static readonly byte MaxSubAuthorities = 15;
//
// Minimum length of a binary representation of a SID
//
public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6)
//
// Maximum length of a binary representation of a SID
//
public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth
#endregion
#region Private Members
//
// Immutable properties of a SID
//
private IdentifierAuthority _identifierAuthority;
private int[] _subAuthorities;
private byte[] _binaryForm;
private SecurityIdentifier _accountDomainSid;
private bool _accountDomainSidInitialized = false;
//
// Computed attributes of a SID
//
private string _sddlForm = null;
#endregion
#region Constructors
//
// Shared constructor logic
// NOTE: subauthorities are really unsigned integers, but due to CLS
// lack of support for unsigned integers the caller must perform
// the typecast
//
private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
if (subAuthorities == null)
{
throw new ArgumentNullException("subAuthorities");
}
Contract.EndContractBlock();
//
// Check the number of subauthorities passed in
//
if (subAuthorities.Length > MaxSubAuthorities)
{
throw new ArgumentOutOfRangeException(
"subAuthorities.Length",
subAuthorities.Length,
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities));
}
//
// Identifier authority is at most 6 bytes long
//
if (identifierAuthority < 0 ||
(long)identifierAuthority > MaxIdentifierAuthority)
{
throw new ArgumentOutOfRangeException(
"identifierAuthority",
identifierAuthority,
SR.IdentityReference_IdentifierAuthorityTooLarge);
}
//
// Create a local copy of the data passed in
//
_identifierAuthority = identifierAuthority;
_subAuthorities = new int[subAuthorities.Length];
subAuthorities.CopyTo(_subAuthorities, 0);
//
// Compute and store the binary form
//
// typedef struct _SID {
// UCHAR Revision;
// UCHAR SubAuthorityCount;
// SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
// ULONG SubAuthority[ANYSIZE_ARRAY]
// } SID, *PISID;
//
byte i;
_binaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount];
//
// First two bytes contain revision and subauthority count
//
_binaryForm[0] = Revision;
_binaryForm[1] = (byte)this.SubAuthorityCount;
//
// Identifier authority takes up 6 bytes
//
for (i = 0; i < 6; i++)
{
_binaryForm[2 + i] = (byte)((((ulong)_identifierAuthority) >> ((5 - i) * 8)) & 0xFF);
}
//
// Subauthorities go last, preserving big-endian representation
//
for (i = 0; i < this.SubAuthorityCount; i++)
{
byte shift;
for (shift = 0; shift < 4; shift += 1)
{
_binaryForm[8 + 4 * i + shift] = (byte)(((ulong)_subAuthorities[i]) >> (shift * 8));
}
}
}
private void CreateFromBinaryForm(byte[] binaryForm, int offset)
{
//
// Give us something to work with
//
if (binaryForm == null)
{
throw new ArgumentNullException("binaryForm");
}
//
// Negative offsets are not allowed
//
if (offset < 0)
{
throw new ArgumentOutOfRangeException(
"offset",
offset,
SR.ArgumentOutOfRange_NeedNonNegNum);
}
//
// At least a minimum-size SID should fit in the buffer
//
if (binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength)
{
throw new ArgumentOutOfRangeException(
"binaryForm",
SR.ArgumentOutOfRange_ArrayTooSmall);
}
Contract.EndContractBlock();
IdentifierAuthority Authority;
int[] SubAuthorities;
//
// Extract the elements of a SID
//
if (binaryForm[offset] != Revision)
{
//
// Revision is incorrect
//
throw new ArgumentException(
SR.IdentityReference_InvalidSidRevision,
"binaryForm");
}
//
// Insist on the correct number of subauthorities
//
if (binaryForm[offset + 1] > MaxSubAuthorities)
{
throw new ArgumentException(
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities),
"binaryForm");
}
//
// Make sure the buffer is big enough
//
int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1];
if (binaryForm.Length - offset < Length)
{
throw new ArgumentException(
SR.ArgumentOutOfRange_ArrayTooSmall,
"binaryForm");
}
Authority =
(IdentifierAuthority)(
(((long)binaryForm[offset + 2]) << 40) +
(((long)binaryForm[offset + 3]) << 32) +
(((long)binaryForm[offset + 4]) << 24) +
(((long)binaryForm[offset + 5]) << 16) +
(((long)binaryForm[offset + 6]) << 8) +
(((long)binaryForm[offset + 7])));
SubAuthorities = new int[binaryForm[offset + 1]];
//
// Subauthorities are represented in big-endian format
//
for (byte i = 0; i < binaryForm[offset + 1]; i++)
{
SubAuthorities[i] =
(int)(
(((uint)binaryForm[offset + 8 + 4 * i + 0]) << 0) +
(((uint)binaryForm[offset + 8 + 4 * i + 1]) << 8) +
(((uint)binaryForm[offset + 8 + 4 * i + 2]) << 16) +
(((uint)binaryForm[offset + 8 + 4 * i + 3]) << 24));
}
CreateFromParts(Authority, SubAuthorities);
return;
}
//
// Constructs a SecurityIdentifier object from its string representation
// Returns 'null' if string passed in is not a valid SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(string sddlForm)
{
byte[] resultSid;
//
// Give us something to work with
//
if (sddlForm == null)
{
throw new ArgumentNullException("sddlForm");
}
Contract.EndContractBlock();
//
// Call into the underlying O/S conversion routine
//
int Error = Win32.CreateSidFromString(sddlForm, out resultSid);
if (Error == Interop.mincore.Errors.ERROR_INVALID_SID)
{
throw new ArgumentException(SR.Argument_InvalidValue, "sddlForm");
}
else if (Error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error));
throw new Exception(Interop.mincore.GetMessage(Error));
}
CreateFromBinaryForm(resultSid, 0);
}
//
// Constructs a SecurityIdentifier object from its binary representation
//
public SecurityIdentifier(byte[] binaryForm, int offset)
{
CreateFromBinaryForm(binaryForm, offset);
}
//
// Constructs a SecurityIdentifier object from an IntPtr
//
public SecurityIdentifier(IntPtr binaryForm)
: this(binaryForm, true)
{
}
internal SecurityIdentifier(IntPtr binaryForm, bool noDemand)
: this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0)
{
}
//
// Constructs a well-known SID
// The 'domainSid' parameter is optional and only used
// by the well-known types that require it
// NOTE: although there is a P/Invoke call involved in the implementation of this constructor,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
{
//
// sidType must not be equal to LogonIdsSid
//
if (sidType == WellKnownSidType.LogonIdsSid)
{
throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, "sidType");
}
Contract.EndContractBlock();
byte[] resultSid;
int Error;
//
// sidType should not exceed the max defined value
//
if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.MaxDefined))
{
throw new ArgumentException(SR.Argument_InvalidValue, "sidType");
}
//
// for sidType between 38 to 50, the domainSid parameter must be specified
//
if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid))
{
if (domainSid == null)
{
throw new ArgumentNullException("domainSid", SR.Format(SR.IdentityReference_DomainSidRequired, sidType));
}
//
// verify that the domain sid is a valid windows domain sid
// to do that we call GetAccountDomainSid and the return value should be the same as the domainSid
//
SecurityIdentifier resultDomainSid;
int ErrorCode;
ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid);
if (ErrorCode == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (ErrorCode == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID)
{
// this means that the domain sid is not valid
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, "domainSid");
}
else if (ErrorCode != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode));
throw new Exception(Interop.mincore.GetMessage(ErrorCode));
}
//
// if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid
// Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities)
//
if (resultDomainSid != domainSid)
{
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, "domainSid");
}
}
Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid);
if (Error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER)
{
throw new ArgumentException(Interop.mincore.GetMessage(Error), "sidType/domainSid");
}
else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error));
throw new Exception(Interop.mincore.GetMessage(Error));
}
CreateFromBinaryForm(resultSid, 0);
}
internal SecurityIdentifier(SecurityIdentifier domainSid, uint rid)
{
int i;
int[] SubAuthorities = new int[domainSid.SubAuthorityCount + 1];
for (i = 0; i < domainSid.SubAuthorityCount; i++)
{
SubAuthorities[i] = domainSid.GetSubAuthority(i);
}
SubAuthorities[i] = (int)rid;
CreateFromParts(domainSid.IdentifierAuthority, SubAuthorities);
}
internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
CreateFromParts(identifierAuthority, subAuthorities);
}
#endregion
#region Static Properties
//
// Revision is always '1'
//
internal static byte Revision
{
get
{
return 1;
}
}
#endregion
#region Non-static Properties
//
// This is for internal consumption only, hence it is marked 'internal'
// Making this call public would require a deep copy of the data to
// prevent the caller from messing with the internal representation.
//
internal byte[] BinaryForm
{
get
{
return _binaryForm;
}
}
internal IdentifierAuthority IdentifierAuthority
{
get
{
return _identifierAuthority;
}
}
internal int SubAuthorityCount
{
get
{
return _subAuthorities.Length;
}
}
public int BinaryLength
{
get
{
return _binaryForm.Length;
}
}
//
// Returns the domain portion of a SID or null if the specified
// SID is not an account SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier AccountDomainSid
{
get
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
return _accountDomainSid;
}
}
#endregion
#region Inherited properties and methods
public override bool Equals(object o)
{
if (o == null)
{
return false;
}
SecurityIdentifier sid = o as SecurityIdentifier;
if (sid == null)
{
return false;
}
return (this == sid); // invokes operator==
}
public bool Equals(SecurityIdentifier sid)
{
if (sid == null)
{
return false;
}
return (this == sid); // invokes operator==
}
public override int GetHashCode()
{
int hashCode = ((long)this.IdentifierAuthority).GetHashCode();
for (int i = 0; i < SubAuthorityCount; i++)
{
hashCode ^= this.GetSubAuthority(i);
}
return hashCode;
}
public override string ToString()
{
if (_sddlForm == null)
{
StringBuilder result = new StringBuilder();
//
// Typecasting of _IdentifierAuthority to a long below is important, since
// otherwise you would see this: "S-1-NTAuthority-32-544"
//
result.AppendFormat("S-1-{0}", (long)_identifierAuthority);
for (int i = 0; i < SubAuthorityCount; i++)
{
result.AppendFormat("-{0}", (uint)(_subAuthorities[i]));
}
_sddlForm = result.ToString();
}
return _sddlForm;
}
public override string Value
{
get
{
return ToString().ToUpperInvariant();
}
}
internal static bool IsValidTargetTypeStatic(Type targetType)
{
if (targetType == typeof(NTAccount))
{
return true;
}
else if (targetType == typeof(SecurityIdentifier))
{
return true;
}
else
{
return false;
}
}
public override bool IsValidTargetType(Type targetType)
{
return IsValidTargetTypeStatic(targetType);
}
internal SecurityIdentifier GetAccountDomainSid()
{
SecurityIdentifier ResultSid;
int Error;
Error = Win32.GetWindowsAccountDomainSid(this, out ResultSid);
if (Error == Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (Error == Interop.mincore.Errors.ERROR_NON_ACCOUNT_SID)
{
ResultSid = null;
}
else if (Error != Interop.mincore.Errors.ERROR_SUCCESS)
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error));
throw new Exception(Interop.mincore.GetMessage(Error));
}
return ResultSid;
}
public bool IsAccountSid()
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
if (_accountDomainSid == null)
{
return false;
}
return true;
}
public override IdentityReference Translate(Type targetType)
{
if (targetType == null)
{
throw new ArgumentNullException("targetType");
}
Contract.EndContractBlock();
if (targetType == typeof(SecurityIdentifier))
{
return this; // assumes SecurityIdentifier objects are immutable
}
else if (targetType == typeof(NTAccount))
{
IdentityReferenceCollection irSource = new IdentityReferenceCollection(1);
irSource.Add(this);
IdentityReferenceCollection irTarget;
irTarget = SecurityIdentifier.Translate(irSource, targetType, true);
return irTarget[0];
}
else
{
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType");
}
}
#endregion
#region Operators
public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
{
object l = left;
object r = right;
if (l == null && r == null)
{
return true;
}
else if (l == null || r == null)
{
return false;
}
else
{
return (left.CompareTo(right) == 0);
}
}
public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
{
return !(left == right);
}
#endregion
#region IComparable implementation
public int CompareTo(SecurityIdentifier sid)
{
if (sid == null)
{
throw new ArgumentNullException("sid");
}
Contract.EndContractBlock();
if (this.IdentifierAuthority < sid.IdentifierAuthority)
{
return -1;
}
if (this.IdentifierAuthority > sid.IdentifierAuthority)
{
return 1;
}
if (this.SubAuthorityCount < sid.SubAuthorityCount)
{
return -1;
}
if (this.SubAuthorityCount > sid.SubAuthorityCount)
{
return 1;
}
for (int i = 0; i < this.SubAuthorityCount; i++)
{
int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i);
if (diff != 0)
{
return diff;
}
}
return 0;
}
#endregion
#region Public Methods
internal int GetSubAuthority(int index)
{
return _subAuthorities[index];
}
//
// Determines whether this SID is a well-known SID of the specified type
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsWellKnown(WellKnownSidType type)
{
return Win32.IsWellKnownSid(this, type);
}
public void GetBinaryForm(byte[] binaryForm, int offset)
{
_binaryForm.CopyTo(binaryForm, offset);
}
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsEqualDomainSid(SecurityIdentifier sid)
{
return Win32.IsEqualDomainSid(this, sid);
}
private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException("sourceSids");
}
if (sourceSids.Count == 0)
{
throw new ArgumentException(SR.Arg_EmptyCollection, "sourceSids");
}
Contract.EndContractBlock();
IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count];
GCHandle[] HandleArray = new GCHandle[sourceSids.Count];
SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle;
SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle;
try
{
//
// Pin all elements in the array of SIDs
//
int currentSid = 0;
foreach (IdentityReference id in sourceSids)
{
SecurityIdentifier sid = id as SecurityIdentifier;
if (sid == null)
{
throw new ArgumentException(SR.Argument_ImproperType, "sourceSids");
}
HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned);
SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject();
currentSid++;
}
//
// Open LSA policy (for lookup requires it)
//
LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
//
// Perform the actual lookup
//
someFailed = false;
uint ReturnCode;
ReturnCode = Interop.mincore.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr);
//
// Make a decision regarding whether it makes sense to proceed
// based on the return code and the value of the forceSuccess argument
//
if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
{
throw new OutOfMemoryException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
someFailed = true;
}
else if (ReturnCode != 0)
{
int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode));
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode));
throw new Exception(Interop.mincore.GetMessage(win32ErrorCode));
}
NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>());
Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
//
// Interpret the results and generate NTAccount objects
//
IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count);
if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
//
// Interpret the results and generate NT Account objects
//
Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
string[] ReferencedDomains = new string[rdl.Entries];
for (int i = 0; i < rdl.Entries; i++)
{
Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>()));
ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char));
}
Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count];
NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length);
for (int i = 0; i < sourceSids.Count; i++)
{
Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i];
switch ((SidNameUse)Ltn.Use)
{
case SidNameUse.User:
case SidNameUse.Group:
case SidNameUse.Alias:
case SidNameUse.Computer:
case SidNameUse.WellKnownGroup:
string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ;
string domain = ReferencedDomains[Ltn.DomainIndex];
Result.Add(new NTAccount(domain, account));
break;
default:
someFailed = true;
Result.Add(sourceSids[i]);
break;
}
}
}
else
{
for (int i = 0; i < sourceSids.Count; i++)
{
Result.Add(sourceSids[i]);
}
}
return Result;
}
finally
{
for (int i = 0; i < sourceSids.Count; i++)
{
if (HandleArray[i].IsAllocated)
{
HandleArray[i].Free();
}
}
LsaHandle.Dispose();
ReferencedDomainsPtr.Dispose();
NamesPtr.Dispose();
}
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess)
{
bool SomeFailed = false;
IdentityReferenceCollection Result;
Result = Translate(sourceSids, targetType, out SomeFailed);
if (forceSuccess && SomeFailed)
{
IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection();
foreach (IdentityReference id in Result)
{
if (id.GetType() != targetType)
{
UnmappedIdentities.Add(id);
}
}
throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities);
}
return Result;
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException("sourceSids");
}
Contract.EndContractBlock();
if (targetType == typeof(NTAccount))
{
return TranslateToNTAccounts(sourceSids, out someFailed);
}
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType");
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Xunit;
using System.Text;
using System.ComponentModel;
using System.Security;
namespace System.Diagnostics.Tests
{
public partial class ProcessStartInfoTests : ProcessTestBase
{
[Fact]
public void TestEnvironmentProperty()
{
Assert.NotEqual(0, new Process().StartInfo.Environment.Count);
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
IDictionary<string, string> environment = psi.Environment;
Assert.NotEqual(0, environment.Count);
int countItems = environment.Count;
environment.Add("NewKey", "NewValue");
environment.Add("NewKey2", "NewValue2");
Assert.Equal(countItems + 2, environment.Count);
environment.Remove("NewKey");
Assert.Equal(countItems + 1, environment.Count);
environment.Add("NewKey2", "NewValue2Overridden");
Assert.Equal("NewValue2Overridden", environment["NewKey2"]);
//Clear
environment.Clear();
Assert.Equal(0, environment.Count);
//ContainsKey
environment.Add("NewKey", "NewValue");
environment.Add("NewKey2", "NewValue2");
Assert.True(environment.ContainsKey("NewKey"));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey"));
Assert.False(environment.ContainsKey("NewKey99"));
//Iterating
string result = null;
int index = 0;
foreach (string e1 in environment.Values.OrderBy(p => p))
{
index++;
result += e1;
}
Assert.Equal(2, index);
Assert.Equal("NewValueNewValue2", result);
result = null;
index = 0;
foreach (string e1 in environment.Keys.OrderBy(p => p))
{
index++;
result += e1;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
result = null;
index = 0;
foreach (KeyValuePair<string, string> e1 in environment.OrderBy(p => p.Key))
{
index++;
result += e1.Key;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
//Contains
Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue")));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99")));
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99")));
environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98"));
//Indexed
string newIndexItem = environment["NewKey98"];
Assert.Equal("NewValue98", newIndexItem);
//TryGetValue
string stringout = null;
Assert.True(environment.TryGetValue("NewKey", out stringout));
Assert.Equal("NewValue", stringout);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.True(environment.TryGetValue("NeWkEy", out stringout));
Assert.Equal("NewValue", stringout);
}
stringout = null;
Assert.False(environment.TryGetValue("NewKey99", out stringout));
Assert.Equal(null, stringout);
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
string stringout1 = null;
environment.TryGetValue(null, out stringout1);
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2"));
environment.Add("NewKey2", "NewValue2OverriddenAgain");
Assert.Equal("NewValue2OverriddenAgain", environment["NewKey2"]);
//Remove Item
environment.Remove("NewKey98");
environment.Remove("NewKey98"); //2nd occurrence should not assert
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); });
//"Exception not thrown with null key"
Assert.Throws<KeyNotFoundException>(() => environment["1bB"]);
Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2OverriddenAgain")));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2OverriddenAgain")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2Overriddenagain")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2Overriddenagain")));
//Use KeyValuePair Enumerator
string[] results = new string[2];
var x = environment.GetEnumerator();
x.MoveNext();
results[0] = x.Current.Key + " " + x.Current.Value;
x.MoveNext();
results[1] = x.Current.Key + " " + x.Current.Value;
Assert.Equal(new string[] { "NewKey NewValue", "NewKey2 NewValue2OverriddenAgain" }, results.OrderBy(s => s));
//IsReadonly
Assert.False(environment.IsReadOnly);
environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3"));
environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4"));
//CopyTo - the order is undefined.
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10];
environment.CopyTo(kvpa, 0);
KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Value).ToArray();
Assert.Equal("NewKey4", kvpaOrdered[0].Key);
Assert.Equal("NewKey2", kvpaOrdered[2].Key);
environment.CopyTo(kvpa, 6);
Assert.Equal(default(KeyValuePair<string, string>), kvpa[5]);
Assert.StartsWith("NewKey", kvpa[6].Key);
Assert.NotEqual(kvpa[6].Key, kvpa[7].Key);
Assert.StartsWith("NewKey", kvpa[7].Key);
Assert.NotEqual(kvpa[7].Key, kvpa[8].Key);
Assert.StartsWith("NewKey", kvpa[8].Key);
//Exception not thrown with null key
Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); });
//Exception not thrown with null key
Assert.Throws<ArgumentException>(() => { environment.CopyTo(kvpa, 9); });
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() =>
{
KeyValuePair<string, string>[] kvpanull = null;
environment.CopyTo(kvpanull, 0);
});
}
[Fact]
public void TestEnvironmentOfChildProcess()
{
const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings
const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff";
Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output
try
{
// Schedule a process to see what env vars it gets. Have it write out those variables
// to its output stream so we can read them.
Process p = CreateProcess(() =>
{
Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => Convert.ToBase64String(Encoding.UTF8.GetBytes(e.Key + "=" + e.Value)))));
return SuccessExitCode;
});
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Assert.True(p.WaitForExit(WaitInMS));
// Parse the env vars from the child process
var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None).Select(s => Encoding.UTF8.GetString(Convert.FromBase64String(s))));
// Validate against StartInfo.Environment.
var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value));
Assert.True(startInfoEnv.SetEquals(actualEnv),
string.Format("Expected: {0}{1}Actual: {2}",
string.Join(", ", startInfoEnv.Except(actualEnv)),
Environment.NewLine,
string.Join(", ", actualEnv.Except(startInfoEnv))));
// Validate against current process. (Profilers / code coverage tools can add own environment variables
// but we start child process without them. Thus the set of variables from the child process could
// be a subset of variables from current process.)
var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value));
Assert.True(envEnv.IsSupersetOf(actualEnv),
string.Format("Expected: {0}{1}Actual: {2}",
string.Join(", ", envEnv.Except(actualEnv)),
Environment.NewLine,
string.Join(", ", actualEnv.Except(envEnv))));
}
finally
{
Environment.SetEnvironmentVariable(ExtraEnvVar, null);
}
}
[PlatformSpecific(TestPlatforms.Windows)] // UseShellExecute currently not supported on Windows on .NET Core
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default but UseShellExecute=true is not supported on Core")]
public void UseShellExecute_GetSetWindows_Success_Netcore()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.False(psi.UseShellExecute);
// Calling the setter
Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; });
psi.UseShellExecute = false;
// Calling the getter
Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore.");
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Desktop UseShellExecute is set to true by default but UseShellExecute=true is not supported on Core")]
public void UseShellExecute_GetSetWindows_Success_Netfx()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.True(psi.UseShellExecute);
psi.UseShellExecute = false;
Assert.False(psi.UseShellExecute);
psi.UseShellExecute = true;
Assert.True(psi.UseShellExecute);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows
[Fact]
public void TestUseShellExecuteProperty_SetAndGet_Unix()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.False(psi.UseShellExecute);
psi.UseShellExecute = true;
Assert.True(psi.UseShellExecute);
psi.UseShellExecute = false;
Assert.False(psi.UseShellExecute);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // UseShellExecute currently not supported on Windows
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void TestUseShellExecuteProperty_Redirects_NotSupported(int std)
{
Process p = CreateProcessLong();
p.StartInfo.UseShellExecute = true;
switch (std)
{
case 0: p.StartInfo.RedirectStandardInput = true; break;
case 1: p.StartInfo.RedirectStandardOutput = true; break;
case 2: p.StartInfo.RedirectStandardError = true; break;
}
Assert.Throws<InvalidOperationException>(() => p.Start());
}
[Fact]
public void TestArgumentsProperty()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.Equal(string.Empty, psi.Arguments);
psi = new ProcessStartInfo("filename", "-arg1 -arg2");
Assert.Equal("-arg1 -arg2", psi.Arguments);
psi.Arguments = "-arg3 -arg4";
Assert.Equal("-arg3 -arg4", psi.Arguments);
}
[Theory, InlineData(true), InlineData(false)]
public void TestCreateNoWindowProperty(bool value)
{
Process testProcess = CreateProcessLong();
try
{
testProcess.StartInfo.CreateNoWindow = value;
testProcess.Start();
Assert.Equal(value, testProcess.StartInfo.CreateNoWindow);
}
finally
{
if (!testProcess.HasExited)
testProcess.Kill();
Assert.True(testProcess.WaitForExit(WaitInMS));
}
}
[Fact]
public void TestWorkingDirectoryProperty()
{
// check defaults
Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory);
Process p = CreateProcessLong();
p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
try
{
p.Start();
Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory);
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[ActiveIssue(12696)]
[Fact, PlatformSpecific(TestPlatforms.Windows), OuterLoop] // Uses P/Invokes, Requires admin privileges
public void TestUserCredentialsPropertiesOnWindows()
{
string username = "test", password = "PassWord123!!";
try
{
Interop.NetUserAdd(username, password);
}
catch (Exception exc)
{
Console.Error.WriteLine("TestUserCredentialsPropertiesOnWindows: NetUserAdd failed: {0}", exc.Message);
return; // test is irrelevant if we can't add a user
}
bool hasStarted = false;
SafeProcessHandle handle = null;
Process p = null;
try
{
p = CreateProcessLong();
p.StartInfo.LoadUserProfile = true;
p.StartInfo.UserName = username;
p.StartInfo.PasswordInClearText = password;
hasStarted = p.Start();
if (Interop.OpenProcessToken(p.SafeHandle, 0x8u, out handle))
{
SecurityIdentifier sid;
if (Interop.ProcessTokenToSid(handle, out sid))
{
string actualUserName = sid.Translate(typeof(NTAccount)).ToString();
int indexOfDomain = actualUserName.IndexOf('\\');
if (indexOfDomain != -1)
actualUserName = actualUserName.Substring(indexOfDomain + 1);
bool isProfileLoaded = GetNamesOfUserProfiles().Any(profile => profile.Equals(username));
Assert.Equal(username, actualUserName);
Assert.True(isProfileLoaded);
}
}
}
finally
{
IEnumerable<uint> collection = new uint[] { 0 /* NERR_Success */, 2221 /* NERR_UserNotFound */ };
Assert.Contains<uint>(Interop.NetUserDel(null, username), collection);
if (handle != null)
handle.Dispose();
if (hasStarted)
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
}
private static List<string> GetNamesOfUserProfiles()
{
List<string> userNames = new List<string>();
string[] names = Registry.Users.GetSubKeyNames();
for (int i = 1; i < names.Length; i++)
{
try
{
SecurityIdentifier sid = new SecurityIdentifier(names[i]);
string userName = sid.Translate(typeof(NTAccount)).ToString();
int indexofDomain = userName.IndexOf('\\');
if (indexofDomain != -1)
{
userName = userName.Substring(indexofDomain + 1);
userNames.Add(userName);
}
}
catch (Exception) { }
}
return userNames;
}
[Fact]
public void TestEnvironmentVariables_Environment_DataRoundTrips()
{
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
psi.Environment.Clear();
psi.EnvironmentVariables.Add("NewKey", "NewValue");
psi.Environment.Add("NewKey2", "NewValue2");
Assert.Equal(psi.Environment["NewKey"], psi.EnvironmentVariables["NewKey"]);
Assert.Equal(psi.Environment["NewKey2"], psi.EnvironmentVariables["NewKey2"]);
Assert.Equal(2, psi.EnvironmentVariables.Count);
Assert.Equal(psi.Environment.Count, psi.EnvironmentVariables.Count);
Assert.Throws<ArgumentException>(null, () => psi.EnvironmentVariables.Add("NewKey2", "NewValue2"));
psi.EnvironmentVariables.Add("NewKey3", "NewValue3");
psi.Environment.Add("NewKey3", "NewValue3Overridden");
Assert.Equal("NewValue3Overridden", psi.Environment["NewKey3"]);
psi.EnvironmentVariables.Clear();
Assert.Equal(0, psi.Environment.Count);
psi.EnvironmentVariables.Add("NewKey", "NewValue");
psi.EnvironmentVariables.Add("NewKey2", "NewValue2");
// Environment and EnvironmentVariables should be equal, but have different enumeration types.
IEnumerable<KeyValuePair<string, string>> allEnvironment = psi.Environment.OrderBy(k => k.Key);
IEnumerable<DictionaryEntry> allDictionary = psi.EnvironmentVariables.Cast<DictionaryEntry>().OrderBy(k => k.Key);
Assert.Equal(allEnvironment.Select(k => new DictionaryEntry(k.Key, k.Value)), allDictionary);
psi.EnvironmentVariables.Add("NewKey3", "NewValue3");
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[5];
psi.Environment.CopyTo(kvpa, 0);
KeyValuePair<string, string>[] kvpaOrdered = kvpa.OrderByDescending(k => k.Key).ToArray();
Assert.Equal("NewKey", kvpaOrdered[2].Key);
Assert.Equal("NewValue", kvpaOrdered[2].Value);
psi.EnvironmentVariables.Remove("NewKey3");
Assert.False(psi.Environment.Contains(new KeyValuePair<string,string>("NewKey3", "NewValue3")));
}
[PlatformSpecific(TestPlatforms.Windows)] // Test case is specific to Windows
[Fact]
public void Verbs_GetWithExeExtension_ReturnsExpected()
{
var psi = new ProcessStartInfo { FileName = $"{Process.GetCurrentProcess().ProcessName}.exe" };
Assert.Contains("open", psi.Verbs, StringComparer.OrdinalIgnoreCase);
if (PlatformDetection.IsNotWindowsNanoServer)
{
Assert.Contains("runas", psi.Verbs, StringComparer.OrdinalIgnoreCase);
Assert.Contains("runasuser", psi.Verbs, StringComparer.OrdinalIgnoreCase);
}
Assert.DoesNotContain("printto", psi.Verbs, StringComparer.OrdinalIgnoreCase);
Assert.DoesNotContain("closed", psi.Verbs, StringComparer.OrdinalIgnoreCase);
}
[Theory]
[InlineData("")]
[InlineData("nofileextension")]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoExtension_ReturnsEmpty(string fileName)
{
var info = new ProcessStartInfo { FileName = fileName };
Assert.Empty(info.Verbs);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoRegisteredExtension_ReturnsEmpty()
{
var info = new ProcessStartInfo { FileName = "file.nosuchextension" };
Assert.Empty(info.Verbs);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoEmptyStringKey_ReturnsEmpty()
{
const string Extension = ".noemptykeyextension";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithEmptyStringValue_ReturnsEmpty()
{
const string Extension = ".emptystringextension";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
tempKey.Key.SetValue("", "");
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework throws an InvalidCastException for non-string keys. See https://github.com/dotnet/corefx/issues/18187.")]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNonStringValue_ReturnsEmpty()
{
const string Extension = ".nonstringextension";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
tempKey.Key.SetValue("", 123);
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithNoShellSubKey_ReturnsEmpty()
{
const string Extension = ".noshellsubkey";
const string FileName = "file" + Extension;
using (TempRegistryKey tempKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
{
if (tempKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
tempKey.Key.SetValue("", "nosuchshell");
var info = new ProcessStartInfo { FileName = FileName };
Assert.Empty(info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetWithSubkeys_ReturnsEmpty()
{
const string Extension = ".customregistryextension";
const string FileName = "file" + Extension;
const string SubKeyValue = "customregistryextensionshell";
using (TempRegistryKey extensionKey = new TempRegistryKey(Registry.ClassesRoot, Extension))
using (TempRegistryKey shellKey = new TempRegistryKey(Registry.ClassesRoot, SubKeyValue + "\\shell"))
{
if (extensionKey.Key == null)
{
// Skip this test if the user doesn't have permission to
// modify the registry.
return;
}
extensionKey.Key.SetValue("", SubKeyValue);
shellKey.Key.CreateSubKey("verb1");
shellKey.Key.CreateSubKey("NEW");
shellKey.Key.CreateSubKey("new");
shellKey.Key.CreateSubKey("verb2");
var info = new ProcessStartInfo { FileName = FileName };
Assert.Equal(new string[] { "verb1", "verb2" }, info.Verbs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Verbs_GetUnix_ReturnsEmpty()
{
var info = new ProcessStartInfo();
Assert.Empty(info.Verbs);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Test case is specific to Unix
[Fact]
public void TestEnvironmentVariablesPropertyUnix(){
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
StringDictionary environmentVariables = psi.EnvironmentVariables;
Assert.NotEqual(0, environmentVariables.Count);
int CountItems = environmentVariables.Count;
environmentVariables.Add("NewKey", "NewValue");
environmentVariables.Add("NewKey2", "NewValue2");
Assert.Equal(CountItems + 2, environmentVariables.Count);
environmentVariables.Remove("NewKey");
Assert.Equal(CountItems + 1, environmentVariables.Count);
//Exception not thrown with invalid key
Assert.Throws<ArgumentException>(() => { environmentVariables.Add("NewKey2", "NewValue2"); });
Assert.False(environmentVariables.ContainsKey("NewKey"));
environmentVariables.Add("newkey2", "newvalue2");
Assert.True(environmentVariables.ContainsKey("newkey2"));
Assert.Equal("newvalue2", environmentVariables["newkey2"]);
Assert.Equal("NewValue2", environmentVariables["NewKey2"]);
environmentVariables.Clear();
Assert.Equal(0, environmentVariables.Count);
environmentVariables.Add("NewKey", "newvalue");
environmentVariables.Add("newkey2", "NewValue2");
Assert.False(environmentVariables.ContainsKey("newkey"));
Assert.False(environmentVariables.ContainsValue("NewValue"));
string result = null;
int index = 0;
foreach (string e1 in environmentVariables.Values)
{
index++;
result += e1;
}
Assert.Equal(2, index);
Assert.Equal("newvalueNewValue2", result);
result = null;
index = 0;
foreach (string e1 in environmentVariables.Keys)
{
index++;
result += e1;
}
Assert.Equal("NewKeynewkey2", result);
Assert.Equal(2, index);
result = null;
index = 0;
foreach (DictionaryEntry e1 in environmentVariables)
{
index++;
result += e1.Key;
}
Assert.Equal("NewKeynewkey2", result);
Assert.Equal(2, index);
//Key not found
Assert.Throws<KeyNotFoundException>(() =>
{
string stringout = environmentVariables["NewKey99"];
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
string stringout = environmentVariables[null];
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environmentVariables.Add(null, "NewValue2"));
Assert.Throws<ArgumentException>(() => environmentVariables.Add("newkey2", "NewValue2"));
//Use DictionaryEntry Enumerator
var x = environmentVariables.GetEnumerator() as IEnumerator;
x.MoveNext();
var y1 = (DictionaryEntry)x.Current;
Assert.Equal("NewKey newvalue", y1.Key + " " + y1.Value);
x.MoveNext();
y1 = (DictionaryEntry)x.Current;
Assert.Equal("newkey2 NewValue2", y1.Key + " " + y1.Value);
environmentVariables.Add("newkey3", "newvalue3");
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10];
environmentVariables.CopyTo(kvpa, 0);
Assert.Equal("NewKey", kvpa[0].Key);
Assert.Equal("newkey3", kvpa[2].Key);
Assert.Equal("newvalue3", kvpa[2].Value);
string[] kvp = new string[10];
Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvp, 6); });
environmentVariables.CopyTo(kvpa, 6);
Assert.Equal("NewKey", kvpa[6].Key);
Assert.Equal("newvalue", kvpa[6].Value);
Assert.Throws<ArgumentOutOfRangeException>(() => { environmentVariables.CopyTo(kvpa, -1); });
Assert.Throws<ArgumentException>(() => { environmentVariables.CopyTo(kvpa, 9); });
Assert.Throws<ArgumentNullException>(() =>
{
KeyValuePair<string, string>[] kvpanull = null;
environmentVariables.CopyTo(kvpanull, 0);
});
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("domain")]
[PlatformSpecific(TestPlatforms.Windows)]
public void Domain_SetWindows_GetReturnsExpected(string domain)
{
var info = new ProcessStartInfo { Domain = domain };
Assert.Equal(domain ?? string.Empty, info.Domain);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Domain_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.Domain);
Assert.Throws<PlatformNotSupportedException>(() => info.Domain = "domain");
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("filename")]
public void FileName_Set_GetReturnsExpected(string fileName)
{
var info = new ProcessStartInfo { FileName = fileName };
Assert.Equal(fileName ?? string.Empty, info.FileName);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[PlatformSpecific(TestPlatforms.Windows)]
public void LoadUserProfile_SetWindows_GetReturnsExpected(bool loadUserProfile)
{
var info = new ProcessStartInfo { LoadUserProfile = loadUserProfile };
Assert.Equal(loadUserProfile, info.LoadUserProfile);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void LoadUserProfile_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile);
Assert.Throws<PlatformNotSupportedException>(() => info.LoadUserProfile = false);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("passwordInClearText")]
[PlatformSpecific(TestPlatforms.Windows)]
public void PasswordInClearText_SetWindows_GetReturnsExpected(string passwordInClearText)
{
var info = new ProcessStartInfo { PasswordInClearText = passwordInClearText };
Assert.Equal(passwordInClearText, info.PasswordInClearText);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void PasswordInClearText_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText);
Assert.Throws<PlatformNotSupportedException>(() => info.PasswordInClearText = "passwordInClearText");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Password_SetWindows_GetReturnsExpected()
{
using (SecureString password = new SecureString())
{
password.AppendChar('a');
var info = new ProcessStartInfo { Password = password };
Assert.Equal(password, info.Password);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Password_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.Password);
Assert.Throws<PlatformNotSupportedException>(() => info.Password = new SecureString());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("domain")]
[PlatformSpecific(TestPlatforms.Windows)]
public void UserName_SetWindows_GetReturnsExpected(string userName)
{
var info = new ProcessStartInfo { UserName = userName };
Assert.Equal(userName ?? string.Empty, info.UserName);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void UserName_GetSetUnix_ThrowsPlatformNotSupportedException()
{
var info = new ProcessStartInfo();
Assert.Throws<PlatformNotSupportedException>(() => info.UserName);
Assert.Throws<PlatformNotSupportedException>(() => info.UserName = "username");
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("verb")]
public void Verb_Set_GetReturnsExpected(string verb)
{
var info = new ProcessStartInfo { Verb = verb };
Assert.Equal(verb ?? string.Empty, info.Verb);
}
[Theory]
[InlineData(ProcessWindowStyle.Normal - 1)]
[InlineData(ProcessWindowStyle.Maximized + 1)]
public void WindowStyle_SetNoSuchWindowStyle_ThrowsInvalidEnumArgumentException(ProcessWindowStyle style)
{
var info = new ProcessStartInfo();
Assert.Throws<InvalidEnumArgumentException>(() => info.WindowStyle = style);
}
[Theory]
[InlineData(ProcessWindowStyle.Hidden)]
[InlineData(ProcessWindowStyle.Maximized)]
[InlineData(ProcessWindowStyle.Minimized)]
[InlineData(ProcessWindowStyle.Normal)]
public void WindowStyle_Set_GetReturnsExpected(ProcessWindowStyle style)
{
var info = new ProcessStartInfo { WindowStyle = style };
Assert.Equal(style, info.WindowStyle);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("workingdirectory")]
public void WorkingDirectory_Set_GetReturnsExpected(string workingDirectory)
{
var info = new ProcessStartInfo { WorkingDirectory = workingDirectory };
Assert.Equal(workingDirectory ?? string.Empty, info.WorkingDirectory);
}
}
}
| |
using System;
using System.Reflection;
using Fasterflect;
namespace Python.Runtime
{
using MaybeFieldInfo = MaybeMemberInfo<FieldInfo>;
/// <summary>
/// Implements a Python descriptor type that provides access to CLR fields.
/// </summary>
[Serializable]
internal class FieldObject : ExtensionType
{
private MaybeFieldInfo info;
private MemberGetter _memberGetter;
private Type _memberGetterType;
private MemberSetter _memberSetter;
private Type _memberSetterType;
private bool _isValueType;
private Type _isValueTypeType;
public FieldObject(FieldInfo info)
{
this.info = info;
}
/// <summary>
/// Descriptor __get__ implementation. This method returns the
/// value of the field on the given object. The returned value
/// is converted to an appropriately typed Python object.
/// </summary>
public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp)
{
var self = (FieldObject)GetManagedObject(ds);
object result;
if (self == null)
{
return IntPtr.Zero;
}
else if (!self.info.Valid)
{
Exceptions.SetError(Exceptions.AttributeError, self.info.DeletedMessage);
return IntPtr.Zero;
}
FieldInfo info = self.info.Value;
if (ob == IntPtr.Zero || ob == Runtime.PyNone)
{
if (!info.IsStatic)
{
Exceptions.SetError(Exceptions.TypeError,
"instance attribute must be accessed through a class instance");
return IntPtr.Zero;
}
try
{
// Fasterflect does not support constant fields
if (info.IsLiteral && !info.IsInitOnly)
{
result = info.GetValue(null);
}
else
{
result = self.GetMemberGetter(info.DeclaringType)(info.DeclaringType);
}
return Converter.ToPython(result, info.FieldType);
}
catch (Exception e)
{
Exceptions.SetError(Exceptions.TypeError, e.Message);
return IntPtr.Zero;
}
}
try
{
var co = (CLRObject)GetManagedObject(ob);
if (co == null)
{
Exceptions.SetError(Exceptions.TypeError, "instance is not a clr object");
return IntPtr.Zero;
}
// Fasterflect does not support constant fields
if (info.IsLiteral && !info.IsInitOnly)
{
result = info.GetValue(co.inst);
}
else
{
var type = co.inst.GetType();
result = self.GetMemberGetter(type)(self.IsValueType(type) ? co.inst.WrapIfValueType() : co.inst);
}
return Converter.ToPython(result, info.FieldType);
}
catch (Exception e)
{
Exceptions.SetError(Exceptions.TypeError, e.Message);
return IntPtr.Zero;
}
}
/// <summary>
/// Descriptor __set__ implementation. This method sets the value of
/// a field based on the given Python value. The Python value must be
/// convertible to the type of the field.
/// </summary>
public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val)
{
var self = (FieldObject)GetManagedObject(ds);
object newval;
if (self == null)
{
return -1;
}
else if (!self.info.Valid)
{
Exceptions.SetError(Exceptions.AttributeError, self.info.DeletedMessage);
return -1;
}
if (val == IntPtr.Zero)
{
Exceptions.SetError(Exceptions.TypeError, "cannot delete field");
return -1;
}
FieldInfo info = self.info.Value;
if (info.IsLiteral || info.IsInitOnly)
{
Exceptions.SetError(Exceptions.TypeError, "field is read-only");
return -1;
}
bool is_static = info.IsStatic;
if (ob == IntPtr.Zero || ob == Runtime.PyNone)
{
if (!is_static)
{
Exceptions.SetError(Exceptions.TypeError, "instance attribute must be set through a class instance");
return -1;
}
}
if (!Converter.ToManaged(val, info.FieldType, out newval, true))
{
return -1;
}
try
{
if (!is_static)
{
var co = (CLRObject)GetManagedObject(ob);
if (co == null)
{
Exceptions.SetError(Exceptions.TypeError, "instance is not a clr object");
return -1;
}
// Fasterflect does not support constant fields
if (info.IsLiteral && !info.IsInitOnly)
{
info.SetValue(co.inst, newval);
}
else
{
var type = co.inst.GetType();
self.GetMemberSetter(type)(self.IsValueType(type) ? co.inst.WrapIfValueType() : co.inst, newval);
}
}
else
{
// Fasterflect does not support constant fields
if (info.IsLiteral && !info.IsInitOnly)
{
info.SetValue(null, newval);
}
else
{
self.GetMemberSetter(info.DeclaringType)(info.DeclaringType, newval);
}
}
return 0;
}
catch (Exception e)
{
Exceptions.SetError(Exceptions.TypeError, e.Message);
return -1;
}
}
/// <summary>
/// Descriptor __repr__ implementation.
/// </summary>
public static IntPtr tp_repr(IntPtr ob)
{
var self = (FieldObject)GetManagedObject(ob);
return Runtime.PyString_FromString($"<field '{self.info}'>");
}
private MemberGetter GetMemberGetter(Type type)
{
if (type != _memberGetterType)
{
_memberGetter = FasterflectManager.GetFieldGetter(type, info.Value.Name);
_memberGetterType = type;
}
return _memberGetter;
}
private MemberSetter GetMemberSetter(Type type)
{
if (type != _memberSetterType)
{
_memberSetter = FasterflectManager.GetFieldSetter(type, info.Value.Name);
_memberSetterType = type;
}
return _memberSetter;
}
private bool IsValueType(Type type)
{
if (type != _isValueTypeType)
{
_isValueType = FasterflectManager.IsValueType(type);
_isValueTypeType = type;
}
return _isValueType;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.InteropServices.ComTypes
{
public static class __IMoniker
{
public static IObservable<System.Guid> GetClassID(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue)
{
return Observable.Select(IMonikerValue, (IMonikerValueLambda) =>
{
System.Guid pClassIDOutput = default(System.Guid);
IMonikerValueLambda.GetClassID(out pClassIDOutput);
return pClassIDOutput;
});
}
public static IObservable<System.Int32> IsDirty(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue)
{
return Observable.Select(IMonikerValue, (IMonikerValueLambda) => IMonikerValueLambda.IsDirty());
}
public static IObservable<System.Reactive.Unit> Load(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IStream> pStm)
{
return ObservableExt.ZipExecute(IMonikerValue, pStm,
(IMonikerValueLambda, pStmLambda) => IMonikerValueLambda.Load(pStmLambda));
}
public static IObservable<System.Reactive.Unit> Save(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IStream> pStm, IObservable<System.Boolean> fClearDirty)
{
return ObservableExt.ZipExecute(IMonikerValue, pStm, fClearDirty,
(IMonikerValueLambda, pStmLambda, fClearDirtyLambda) =>
IMonikerValueLambda.Save(pStmLambda, fClearDirtyLambda));
}
public static IObservable<System.Int64> GetSizeMax(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue)
{
return Observable.Select(IMonikerValue, (IMonikerValueLambda) =>
{
System.Int64 pcbSizeOutput = default(System.Int64);
IMonikerValueLambda.GetSizeMax(out pcbSizeOutput);
return pcbSizeOutput;
});
}
public static IObservable<Tuple<System.Guid, System.Object>> BindToObject(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkToLeft, IObservable<System.Guid> riidResult)
{
return Observable.Zip(IMonikerValue, pbc, pmkToLeft, riidResult,
(IMonikerValueLambda, pbcLambda, pmkToLeftLambda, riidResultLambda) =>
{
System.Object ppvResultOutput = default(System.Object);
IMonikerValueLambda.BindToObject(pbcLambda, pmkToLeftLambda, ref riidResultLambda,
out ppvResultOutput);
return Tuple.Create(riidResultLambda, ppvResultOutput);
});
}
public static IObservable<Tuple<System.Guid, System.Object>> BindToStorage(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkToLeft, IObservable<System.Guid> riid)
{
return Observable.Zip(IMonikerValue, pbc, pmkToLeft, riid,
(IMonikerValueLambda, pbcLambda, pmkToLeftLambda, riidLambda) =>
{
System.Object ppvObjOutput = default(System.Object);
IMonikerValueLambda.BindToStorage(pbcLambda, pmkToLeftLambda, ref riidLambda, out ppvObjOutput);
return Tuple.Create(riidLambda, ppvObjOutput);
});
}
public static
IObservable
<
Tuple
<System.Runtime.InteropServices.ComTypes.IMoniker,
System.Runtime.InteropServices.ComTypes.IMoniker>> Reduce(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc, IObservable<System.Int32> dwReduceHowFar,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> ppmkToLeft)
{
return Observable.Zip(IMonikerValue, pbc, dwReduceHowFar, ppmkToLeft,
(IMonikerValueLambda, pbcLambda, dwReduceHowFarLambda, ppmkToLeftLambda) =>
{
System.Runtime.InteropServices.ComTypes.IMoniker ppmkReducedOutput =
default(System.Runtime.InteropServices.ComTypes.IMoniker);
IMonikerValueLambda.Reduce(pbcLambda, dwReduceHowFarLambda, ref ppmkToLeftLambda,
out ppmkReducedOutput);
return Tuple.Create(ppmkToLeftLambda, ppmkReducedOutput);
});
}
public static IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> ComposeWith(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkRight,
IObservable<System.Boolean> fOnlyIfNotGeneric)
{
return Observable.Zip(IMonikerValue, pmkRight, fOnlyIfNotGeneric,
(IMonikerValueLambda, pmkRightLambda, fOnlyIfNotGenericLambda) =>
{
System.Runtime.InteropServices.ComTypes.IMoniker ppmkCompositeOutput =
default(System.Runtime.InteropServices.ComTypes.IMoniker);
IMonikerValueLambda.ComposeWith(pmkRightLambda, fOnlyIfNotGenericLambda, out ppmkCompositeOutput);
return ppmkCompositeOutput;
});
}
public static IObservable<System.Runtime.InteropServices.ComTypes.IEnumMoniker> Enum(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Boolean> fForward)
{
return Observable.Zip(IMonikerValue, fForward, (IMonikerValueLambda, fForwardLambda) =>
{
System.Runtime.InteropServices.ComTypes.IEnumMoniker ppenumMonikerOutput =
default(System.Runtime.InteropServices.ComTypes.IEnumMoniker);
IMonikerValueLambda.Enum(fForwardLambda, out ppenumMonikerOutput);
return ppenumMonikerOutput;
});
}
public static IObservable<System.Int32> IsEqual(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkOtherMoniker)
{
return Observable.Zip(IMonikerValue, pmkOtherMoniker,
(IMonikerValueLambda, pmkOtherMonikerLambda) => IMonikerValueLambda.IsEqual(pmkOtherMonikerLambda));
}
public static IObservable<System.Int32> Hash(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue)
{
return Observable.Select(IMonikerValue, (IMonikerValueLambda) =>
{
System.Int32 pdwHashOutput = default(System.Int32);
IMonikerValueLambda.Hash(out pdwHashOutput);
return pdwHashOutput;
});
}
public static IObservable<System.Int32> IsRunning(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkToLeft,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkNewlyRunning)
{
return Observable.Zip(IMonikerValue, pbc, pmkToLeft, pmkNewlyRunning,
(IMonikerValueLambda, pbcLambda, pmkToLeftLambda, pmkNewlyRunningLambda) =>
IMonikerValueLambda.IsRunning(pbcLambda, pmkToLeftLambda, pmkNewlyRunningLambda));
}
public static IObservable<System.Runtime.InteropServices.ComTypes.FILETIME> GetTimeOfLastChange(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkToLeft)
{
return Observable.Zip(IMonikerValue, pbc, pmkToLeft, (IMonikerValueLambda, pbcLambda, pmkToLeftLambda) =>
{
System.Runtime.InteropServices.ComTypes.FILETIME pFileTimeOutput =
default(System.Runtime.InteropServices.ComTypes.FILETIME);
IMonikerValueLambda.GetTimeOfLastChange(pbcLambda, pmkToLeftLambda, out pFileTimeOutput);
return pFileTimeOutput;
});
}
public static IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> Inverse(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue)
{
return Observable.Select(IMonikerValue, (IMonikerValueLambda) =>
{
System.Runtime.InteropServices.ComTypes.IMoniker ppmkOutput =
default(System.Runtime.InteropServices.ComTypes.IMoniker);
IMonikerValueLambda.Inverse(out ppmkOutput);
return ppmkOutput;
});
}
public static IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> CommonPrefixWith(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkOther)
{
return Observable.Zip(IMonikerValue, pmkOther, (IMonikerValueLambda, pmkOtherLambda) =>
{
System.Runtime.InteropServices.ComTypes.IMoniker ppmkPrefixOutput =
default(System.Runtime.InteropServices.ComTypes.IMoniker);
IMonikerValueLambda.CommonPrefixWith(pmkOtherLambda, out ppmkPrefixOutput);
return ppmkPrefixOutput;
});
}
public static IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> RelativePathTo(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkOther)
{
return Observable.Zip(IMonikerValue, pmkOther, (IMonikerValueLambda, pmkOtherLambda) =>
{
System.Runtime.InteropServices.ComTypes.IMoniker ppmkRelPathOutput =
default(System.Runtime.InteropServices.ComTypes.IMoniker);
IMonikerValueLambda.RelativePathTo(pmkOtherLambda, out ppmkRelPathOutput);
return ppmkRelPathOutput;
});
}
public static IObservable<System.String> GetDisplayName(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkToLeft)
{
return Observable.Zip(IMonikerValue, pbc, pmkToLeft, (IMonikerValueLambda, pbcLambda, pmkToLeftLambda) =>
{
System.String ppszDisplayNameOutput = default(System.String);
IMonikerValueLambda.GetDisplayName(pbcLambda, pmkToLeftLambda, out ppszDisplayNameOutput);
return ppszDisplayNameOutput;
});
}
public static IObservable<Tuple<System.Int32, System.Runtime.InteropServices.ComTypes.IMoniker>>
ParseDisplayName(this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue,
IObservable<System.Runtime.InteropServices.ComTypes.IBindCtx> pbc,
IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> pmkToLeft,
IObservable<System.String> pszDisplayName)
{
return Observable.Zip(IMonikerValue, pbc, pmkToLeft, pszDisplayName,
(IMonikerValueLambda, pbcLambda, pmkToLeftLambda, pszDisplayNameLambda) =>
{
System.Int32 pchEatenOutput = default(System.Int32);
System.Runtime.InteropServices.ComTypes.IMoniker ppmkOutOutput =
default(System.Runtime.InteropServices.ComTypes.IMoniker);
IMonikerValueLambda.ParseDisplayName(pbcLambda, pmkToLeftLambda, pszDisplayNameLambda,
out pchEatenOutput, out ppmkOutOutput);
return Tuple.Create(pchEatenOutput, ppmkOutOutput);
});
}
public static IObservable<Tuple<System.Int32, System.Int32>> IsSystemMoniker(
this IObservable<System.Runtime.InteropServices.ComTypes.IMoniker> IMonikerValue)
{
return Observable.Select(IMonikerValue, (IMonikerValueLambda) =>
{
System.Int32 pdwMksysOutput = default(System.Int32);
var result = IMonikerValueLambda.IsSystemMoniker(out pdwMksysOutput);
return Tuple.Create(result, pdwMksysOutput);
});
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Security;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Security
{
/// <summary>
/// A base membership provider class offering much of the underlying functionality for initializing and password encryption/hashing.
/// </summary>
public abstract class MembershipProviderBase : MembershipProvider
{
/// <summary>
/// Providers can override this setting, default is 7
/// </summary>
public virtual int DefaultMinPasswordLength
{
get { return 7; }
}
/// <summary>
/// Providers can override this setting, default is 1
/// </summary>
public virtual int DefaultMinNonAlphanumericChars
{
get { return 1; }
}
/// <summary>
/// Providers can override this setting, default is false to use better security
/// </summary>
public virtual bool DefaultUseLegacyEncoding
{
get { return false; }
}
/// <summary>
/// Providers can override this setting, by default this is false which means that the provider will
/// authenticate the username + password when ChangePassword is called. This property exists purely for
/// backwards compatibility.
/// </summary>
public virtual bool AllowManuallyChangingPassword
{
get { return false; }
}
private string _applicationName;
private bool _enablePasswordReset;
private bool _enablePasswordRetrieval;
private int _maxInvalidPasswordAttempts;
private int _minRequiredNonAlphanumericCharacters;
private int _minRequiredPasswordLength;
private int _passwordAttemptWindow;
private MembershipPasswordFormat _passwordFormat;
private string _passwordStrengthRegularExpression;
private bool _requiresQuestionAndAnswer;
private bool _requiresUniqueEmail;
private string _customHashAlgorithmType ;
internal bool UseLegacyEncoding;
#region Properties
/// <summary>
/// Indicates whether the membership provider is configured to allow users to reset their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns>
public override bool EnablePasswordReset
{
get { return _enablePasswordReset; }
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to retrieve their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns>
public override bool EnablePasswordRetrieval
{
get { return _enablePasswordRetrieval; }
}
/// <summary>
/// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns>
public override int MaxInvalidPasswordAttempts
{
get { return _maxInvalidPasswordAttempts; }
}
/// <summary>
/// Gets the minimum number of special characters that must be present in a valid password.
/// </summary>
/// <value></value>
/// <returns>The minimum number of special characters that must be present in a valid password.</returns>
public override int MinRequiredNonAlphanumericCharacters
{
get { return _minRequiredNonAlphanumericCharacters; }
}
/// <summary>
/// Gets the minimum length required for a password.
/// </summary>
/// <value></value>
/// <returns>The minimum length required for a password. </returns>
public override int MinRequiredPasswordLength
{
get { return _minRequiredPasswordLength; }
}
/// <summary>
/// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns>
public override int PasswordAttemptWindow
{
get { return _passwordAttemptWindow; }
}
/// <summary>
/// Gets a value indicating the format for storing passwords in the membership data store.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns>
public override MembershipPasswordFormat PasswordFormat
{
get { return _passwordFormat; }
}
/// <summary>
/// Gets the regular expression used to evaluate a password.
/// </summary>
/// <value></value>
/// <returns>A regular expression used to evaluate a password.</returns>
public override string PasswordStrengthRegularExpression
{
get { return _passwordStrengthRegularExpression; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
/// </summary>
/// <value></value>
/// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns>
public override bool RequiresQuestionAndAnswer
{
get { return _requiresQuestionAndAnswer; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns>
public override bool RequiresUniqueEmail
{
get { return _requiresUniqueEmail; }
}
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
/// <value></value>
/// <returns>The name of the application using the custom membership provider.</returns>
public override string ApplicationName
{
get
{
return _applicationName;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ProviderException("ApplicationName cannot be empty.");
if (value.Length > 0x100)
throw new ProviderException("Provider application name too long.");
_applicationName = value;
}
}
#endregion
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call
/// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider
/// has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config)
{
// Initialize base provider class
base.Initialize(name, config);
_enablePasswordRetrieval = config.GetValue("enablePasswordRetrieval", false);
_enablePasswordReset = config.GetValue("enablePasswordReset", false);
_requiresQuestionAndAnswer = config.GetValue("requiresQuestionAndAnswer", false);
_requiresUniqueEmail = config.GetValue("requiresUniqueEmail", true);
_maxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
_passwordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
_minRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", DefaultMinPasswordLength, true, 0x80);
_minRequiredNonAlphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", DefaultMinNonAlphanumericChars, true, 0x80);
_passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
_applicationName = config["applicationName"];
if (string.IsNullOrEmpty(_applicationName))
_applicationName = GetDefaultAppName();
//by default we will continue using the legacy encoding.
UseLegacyEncoding = config.GetValue("useLegacyEncoding", DefaultUseLegacyEncoding);
// make sure password format is Hashed by default.
string str = config["passwordFormat"] ?? "Hashed";
switch (str.ToLower())
{
case "clear":
_passwordFormat = MembershipPasswordFormat.Clear;
break;
case "encrypted":
_passwordFormat = MembershipPasswordFormat.Encrypted;
break;
case "hashed":
_passwordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Provider bad password format");
}
if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval)
{
var ex = new ProviderException("Provider can not retrieve a hashed password");
LogHelper.Error<MembershipProviderBase>("Cannot specify a Hashed password format with the enabledPasswordRetrieval option set to true", ex);
throw ex;
}
_customHashAlgorithmType = config.GetValue("hashAlgorithmType", string.Empty);
}
/// <summary>
/// Override this method to ensure the password is valid before raising the event
/// </summary>
/// <param name="e"></param>
protected override void OnValidatingPassword(ValidatePasswordEventArgs e)
{
var attempt = IsPasswordValid(e.Password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength);
if (attempt.Success == false)
{
e.Cancel = true;
return;
}
base.OnValidatingPassword(e);
}
protected internal enum PasswordValidityError
{
Ok,
Length,
AlphanumericChars,
Strength
}
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">This property is ignore for this provider</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
/// <remarks>
/// Checks to ensure the AllowManuallyChangingPassword rule is adhered to
/// </remarks>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
if (oldPassword.IsNullOrWhiteSpace() && AllowManuallyChangingPassword == false)
{
//If the old password is empty and AllowManuallyChangingPassword is false, than this provider cannot just arbitrarily change the password
throw new NotSupportedException("This provider does not support manually changing the password");
}
var args = new ValidatePasswordEventArgs(username, newPassword, false);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
throw args.FailureInformation;
throw new MembershipPasswordException("Change password canceled due to password validation failure.");
}
if (AllowManuallyChangingPassword == false)
{
if (ValidateUser(username, oldPassword) == false) return false;
}
return PerformChangePassword(username, oldPassword, newPassword);
}
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">This property is ignore for this provider</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
protected abstract bool PerformChangePassword(string username, string oldPassword, string newPassword);
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
/// <remarks>
/// Performs the basic validation before passing off to PerformChangePasswordQuestionAndAnswer
/// </remarks>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
if (RequiresQuestionAndAnswer == false)
{
throw new NotSupportedException("Updating the password Question and Answer is not available if requiresQuestionAndAnswer is not set in web.config");
}
if (AllowManuallyChangingPassword == false)
{
if (ValidateUser(username, password) == false)
{
return false;
}
}
return PerformChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
protected abstract bool PerformChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer);
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
/// <remarks>
/// Ensures the ValidatingPassword event is executed before executing PerformCreateUser and performs basic membership provider validation of values.
/// </remarks>
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
var valStatus = ValidateNewUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey);
if (valStatus != MembershipCreateStatus.Success)
{
status = valStatus;
return null;
}
return PerformCreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);
}
/// <summary>
/// Performs the validation of the information for creating a new user
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="email"></param>
/// <param name="passwordQuestion"></param>
/// <param name="passwordAnswer"></param>
/// <param name="isApproved"></param>
/// <param name="providerUserKey"></param>
/// <returns></returns>
protected MembershipCreateStatus ValidateNewUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey)
{
var args = new ValidatePasswordEventArgs(username, password, true);
OnValidatingPassword(args);
if (args.Cancel)
{
return MembershipCreateStatus.InvalidPassword;
}
// Validate password
var passwordValidAttempt = IsPasswordValid(password, MinRequiredNonAlphanumericCharacters, PasswordStrengthRegularExpression, MinRequiredPasswordLength);
if (passwordValidAttempt.Success == false)
{
return MembershipCreateStatus.InvalidPassword;
}
// Validate email
if (IsEmailValid(email) == false)
{
return MembershipCreateStatus.InvalidEmail;
}
// Make sure username isn't all whitespace
if (string.IsNullOrWhiteSpace(username.Trim()))
{
return MembershipCreateStatus.InvalidUserName;
}
// Check password question
if (string.IsNullOrWhiteSpace(passwordQuestion) && RequiresQuestionAndAnswer)
{
return MembershipCreateStatus.InvalidQuestion;
}
// Check password answer
if (string.IsNullOrWhiteSpace(passwordAnswer) && RequiresQuestionAndAnswer)
{
return MembershipCreateStatus.InvalidAnswer;
}
return MembershipCreateStatus.Success;
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
protected abstract MembershipUser PerformCreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);
/// <summary>
/// Gets the members password if password retreival is enabled
/// </summary>
/// <param name="username"></param>
/// <param name="answer"></param>
/// <returns></returns>
public override string GetPassword(string username, string answer)
{
if (EnablePasswordRetrieval == false)
throw new ProviderException("Password Retrieval Not Enabled.");
if (PasswordFormat == MembershipPasswordFormat.Hashed)
throw new ProviderException("Cannot retrieve Hashed passwords.");
return PerformGetPassword(username, answer);
}
/// <summary>
/// Gets the members password if password retreival is enabled
/// </summary>
/// <param name="username"></param>
/// <param name="answer"></param>
/// <returns></returns>
protected abstract string PerformGetPassword(string username, string answer);
public override string ResetPassword(string username, string answer)
{
if (EnablePasswordReset == false)
{
throw new NotSupportedException("Password reset is not supported");
}
var newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
var args = new ValidatePasswordEventArgs(username, newPassword, true);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
{
throw args.FailureInformation;
}
throw new MembershipPasswordException("Reset password canceled due to password validation failure.");
}
return PerformResetPassword(username, answer, newPassword);
}
protected abstract string PerformResetPassword(string username, string answer, string generatedPassword);
protected internal static Attempt<PasswordValidityError> IsPasswordValid(string password, int minRequiredNonAlphanumericChars, string strengthRegex, int minLength)
{
if (minRequiredNonAlphanumericChars > 0)
{
var nonAlphaNumeric = Regex.Replace(password, "[a-zA-Z0-9]", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
if (nonAlphaNumeric.Length < minRequiredNonAlphanumericChars)
{
return Attempt.Fail(PasswordValidityError.AlphanumericChars);
}
}
if (string.IsNullOrEmpty(strengthRegex) == false)
{
if (Regex.IsMatch(password, strengthRegex, RegexOptions.Compiled) == false)
{
return Attempt.Fail(PasswordValidityError.Strength);
}
}
if (password.Length < minLength)
{
return Attempt.Fail(PasswordValidityError.Length);
}
return Attempt.Succeed(PasswordValidityError.Ok);
}
/// <summary>
/// Gets the name of the default app.
/// </summary>
/// <returns></returns>
internal static string GetDefaultAppName()
{
try
{
string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;
if (string.IsNullOrEmpty(applicationVirtualPath))
{
return "/";
}
return applicationVirtualPath;
}
catch
{
return "/";
}
}
internal static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed)
{
int num;
string s = config[valueName];
if (s == null)
{
return defaultValue;
}
if (!int.TryParse(s, out num))
{
if (zeroAllowed)
{
throw new ProviderException("Value must be non negative integer");
}
throw new ProviderException("Value must be positive integer");
}
if (zeroAllowed && (num < 0))
{
throw new ProviderException("Value must be non negativeinteger");
}
if (!zeroAllowed && (num <= 0))
{
throw new ProviderException("Value must be positive integer");
}
if ((maxValueAllowed > 0) && (num > maxValueAllowed))
{
throw new ProviderException("Value too big");
}
return num;
}
/// <summary>
/// If the password format is a hashed keyed algorithm then we will pre-pend the salt used to hash the password
/// to the hashed password itself.
/// </summary>
/// <param name="pass"></param>
/// <param name="salt"></param>
/// <returns></returns>
protected internal string FormatPasswordForStorage(string pass, string salt)
{
if (UseLegacyEncoding)
{
return pass;
}
if (PasswordFormat == MembershipPasswordFormat.Hashed)
{
//the better way, we use salt per member
return salt + pass;
}
return pass;
}
internal static bool IsEmailValid(string email)
{
const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
return Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
protected internal string EncryptOrHashPassword(string pass, string salt)
{
//if we are doing it the old way
if (UseLegacyEncoding)
{
return LegacyEncodePassword(pass);
}
//This is the correct way to implement this (as per the sql membership provider)
if (PasswordFormat == MembershipPasswordFormat.Clear)
return pass;
var bytes = Encoding.Unicode.GetBytes(pass);
var numArray1 = Convert.FromBase64String(salt);
byte[] inArray;
if (PasswordFormat == MembershipPasswordFormat.Hashed)
{
var hashAlgorithm = GetHashAlgorithm(pass);
var algorithm = hashAlgorithm as KeyedHashAlgorithm;
if (algorithm != null)
{
var keyedHashAlgorithm = algorithm;
if (keyedHashAlgorithm.Key.Length == numArray1.Length)
keyedHashAlgorithm.Key = numArray1;
else if (keyedHashAlgorithm.Key.Length < numArray1.Length)
{
var numArray2 = new byte[keyedHashAlgorithm.Key.Length];
Buffer.BlockCopy(numArray1, 0, numArray2, 0, numArray2.Length);
keyedHashAlgorithm.Key = numArray2;
}
else
{
var numArray2 = new byte[keyedHashAlgorithm.Key.Length];
var dstOffset = 0;
while (dstOffset < numArray2.Length)
{
var count = Math.Min(numArray1.Length, numArray2.Length - dstOffset);
Buffer.BlockCopy(numArray1, 0, numArray2, dstOffset, count);
dstOffset += count;
}
keyedHashAlgorithm.Key = numArray2;
}
inArray = keyedHashAlgorithm.ComputeHash(bytes);
}
else
{
var buffer = new byte[numArray1.Length + bytes.Length];
Buffer.BlockCopy(numArray1, 0, buffer, 0, numArray1.Length);
Buffer.BlockCopy(bytes, 0, buffer, numArray1.Length, bytes.Length);
inArray = hashAlgorithm.ComputeHash(buffer);
}
}
else
{
//this code is copied from the sql membership provider - pretty sure this could be nicely re-written to completely
// ignore the salt stuff since we are not salting the password when encrypting.
var password = new byte[numArray1.Length + bytes.Length];
Buffer.BlockCopy(numArray1, 0, password, 0, numArray1.Length);
Buffer.BlockCopy(bytes, 0, password, numArray1.Length, bytes.Length);
inArray = EncryptPassword(password, MembershipPasswordCompatibilityMode.Framework40);
}
return Convert.ToBase64String(inArray);
}
/// <summary>
/// Checks the password.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="dbPassword">The dbPassword.</param>
/// <returns></returns>
protected internal bool CheckPassword(string password, string dbPassword)
{
switch (PasswordFormat)
{
case MembershipPasswordFormat.Encrypted:
var decrypted = DecryptPassword(dbPassword);
return decrypted == password;
case MembershipPasswordFormat.Hashed:
string salt;
var storedHashedPass = StoredPassword(dbPassword, out salt);
var hashed = EncryptOrHashPassword(password, salt);
return storedHashedPass == hashed;
case MembershipPasswordFormat.Clear:
return password == dbPassword;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Encrypt/hash a new password with a new salt
/// </summary>
/// <param name="newPassword"></param>
/// <param name="salt"></param>
/// <returns></returns>
protected internal string EncryptOrHashNewPassword(string newPassword, out string salt)
{
salt = GenerateSalt();
return EncryptOrHashPassword(newPassword, salt);
}
protected internal string DecryptPassword(string pass)
{
//if we are doing it the old way
if (UseLegacyEncoding)
{
return LegacyUnEncodePassword(pass);
}
//This is the correct way to implement this (as per the sql membership provider)
switch ((int)PasswordFormat)
{
case 0:
return pass;
case 1:
throw new ProviderException("Provider can not decrypt hashed password");
default:
var bytes = DecryptPassword(Convert.FromBase64String(pass));
return bytes == null ? null : Encoding.Unicode.GetString(bytes, 16, bytes.Length - 16);
}
}
/// <summary>
/// Returns the hashed password without the salt if it is hashed
/// </summary>
/// <param name="storedString"></param>
/// <param name="salt">returns the salt</param>
/// <returns></returns>
internal string StoredPassword(string storedString, out string salt)
{
if (UseLegacyEncoding)
{
salt = string.Empty;
return storedString;
}
switch (PasswordFormat)
{
case MembershipPasswordFormat.Hashed:
var saltLen = GenerateSalt();
salt = storedString.Substring(0, saltLen.Length);
return storedString.Substring(saltLen.Length);
case MembershipPasswordFormat.Clear:
case MembershipPasswordFormat.Encrypted:
default:
salt = string.Empty;
return storedString;
}
}
protected internal static string GenerateSalt()
{
var numArray = new byte[16];
new RNGCryptoServiceProvider().GetBytes(numArray);
return Convert.ToBase64String(numArray);
}
protected internal HashAlgorithm GetHashAlgorithm(string password)
{
if (UseLegacyEncoding)
{
//before we were never checking for an algorithm type so we were always using HMACSHA1
// for any SHA specified algorithm :( so we'll need to keep doing that for backwards compat support.
if (Membership.HashAlgorithmType.InvariantContains("SHA"))
{
return new HMACSHA1
{
//the legacy salt was actually the password :(
Key = Encoding.Unicode.GetBytes(password)
};
}
}
//get the algorithm by name
if (_customHashAlgorithmType.IsNullOrWhiteSpace())
{
_customHashAlgorithmType = Membership.HashAlgorithmType;
}
var alg = HashAlgorithm.Create(_customHashAlgorithmType);
if (alg == null)
{
throw new InvalidOperationException("The hash algorithm specified " + Membership.HashAlgorithmType + " cannot be resolved");
}
return alg;
}
/// <summary>
/// Encodes the password.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The encoded password.</returns>
protected string LegacyEncodePassword(string password)
{
string encodedPassword = password;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
var hashAlgorith = GetHashAlgorithm(password);
encodedPassword = Convert.ToBase64String(hashAlgorith.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
default:
throw new ProviderException("Unsupported password format.");
}
return encodedPassword;
}
/// <summary>
/// Unencode password.
/// </summary>
/// <param name="encodedPassword">The encoded password.</param>
/// <returns>The unencoded password.</returns>
protected string LegacyUnEncodePassword(string encodedPassword)
{
string password = encodedPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
break;
case MembershipPasswordFormat.Hashed:
throw new ProviderException("Cannot unencode a hashed password.");
default:
throw new ProviderException("Unsupported password format.");
}
return password;
}
public override string ToString()
{
var result = base.ToString();
var sb = new StringBuilder(result);
sb.AppendLine("Name =" + Name);
sb.AppendLine("_applicationName =" + _applicationName);
sb.AppendLine("_enablePasswordReset=" + _enablePasswordReset);
sb.AppendLine("_enablePasswordRetrieval=" + _enablePasswordRetrieval);
sb.AppendLine("_maxInvalidPasswordAttempts=" + _maxInvalidPasswordAttempts);
sb.AppendLine("_minRequiredNonAlphanumericCharacters=" + _minRequiredNonAlphanumericCharacters);
sb.AppendLine("_minRequiredPasswordLength=" + _minRequiredPasswordLength);
sb.AppendLine("_passwordAttemptWindow=" + _passwordAttemptWindow);
sb.AppendLine("_passwordFormat=" + _passwordFormat);
sb.AppendLine("_passwordStrengthRegularExpression=" + _passwordStrengthRegularExpression);
sb.AppendLine("_requiresQuestionAndAnswer=" + _requiresQuestionAndAnswer);
sb.AppendLine("_requiresUniqueEmail=" + _requiresUniqueEmail);
return sb.ToString();
}
}
}
| |
using GameTimer;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using ResolutionBuddy;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace MenuBuddy
{
/// <summary>
/// The loading screen coordinates transitions between the menu system and the
/// game itself. Normally one screen will transition off at the same time as
/// the next screen is transitioning on, but for larger transitions that can
/// take a longer time to load their data, we want the menu system to be entirely
/// gone before we start loading the game. This is done as follows:
///
/// - Tell all the existing screens to transition off.
/// - Activate a loading screen, which will transition on at the same time.
/// - The loading screen watches the state of the previous screens.
/// - When it sees they have finished transitioning off, it activates the real
/// next screen, which may take a long time to load its data. The loading
/// screen will be the only thing displayed while this load is taking place.
/// </summary>
public class LoadingScreen : WidgetScreen
{
#region Properties
private IScreen[] ScreensToLoad { get; set; }
BackgroundWorker _backgroundThread;
private string LoadSoundEffect { get; set; }
public string Font { get; set; }
#if DESKTOP
CountdownTimer timer = new CountdownTimer();
#endif
#endregion //Properties
#region Methods
/// <summary>
/// The constructor is private: loading screens should be activated via the static Load method instead.
/// </summary>
private LoadingScreen(string loadSoundEffect, IScreen[] screensToLoad)
: base("Loading")
{
ScreensToLoad = screensToLoad;
LoadSoundEffect = loadSoundEffect;
CoveredByOtherScreens = false;
CoverOtherScreens = true;
Transition.OnTime = 0.5f;
}
/// <summary>
/// Activates the loading screen.
/// </summary>
/// <param name="screenManager">The screenmanager.</param>
/// <param name="loadingIsSlow">If true, the loading screen will be displayed, otherwise will just pop up screensToLoad</param>
/// <param name="controllingPlayer">The player that loaded the screen. Just pass null!!!</param>
/// <param name="loadSoundEffect">Play the transition sound here instead of in the screen that initiated the load.</param>
/// <param name="screensToLoad">Params list of all the screens we want to load.</param>
public static Task Load(ScreenManager screenManager,
params IScreen[] screensToLoad)
{
// Create and activate the loading screen.
var loadingScreen = new LoadingScreen(null, screensToLoad);
return screenManager.AddScreen(loadingScreen, null);
}
public static Task Load(ScreenManager screenManager,
int controllingPlayer,
string loadSoundEffect,
params IScreen[] screensToLoad)
{
// Create and activate the loading screen.
var loadingScreen = new LoadingScreen(loadSoundEffect, screensToLoad);
return screenManager.AddScreen(loadingScreen, controllingPlayer);
}
public static Task Load(ScreenManager screenManager,
string loadSoundEffect,
params IScreen[] screensToLoad)
{
// Create and activate the loading screen.
var loadingScreen = new LoadingScreen(loadSoundEffect, screensToLoad);
return screenManager.AddScreen(loadingScreen, null);
}
public static Task Load(ScreenManager screenManager,
string loadSoundEffect,
string fontResource,
params IScreen[] screensToLoad)
{
// Create and activate the loading screen.
var loadingScreen = new LoadingScreen(loadSoundEffect, screensToLoad)
{
Font = fontResource,
};
return screenManager.AddScreen(loadingScreen, null);
}
public override async Task LoadContent()
{
await base.LoadContent();
var layout = new RelativeLayout
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center,
Position = Resolution.TitleSafeArea.Center,
};
//create the message widget
var width = 0f;
var msg = new Label("Loading...", Content, FontSize.Medium, Font)
{
Highlightable = false,
Horizontal = HorizontalAlignment.Right,
Vertical = VerticalAlignment.Center,
};
width += msg.Rect.Width;
Texture2D hourglassTex = null;
try
{
hourglassTex = Content.Load<Texture2D>(StyleSheet.LoadingScreenHourglassImageResource);
}
catch (Exception)
{
//No hourglass texture :P
}
if (null != hourglassTex)
{
//create the hourglass widget
var hourglass = new Image(hourglassTex)
{
Horizontal = HorizontalAlignment.Left,
Vertical = VerticalAlignment.Center,
Scale = 1.5f,
Highlightable = false,
};
layout.AddItem(hourglass);
width += hourglass.Rect.Width;
//add a little shim in between the widgets
width += 32f;
}
layout.AddItem(msg);
layout.Size = new Vector2(width, 64f);
AddItem(layout);
//play the "loading" sound effect
if (!string.IsNullOrEmpty(LoadSoundEffect))
{
var sound = Content.Load<SoundEffect>(LoadSoundEffect);
sound.Play();
}
#if DESKTOP
timer.Start(1f);
#else
// Start up the background thread, which will update the network session and draw the animation while we are loading.
_backgroundThread = new BackgroundWorker();
_backgroundThread.WorkerSupportsCancellation = true;
_backgroundThread.DoWork += new DoWorkEventHandler(BackgroundWorkerThread);
_backgroundThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CleanUp);
_backgroundThread.RunWorkerAsync();
#endif
}
#if DESKTOP
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
timer.Update(gameTime);
//If this is Desktop and a second has elapsed, load all the screen content
if (IsActive && !timer.HasTimeRemaining)
{
BackgroundWorkerThread(this, new DoWorkEventArgs(null));
CleanUp(this, new RunWorkerCompletedEventArgs(null, null, false));
}
}
#endif
/// <summary>
/// Draws the loading screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
// The gameplay screen takes a while to load, so we display a loading
// message while that is going on, but the menus load very quickly, and
// it would look silly if we flashed this up for just a fraction of a
// second while returning from the game to the menus. This parameter
// tells us how long the loading is going to take, so we know whether
// to bother drawing the message.
ScreenManager.SpriteBatchBegin();
FadeBackground();
ScreenManager.SpriteBatchEnd();
base.Draw(gameTime);
}
#endregion //Update and Draw
#region Background Thread
/// <summary>
/// Worker thread draws the loading animation and updates the network
/// session while the load is taking place.
/// </summary>
void BackgroundWorkerThread(object sender, DoWorkEventArgs e)
{
ScreenManager.AddScreen(ScreensToLoad, ControllingPlayer).Wait();
}
void CleanUp(object sender, RunWorkerCompletedEventArgs e)
{
//clean up all the memory from those other screens
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
ExitScreen();
// Once the load has finished, we use ResetElapsedTime to tell
// the game timing mechanism that we have just finished a very
// long frame, and that it should not try to catch up.
ScreenManager.Game.ResetElapsedTime();
}
#endregion //Background Thread
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-2015 Charlie Poole, Rob Prouse
//
// 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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class ValueSourceTests : ValueSourceMayBeInherited
{
[Test]
public void ValueSourceCanBeStaticProperty(
[ValueSource(nameof(StaticProperty))] string source)
{
Assert.AreEqual("StaticProperty", source);
}
static IEnumerable StaticProperty
{
get
{
yield return "StaticProperty";
}
}
[Test]
public void ValueSourceCanBeInheritedStaticProperty(
[ValueSource(nameof(InheritedStaticProperty))] bool source)
{
Assert.AreEqual(true, source);
}
[Test]
public void ValueSourceMayNotBeInstanceProperty()
{
var result = TestBuilder.RunParameterizedMethodSuite(GetType(), "MethodWithValueSourceInstanceProperty");
Assert.That(result.Children.ToArray()[0].ResultState, Is.EqualTo(ResultState.NotRunnable));
}
public void MethodWithValueSourceInstanceProperty(
[ValueSource(nameof(InstanceProperty))] string source)
{
Assert.AreEqual("InstanceProperty", source);
}
IEnumerable InstanceProperty
{
get { return new object[] { "InstanceProperty" }; }
}
[Test]
public void ValueSourceCanBeStaticMethod(
[ValueSource(nameof(StaticMethod))] string source)
{
Assert.AreEqual("StaticMethod", source);
}
static IEnumerable StaticMethod()
{
return new object[] { "StaticMethod" };
}
[Test]
public void ValueSourceMayNotBeInstanceMethod()
{
var result = TestBuilder.RunParameterizedMethodSuite(GetType(), "MethodWithValueSourceInstanceMethod");
Assert.That(result.Children.ToArray()[0].ResultState, Is.EqualTo(ResultState.NotRunnable));
}
public void MethodWithValueSourceInstanceMethod(
[ValueSource(nameof(InstanceMethod))] string source)
{
Assert.AreEqual("InstanceMethod", source);
}
IEnumerable InstanceMethod()
{
return new object[] { "InstanceMethod" };
}
[Test]
public void ValueSourceCanBeStaticField(
[ValueSource(nameof(StaticField))] string source)
{
Assert.AreEqual("StaticField", source);
}
internal static object[] StaticField = { "StaticField" };
[Test]
public void ValueSourceMayNotBeInstanceField()
{
var result = TestBuilder.RunParameterizedMethodSuite(GetType(), "MethodWithValueSourceInstanceField");
Assert.That(result.Children.ToArray ()[0].ResultState, Is.EqualTo(ResultState.NotRunnable));
}
public void MethodWithValueSourceInstanceField(
[ValueSource(nameof(InstanceField))] string source)
{
Assert.AreEqual("InstanceField", source);
}
internal object[] InstanceField = { "InstanceField" };
[Test, Sequential]
public void MultipleArguments(
[ValueSource(nameof(Numerators))] int n,
[ValueSource(nameof(Denominators))] int d,
[ValueSource(nameof(Quotients))] int q)
{
Assert.AreEqual(q, n / d);
}
internal static int[] Numerators = new int[] { 12, 12, 12 };
internal static int[] Denominators = new int[] { 3, 4, 6 };
internal static int[] Quotients = new int[] { 4, 3, 2 };
[Test, Sequential]
public void ValueSourceMayBeInAnotherClass(
[ValueSource(typeof(DivideDataProvider), nameof(DivideDataProvider.Numerators))] int n,
[ValueSource(typeof(DivideDataProvider), nameof(DivideDataProvider.Denominators))] int d,
[ValueSource(typeof(DivideDataProvider), nameof(DivideDataProvider.Quotients))] int q)
{
Assert.AreEqual(q, n / d);
}
private class DivideDataProvider
{
internal static int[] Numerators = new int[] { 12, 12, 12 };
internal static int[] Denominators = new int[] { 3, 4, 6 };
internal static int[] Quotients = new int[] { 4, 3, 2 };
}
[Test]
public void ValueSourceMayBeGeneric(
[ValueSourceAttribute(typeof(ValueProvider), nameof(ValueProvider.IntegerProvider))] int val)
{
Assert.That(2 * val, Is.EqualTo(val + val));
}
public class ValueProvider
{
public static IEnumerable<int> IntegerProvider()
{
List<int> dataList = new List<int>();
dataList.Add(1);
dataList.Add(2);
dataList.Add(4);
dataList.Add(8);
return dataList;
}
public static IEnumerable<int> ForeignNullResultProvider()
{
return null;
}
}
public static string NullSource = null;
public static IEnumerable<int> NullDataSourceProvider()
{
return null;
}
public static IEnumerable<int> NullDataSourceProperty
{
get { return null; }
}
[Test, Explicit("Null or nonexistent data sources definitions should not prevent other tests from run #1121")]
public void ValueSourceMayNotBeNull(
[ValueSource(nameof(NullSource))] string nullSource,
[ValueSource(nameof(NullDataSourceProvider))] string nullDataSourceProvided,
[ValueSource(typeof(ValueProvider), nameof(ValueProvider.ForeignNullResultProvider))] string nullDataSourceProvider,
[ValueSource(nameof(NullDataSourceProperty))] int nullDataSourceProperty,
[ValueSource("SomeNonExistingMemberSource")] int nonExistingMember)
{
Assert.Fail();
}
[Test]
public void ValueSourceAttributeShouldThrowInsteadOfReturningNull()
{
var method = GetType().GetMethod("ValueSourceMayNotBeNull");
var parameters = method.GetParameters();
foreach (var parameter in parameters)
{
var dataSource = parameter.GetAttributes<IParameterDataSource>(false)[0];
Assert.Throws<InvalidDataSourceException>(() => dataSource.GetData(GetType(), parameter));
}
}
[Test]
public void MethodWithArrayArguments([ValueSource(nameof(ComplexArrayBasedTestInput))] object o)
{
}
static object[] ComplexArrayBasedTestInput = new[]
{
new object[] { 1, "text", new object() },
new object[0],
new object[] { 1, new int[] { 2, 3 }, 4 },
new object[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
new object[] { new byte[,] { { 1, 2 }, { 2, 3 } } }
};
[Test]
public void TestNameIntrospectsArrayValues()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
GetType(), nameof(MethodWithArrayArguments));
Assert.That(suite.TestCaseCount, Is.EqualTo(5));
Assert.Multiple(() =>
{
Assert.That(suite.Tests[0].Name, Is.EqualTo(@"MethodWithArrayArguments([1, ""text"", System.Object])"));
Assert.That(suite.Tests[1].Name, Is.EqualTo(@"MethodWithArrayArguments([])"));
Assert.That(suite.Tests[2].Name, Is.EqualTo(@"MethodWithArrayArguments([1, Int32[], 4])"));
Assert.That(suite.Tests[3].Name, Is.EqualTo(@"MethodWithArrayArguments([1, 2, 3, 4, 5, ...])"));
Assert.That(suite.Tests[4].Name, Is.EqualTo(@"MethodWithArrayArguments([System.Byte[,]])"));
});
}
}
public class ValueSourceMayBeInherited
{
protected static IEnumerable<bool> InheritedStaticProperty
{
get { yield return true; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xrm.Sdk;
#if DLAB_UNROOT_NAMESPACE || DLAB_XRM
namespace DLaB.Xrm
#else
namespace Source.DLaB.Xrm
#endif
{
public static partial class Extensions
{
#region Entity
#region AddAliased
/// <summary>
/// Adds the aliased entity to the current entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="entityToAdd">The entity to add.</param>
public static void AddAliasedEntity(this Entity entity, Entity entityToAdd)
{
foreach (var attribute in entityToAdd.Attributes.Where(a => !(a.Value is AliasedValue)))
{
var formattedValue = entityToAdd.FormattedValues.TryGetValue(attribute.Key, out var formatted) ? formatted : null;
entity.AddAliasedValue(entityToAdd.LogicalName, attribute.Key, attribute.Value, formattedValue);
}
}
/// <summary>
/// Adds the value to the entity as an Aliased Value. Helpful when you need to add attributes
/// that are for other entities locally, in such a way that it looks like it was added by a link on a query
/// expression
/// </summary>
/// <param name="entity"></param>
/// <param name="logicalName">The logical name from which the aliased value would have come from</param>
/// <param name="attributeName">The logical name of the attribute of the aliased value</param>
/// <param name="value">The Value to store in the aliased value</param>
/// <param name="formattedValue">The formatted value</param>
public static void AddAliasedValue(this Entity entity, string logicalName, string attributeName, object value, string formattedValue = null)
{
entity.AddAliasedValue(null, logicalName, attributeName, value, formattedValue);
}
/// <summary>
/// Adds the value to the entity as an Aliased Value. Helpful when you need to add attributes
/// that are for other entities locally, in such a way that it looks like it was added by a link on a query
/// expression
/// </summary>
/// <param name="entity"></param>
/// <param name="aliasName">Aliased Name of the Attribute</param>
/// <param name="logicalName">The logical name from which the aliased value would have come from</param>
/// <param name="attributeName">The logical name of the attribute of the aliased value</param>
/// <param name="value">The Value to store in the aliased value</param>
/// <param name="formattedValue">The formatted value</param>
public static void AddAliasedValue(this Entity entity, string aliasName, string logicalName, string attributeName, object value, string formattedValue = null)
{
aliasName = aliasName ?? logicalName;
var name = aliasName + "." + attributeName;
entity.Attributes.Add(name, new AliasedValue(logicalName, attributeName, value));
if (formattedValue != null)
{
entity.FormattedValues.Add(name, formattedValue);
}
}
/// <summary>
/// Adds the value to the entity as an Aliased Value, or replaces an already existing value. Helpful when you need to add attributes
/// that are for other entities locally, in such a way that it looks like it was added by a link on a query
/// expression
/// </summary>
/// <param name="entity"></param>
/// <param name="logicalName">The logical name from which the aliased value would have come from</param>
/// <param name="attributeName">The logical name of the attribute of the aliased value</param>
/// <param name="value">The Value to store in the aliased value</param>
/// <param name="formattedValue">The formatted value</param>
public static void AddOrReplaceAliasedValue(this Entity entity, string logicalName, string attributeName, object value, string formattedValue = null)
{
// Check for value already existing
foreach (var attribute in entity.Attributes.Where(a => a.Value is AliasedValue))
{
var aliasedValue = ((AliasedValue)attribute.Value);
if (aliasedValue.EntityLogicalName != logicalName || aliasedValue.AttributeLogicalName != attributeName) { continue; }
entity[attribute.Key] = new AliasedValue(aliasedValue.EntityLogicalName, aliasedValue.AttributeLogicalName, value);
if (formattedValue != null)
{
entity.FormattedValues[attribute.Key] = formattedValue;
}
return;
}
entity.AddAliasedValue(logicalName, attributeName, value, formattedValue);
}
#endregion AddAliased
#region GetAliasedEntity
/// <summary>
/// Gets the aliased entity from the current entity.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public static T GetAliasedEntity<T>(this Entity entity) where T : Entity, new()
{
return entity.GetAliasedEntity<T>(null);
}
/// <summary>
/// Gets the aliased entity from the current entity with the given entity name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity">The entity.</param>
/// <param name="aliasedEntityName">Name of the aliased entity.</param>
/// <returns></returns>
public static T GetAliasedEntity<T>(this Entity entity, string aliasedEntityName) where T : Entity, new()
{
var entityLogicalName = EntityHelper.GetEntityLogicalName<T>();
var aliasedEntity = new T();
var idAttribute = GetIdAttributeName(aliasedEntity);
foreach (var entry in entity.Attributes)
{
if (entry.Value is AliasedValue aliased && aliased.EntityLogicalName == entityLogicalName &&
(
(aliasedEntityName == null && // No Entity Attribute Name Specified
(entry.Key.Contains(".") || entry.Key == aliased.AttributeLogicalName || aliased.AttributeLogicalName == idAttribute))
// And the key contains a "." or is an exact match on the aliased attribute logical name. This keeps groupings that may not be the same type (Date Group by Day) from populating the aliased entity
// The one exception for this is the Id. which we want to include if we can
||
(aliasedEntityName != null && // Or an Entity Attribute Name is specified, and
entry.Key.StartsWith(aliasedEntityName + ".")) // it starts with the aliasedEntityName + ".
))
{
aliasedEntity[aliased.AttributeLogicalName] = aliased.Value;
if (entity.FormattedValues.TryGetValue(entry.Key, out string formattedValue))
{
aliasedEntity.FormattedValues[aliased.AttributeLogicalName] = formattedValue;
}
}
}
// Remove names for Entity References.
foreach (var entry in aliasedEntity.Attributes.Where(a => a.Key.EndsWith("name")).ToList())
{
var nonNameAttribute = entry.Key.Substring(0, entry.Key.Length - "name".Length);
if (aliasedEntity.Contains(nonNameAttribute))
{
if (aliasedEntity[nonNameAttribute] is EntityReference entityRef && entityRef.Name == (string)entry.Value)
{
aliasedEntity.Attributes.Remove(entry.Key);
}
}
}
if (aliasedEntity.Attributes.Contains(idAttribute))
{
aliasedEntity.Id = (Guid)aliasedEntity[idAttribute];
}
return aliasedEntity;
}
#endregion GetAliasedEntity
#region GetAliasedValue
/// <summary>
/// Returns the Aliased Value for a column specified in a Linked entity, returning the default value for
/// the type if it wasn't found
/// </summary>
/// <typeparam name="T">The type of the aliased attribute form the linked entity</typeparam>
/// <param name="entity"></param>
/// <param name="attributeName">The aliased attribute from the linked entity. Can be prepended with the
/// linked entities logical name and a period. ie "Contact.LastName"</param>
/// <returns></returns>
public static T GetAliasedValue<T>(this Entity entity, string attributeName)
{
var aliasedEntityName = SplitAliasedAttributeEntityName(ref attributeName);
var value = (from entry in entity.Attributes
where entry.IsSpecifiedAliasedValue(aliasedEntityName, attributeName)
select entry.Value).FirstOrDefault();
if (value == null)
{
return default(T);
}
if (!(value is AliasedValue aliased))
{
throw new InvalidCastException($"Attribute {attributeName} was of type {value.GetType().FullName}, not AliasedValue");
}
try
{
// If the primary key of an entity is returned, it is returned as a Guid. If it is a FK, it is returned as an Entity Reference
// Handle that here
if (typeof(T) == typeof(EntityReference) && aliased.Value is Guid guid)
{
return (T)(object)new EntityReference(aliased.EntityLogicalName, guid);
}
if (typeof(T) == typeof(Guid) && aliased.Value is EntityReference reference)
{
return (T)(object)reference.Id;
}
return (T)aliased.Value;
}
catch (InvalidCastException)
{
throw new InvalidCastException($"Unable to cast attribute {aliased.EntityLogicalName}.{aliased.AttributeLogicalName} from type {aliased.Value.GetType().Name} to type {typeof(T).Name}");
}
}
#endregion GetAliasedValue
#region HasAliasedAttribute
/// <summary>
/// Returns the Aliased Value for a column specified in a Linked entity
/// </summary>
/// <param name="entity"></param>
/// <param name="attributeName">The aliased attribute from the linked entity. Can be prepended with the
/// linked entities logical name and a period. ie "Contact.LastName"</param>
/// <returns></returns>
public static bool HasAliasedAttribute(this Entity entity, string attributeName)
{
var aliasedEntityName = SplitAliasedAttributeEntityName(ref attributeName);
return entity.Attributes.Any(e =>
e.IsSpecifiedAliasedValue(aliasedEntityName, attributeName));
}
#endregion HasAliasedAttribute
#region Helpers
private static bool IsSpecifiedAliasedValue(this KeyValuePair<string, object> entry, string aliasedEntityName, string attributeName)
{
if (!(entry.Value is AliasedValue aliased))
{
return false;
}
// There are two ways to define an Aliased name that need to be handled
// 1. At the Entity level in Query Expression or Fetch Xml. This makes the key in the format AliasedEntityName.AttributeName
// 2. At the attribute level in FetchXml Group. This makes the key the Attribute Name. The aliased Entity Name should always be null in this case
var value = false;
if (aliasedEntityName == null)
{
// No aliased entity name specified. If attribute name matches, assume it's correct, or,
// if the key is the attribute name. This covers the 2nd possibility above
value = aliased.AttributeLogicalName == attributeName || entry.Key == attributeName;
}
else if (aliased.AttributeLogicalName == attributeName)
{
// The Aliased Entity Name has been defined. Check to see if the attribute name join is valid
value = entry.Key == aliasedEntityName + "." + attributeName;
}
return value;
}
/// <summary>
/// Handles splitting the attributeName if it is formatted as "EntityAliasedName.AttributeName",
/// updating the attribute name and returning the aliased EntityName
/// </summary>
/// <param name="attributeName"></param>
private static string SplitAliasedAttributeEntityName(ref string attributeName)
{
string aliasedEntityName = null;
if (attributeName.Contains('.'))
{
var split = attributeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length != 2)
{
throw new Exception("Attribute Name was specified for an Aliased Value with " + split.Length +
" split parts, and two were expected. Attribute Name = " + attributeName);
}
aliasedEntityName = split[0];
attributeName = split[1];
}
return aliasedEntityName;
}
#endregion Helpers
#endregion Entity
}
}
| |
// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli
using System;
using System.Linq;
using System.Threading.Tasks;
using PocketCampus.Common;
using PocketCampus.Common.Services;
using PocketCampus.Map.Models;
using PocketCampus.Map.Services;
using ThinMvvm;
using ThinMvvm.Logging;
namespace PocketCampus.Map.ViewModels
{
[LogId( "/map" )]
public sealed class MainViewModel : DataViewModel<MapSearchRequest>, IDisposable
{
// If the user toggled centering the map on their position, moving this far will toggle it off (in meters)
private const double StopCenterOnUserThreshold = 5.0;
// The zoom level used when centering the map on the campus.
private const int CampusZoomLevel = 16;
// The coordinates of the campus center.
private static readonly GeoPosition CampusPosition = new GeoPosition( 46.520533, 6.565012 );
private readonly IMapService _mapService;
private readonly ILocationService _locationService;
private readonly INavigationService _navigationService;
private readonly IPluginSettings _settings;
private string _query;
private SearchStatus _searchStatus;
private MapItem[] _searchResults;
private GeoLocationStatus _locationStatus;
private bool _isCenteredOnUser;
public MapProperties Properties { get; private set; }
public string Query
{
get { return _query; }
set { SetProperty( ref _query, value ); }
}
public SearchStatus SearchStatus
{
get { return _searchStatus; }
private set { SetProperty( ref _searchStatus, value ); }
}
public MapItem[] SearchResults
{
get { return _searchResults; }
private set { SetProperty( ref _searchResults, value ); }
}
public GeoLocationStatus LocationStatus
{
get { return _locationStatus; }
private set { SetProperty( ref _locationStatus, value ); }
}
public bool IsCenteredOnUser
{
get { return _isCenteredOnUser; }
set { SetProperty( ref _isCenteredOnUser, value ); }
}
[LogId( "CenterOnCampus" )]
public Command CenterOnCampusCommand
{
get { return this.GetCommand( CenterOnCampus ); }
}
[LogId( "OpenSettings" )]
public Command ViewSettingsCommand
{
get { return this.GetCommand( _navigationService.NavigateTo<SettingsViewModel> ); }
}
[LogId( "Search" )]
[LogParameter( "Query" )]
public AsyncCommand SearchCommand
{
get { return this.GetAsyncCommand( () => SearchAsync( Query ) ); }
}
public MainViewModel( ILocationService locationService, INavigationService navigationService,
IMapService mapService, IPluginSettings settings,
MapSearchRequest request )
{
_mapService = mapService;
_locationService = locationService;
_navigationService = navigationService;
_settings = settings;
_locationService.Ready += LocationService_Ready;
_locationService.LocationChanged += LocationService_LocationChanged;
_locationService.Error += LocationService_Error;
Properties = new MapProperties();
ExecuteRequest( request );
this.ListenToProperty( x => x.IsCenteredOnUser, IsCenterdOnUserChanged );
Properties.ListenToProperty( x => x.Center, OnCenterChanged );
}
public override Task OnNavigatedToAsync()
{
// HACK: No call to base, we don't want the "try to refresh on the first navigation" behavior here
// Inheriting from DataViewModel is weird anyway...
if ( Properties.Center == null )
{
CenterOnCampus();
}
_locationService.IsEnabled = _settings.UseGeolocation;
if ( !_settings.UseGeolocation )
{
Properties.UserPosition = null;
LocationStatus = GeoLocationStatus.NotRequested;
}
return Task.FromResult( 0 );
}
private async void ExecuteRequest( MapSearchRequest request )
{
if ( request.Query != null )
{
Query = request.Query;
await SearchAsync( request.Query );
}
else if ( request.Item != null )
{
SearchResults = new[] { request.Item };
}
}
private Task SearchAsync( string query )
{
return TryExecuteAsync( async token =>
{
var results = await _mapService.SearchAsync( query, token );
var uniqueResult = results.FirstOrDefault( r => NameNormalizer.AreRoomNamesEqual( r.Name, query ) );
if ( !token.IsCancellationRequested )
{
SearchStatus = results.Length == 0 ? SearchStatus.NoResults : SearchStatus.Finished;
SearchResults = uniqueResult == null ? results : new[] { uniqueResult };
}
} );
}
private void CenterOnCampus()
{
IsCenteredOnUser = false;
Properties.ZoomLevel = CampusZoomLevel;
Properties.Center = CampusPosition;
}
private void IsCenterdOnUserChanged()
{
Messenger.Send( new EventLogRequest( "ToggleCenterOnUser", IsCenteredOnUser.ToString() ) );
if ( IsCenteredOnUser )
{
Properties.UserPosition = _locationService.LastKnownLocation;
Properties.Center = Properties.UserPosition;
}
}
private void OnCenterChanged()
{
if ( Properties.Center == null || Properties.UserPosition == null )
{
// when loading the map, or if geolocation is disabled
return;
}
if ( Properties.Center.DistanceTo( Properties.UserPosition ) >= StopCenterOnUserThreshold )
{
IsCenteredOnUser = false;
}
}
private void LocationService_Ready( object sender, EventArgs e )
{
LocationStatus = GeoLocationStatus.Success;
}
private void LocationService_LocationChanged( object sender, LocationChangedEventArgs e )
{
Properties.UserPosition = e.Location;
if ( IsCenteredOnUser )
{
Properties.Center = Properties.UserPosition;
}
}
private void LocationService_Error( object sender, EventArgs e )
{
Properties.UserPosition = null;
LocationStatus = GeoLocationStatus.Error;
}
// Avoid memory leaks
public new void Dispose()
{
base.Dispose();
_locationService.Ready -= LocationService_Ready;
_locationService.LocationChanged -= LocationService_LocationChanged;
_locationService.Error -= LocationService_Error;
}
}
}
| |
#define THREADING
using Saga.Enumarations;
using Saga.Map.Definitions.Misc;
using Saga.Map.Utils.Definitions.Misc;
using Saga.Map.Utils.Structures;
using Saga.Packets;
using Saga.PrimaryTypes;
using Saga.Quests;
using Saga.Structures;
using Saga.Tasks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
namespace Saga.Map.Client
{
partial class Client
{
/// <summary>
/// Notifies the client to load start sending all pre-cached and yet to be
/// processed packets.
///
/// See the above method
/// </summary>
/// <remarks>
/// Due the nature of this method we'll be invoking a notification on
/// our "assumed" to be pending LoadMap method. We'll process all Moveable
/// objects in the sightrange here.
///
/// We cannot do this when we're precaching because suppose the client takes
/// 10 minutes to load, all the moveable monsters and characters can be gone
/// already. And thus sending outdated information.
/// </remarks>
private void CM_CHARACTER_MAPLOADED()
{
try
{
#region Internal
//Register on the new map
this.character.currentzone.Regiontree.Subscribe(this.character);
//GET NEW Z-POS
float z = character.Position.z + 100;
//Refresh Personal Requests
CommonFunctions.RefreshPersonalRequests(this.character);
Regiontree.UpdateRegion(this.character);
isloaded = false;
#endregion Internal
#region Actor infromation
{
/*
* Send actor information
*
* This packet makes a actor appear on the screen. Just like character information
* It defines automaticly which actor is your actor.
*/
SMSG_ACTORINFO spkt = new SMSG_ACTORINFO();
spkt.ActorID = this.character.id;
spkt.X = this.character.Position.x;
spkt.Y = this.character.Position.y;
spkt.Z = this.character.Position.z;
spkt.race = this.character.race;
spkt.face = this.character.FaceDetails;
spkt.ActiveWeaponIndex = (byte)this.character.weapons.ActiveWeaponIndex;
spkt.InventoryContainerSize = (byte)this.character.container.Capacity;
spkt.StorageContainerSize = (byte)this.character.STORAGE.Capacity;
spkt.UnlockedWeaponCount = this.character.weapons.UnlockedWeaponSlots;
spkt.Unknown = 0;
spkt.PrimaryWeaponByIndex = this.character.weapons.PrimaryWeaponIndex;
spkt.SeccondairyWeaponByIndex = this.character.weapons.SeconairyWeaponIndex;
spkt.Name = this.character.Name;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Actor infromation
#region Battle Stats
{
CommonFunctions.SendBattleStatus(this.character);
}
#endregion Battle Stats
#region Extend Stats
{
/*
* Sends over the status points attributes
*
*/
SMSG_EXTSTATS spkt2 = new SMSG_EXTSTATS();
spkt2.base_stats_1 = character.stats.BASE;
spkt2.base_stats_2 = character.stats.CHARACTER;
spkt2.base_stats_jobs = character.stats.EQUIPMENT;
spkt2.base_stats_bonus = character.stats.ENCHANTMENT;
spkt2.statpoints = character.stats.REMAINING;
spkt2.SessionId = character.id;
this.Send((byte[])spkt2);
}
#endregion Extend Stats
if (IsFirstTimeLoad)
{
#if THREADING
WaitCallback FireTimeLoginCallback = delegate(object a)
{
#else
{
#endif
#region Equipment List
{
/*
* Sends a list of all Equiped Equipment
*/
SMSG_EQUIPMENTLIST spkt = new SMSG_EQUIPMENTLIST();
for (int i = 0; i < 16; i++)
{
Rag2Item item = this.character.Equipment[i];
if (item != null) spkt.AddItem(item, item.active, i);
}
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Equipment List
#region Weaponary List
{
/*
* Sends a list of all weapons
*/
SMSG_WEAPONLIST spkt = new SMSG_WEAPONLIST();
spkt.SessionId = this.character.id;
for (int i = 0; i < 5; i++)
{
Weapon current = this.character.weapons[i];
spkt.AddWeapon(current);
}
this.Send((byte[])spkt);
}
#endregion Weaponary List
#region Unlock Weaponary
{
/*
* This packet unlocks the selected slots
*/
SMSG_ADDITIONLIST spkt = new SMSG_ADDITIONLIST();
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Unlock Weaponary
#region Character Status
{
/*
* Send Character status
*
* This updates the characters status, this defines which job you're using
* the experience you have. The experience is expressed in absolute values
* so it doesn't represent a relative value for exp required.
*
* It also contains the definitions of how many LC, LP, HP, SP you have.
* Note: LC represents the amount of breath capacity.
*/
SMSG_CHARSTATUS spkt = new SMSG_CHARSTATUS();
spkt.Job = this.character.job;
spkt.Exp = this.character.Cexp;
spkt.JobExp = this.character.Jexp;
spkt.LC = this.character._status.CurrentOxygen;
spkt.MaxLC = this.character._status.MaximumOxygen;
spkt.HP = this.character.HP;
spkt.MaxHP = this.character.HPMAX;
spkt.SP = this.character.SP;
spkt.MaxSP = this.character.SPMAX;
spkt.LP = this.character._status.CurrentLp;
spkt.MaxLP = 7;
spkt.FieldOfSight = 0;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Character Status
#region Battle Skills
{
/*
* Region Send all battle skills
*
* Also known as all active skills, heals, buffs included
*/
List<Skill> list = this.character.learnedskills;
SMSG_BATTLESKILL battleskills = new SMSG_BATTLESKILL(list.Count);
foreach (Skill skill in list)
battleskills.AddSkill(skill.Id, skill.Experience);
battleskills.SessionId = this.character.id;
this.Send((byte[])battleskills);
}
#endregion Battle Skills
#region Special Skills
{
/*
* Sends over an list of special skills
*
*/
SMSG_LISTSPECIALSKILLS spkt = new SMSG_LISTSPECIALSKILLS();
for (int i = 0; i < 16; i++)
{
Skill skill = character.SpecialSkills[i];
if (skill != null)
{
spkt.AddSkill(skill.info.skillid, skill.Experience, (byte)i);
}
}
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Special Skills
#region Update Zeny
{
/*
* Send Money
*
* This sets the money of a player to a absolute value. For instance if you
* say 500, it would mean the player gets 500 rufi. There are no relative
* values for TakeMoney or GiveMoney.
*/
SMSG_SENDZENY spkt = new SMSG_SENDZENY();
spkt.Zeny = this.character.ZENY;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Update Zeny
#region Send Quest List
{
SMSG_QUESTINFO spkt3 = new SMSG_QUESTINFO();
spkt3.SessionId = this.character.id;
foreach (QuestBase Quest in this.character.QuestObjectives)
{
List<Saga.Quests.Objectives.ObjectiveList.StepInfo> Steps =
QuestBase.GetSteps(this.character, Quest.QuestId);
spkt3.AddQuest(Quest.QuestId, (byte)Steps.Count);
for (int i = 0; i < Steps.Count; i++)
{
Saga.Quests.Objectives.ObjectiveList.StepInfo currentStep = Steps[i];
uint nextstep = (i + 1 < Steps.Count) ? Steps[i + 1].StepId : 0;
spkt3.AddQuestStep(currentStep.StepId, currentStep.State, nextstep, Quest.isnew);
}
}
this.Send((byte[])spkt3);
foreach (QuestBase Quest in this.character.QuestObjectives)
{
List<Saga.Quests.Objectives.ObjectiveList.StepInfo> Steps =
QuestBase.GetSteps(this.character, Quest.QuestId);
for (int i = 0; i < Steps.Count; i++)
{
Saga.Quests.Objectives.ObjectiveList.StepInfo currentStep = Steps[i];
if (currentStep.State == 1)
{
Predicate<Saga.Quests.Objectives.ObjectiveList.SubStep> Findsubstep = delegate(Saga.Quests.Objectives.ObjectiveList.SubStep objective)
{
return objective.Quest == Quest.QuestId
&& objective.StepId == currentStep.StepId;
};
List<Quests.Objectives.ObjectiveList.SubStep> Substeps =
this.character.QuestObjectives.Substeps.FindAll(Findsubstep);
foreach (Saga.Quests.Objectives.ObjectiveList.SubStep substep in Substeps)
{
if (substep.current > 0)
{
SMSG_QUESTSUBSTEPUPDATE spkt = new SMSG_QUESTSUBSTEPUPDATE();
spkt.Unknown = 1;
spkt.SubStep = (byte)substep.SubStepId;
spkt.StepID = substep.StepId;
spkt.QuestID = substep.Quest;
spkt.Amount = (byte)substep.current;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
}
break;
}
}
}
}
#endregion Send Quest List
#region Send Way Points
{
foreach (QuestBase Quest in this.character.QuestObjectives)
{
SMSG_SENDNAVIGATIONPOINT spkt2 = new SMSG_SENDNAVIGATIONPOINT();
spkt2.SessionId = this.character.id;
spkt2.QuestID = Quest.QuestId;
foreach (Saga.Quests.Objectives.ObjectiveList.Waypoint waypoint in QuestBase.UserGetWaypoints(this.character, Quest.QuestId))
{
Predicate<MapObject> IsNpc = delegate(MapObject match)
{
return match.ModelId == waypoint.NpcId;
};
MapObject myObject = this.character.currentzone.Regiontree.SearchActor(IsNpc, SearchFlags.Npcs);
if (myObject != null)
{
spkt2.AddPosition(waypoint.NpcId, myObject.Position.x, myObject.Position.y, myObject.Position.z);
}
}
this.Send((byte[])spkt2);
}
}
#endregion Send Way Points
#region Addition List
{
SMSG_ADDITIONLIST spkt = new SMSG_ADDITIONLIST();
spkt.SessionId = this.character.id;
foreach (AdditionState state in character._additions)
{
if (state.CanExpire)
{
spkt.Add(state.Addition, state.Lifetime);
}
else
{
spkt.Add(state.Addition, 0);
}
}
this.Send((byte[])spkt);
}
#endregion Addition List
#region Scenario
{
QuestBase scenarioQuest = this.character.QuestObjectives.Quests[3];
if (scenarioQuest != null)
{
SMSG_INITIALIZESCENARIO spkt = new SMSG_INITIALIZESCENARIO();
spkt.Scenario1 = scenarioQuest.QuestId;
List<Saga.Quests.Objectives.ObjectiveList.StepInfo> list;
if (this.character.QuestObjectives.ScenarioSteps.TryGetValue(scenarioQuest.QuestId, out list))
if (list.Count > 0)
{
spkt.Scenario2 = list[0].StepId;
spkt.StepStatus = 1;
spkt.Enabled = 0;
}
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
else
{
QuestBase qbase;
if (Singleton.Quests.TryFindScenarioQuest(1, out qbase))
{
qbase.OnStart(character.id);
}
}
}
#endregion Scenario
#region Mail
{
int count = Singleton.Database.GetInboxUncheckedCount(this.character.Name);
SMSG_MAILARRIVED spkt = new SMSG_MAILARRIVED();
spkt.Amount = (uint)count;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
#endregion Mail
#region Inventory List
{
SMSG_INVENTORYLIST spkt5 = new SMSG_INVENTORYLIST((byte)this.character.container.Count);
spkt5.SessionId = this.character.id;
foreach (Rag2Item c in this.character.container)
spkt5.AddItem(c);
this.Send((byte[])spkt5);
}
#endregion Inventory List
#region Friendlist
{
WaitCallback FriendlistLogin = delegate(object state)
{
//Look through all friends lists of logged on players and if they are friends then
// notify them that the user logged on.
SMSG_FRIENDSLIST_NOTIFYLOGIN spkt = new SMSG_FRIENDSLIST_NOTIFYLOGIN();
spkt.name = this.character.Name;
foreach (Character characterTarget in LifeCycle.Characters)
{
lock (characterTarget)
{
if (characterTarget.id != this.character.id)
if (character._friendlist.Contains(this.character.Name))
{
spkt.SessionId = characterTarget.id;
characterTarget.client.Send((byte[])spkt);
}
}
}
};
ThreadPool.QueueUserWorkItem(FriendlistLogin);
}
#endregion Friendlist
#if THREADING
};
ThreadPool.QueueUserWorkItem(FireTimeLoginCallback);
#else
}
#endif
}
else
{
//Always ubsubcribe from the respawn manager in case
//we forget to do it.
Tasks.Respawns.Unsubscribe(this.character);
}
#region Dynamic Objects
{
try
{
Regiontree tree = this.character.currentzone.Regiontree;
#if THREADING
WaitCallback FindCharactersActors = delegate(object a)
{
#else
{
#endif
foreach (Character regionObject in tree.SearchActors(this.character, SearchFlags.Characters))
{
try
{
if (Point.IsInSightRangeByRadius(this.character.Position, regionObject.Position))
{
regionObject.ShowObject(this.character);
if (this.character.id != regionObject.id)
{
this.character.ShowObject(regionObject);
}
regionObject.Appears(this.character);
}
}
catch (SocketException)
{
Trace.WriteLine("Network eror");
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
}
}
#if THREADING
};
#else
}
#endif
#if THREADING
WaitCallback FindNpcActors = delegate(object a)
{
#else
{
#endif
foreach (MapObject regionObject in tree.SearchActors(this.character, SearchFlags.MapItems | SearchFlags.Npcs))
{
try
{
if (Point.IsInSightRangeByRadius(this.character.Position, regionObject.Position))
{
regionObject.ShowObject(this.character);
regionObject.Appears(this.character);
}
}
catch (SocketException)
{
Trace.WriteLine("Network eror");
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
}
}
#if THREADING
};
#else
}
#endif
#if THREADING
ThreadPool.QueueUserWorkItem(FindCharactersActors);
ThreadPool.QueueUserWorkItem(FindNpcActors);
#endif
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
}
}
#endregion Dynamic Objects
#region Time Weather
CommonFunctions.UpdateTimeWeather(this.character);
#endregion Time Weather
#region Map Info
{
SMSG_SHOWMAPINFO spkt2 = new SMSG_SHOWMAPINFO();
spkt2.SessionId = this.character.id;
spkt2.ZoneInfo = this.character.ZoneInformation;
this.Send((byte[])spkt2);
}
#endregion Map Info
#region Return Points
{
/*
* Send Resturn points
* Return points define which map you'll be send to when you
* use your promise stone or die
*/
WorldCoordinate lpos = this.character.lastlocation.map > 0 ? this.character.lastlocation : this.character.savelocation;
WorldCoordinate spos = this.character.savelocation;
if (spos.map == this.character.currentzone.Map)
{
this.character.stance = (byte)StancePosition.Stand;
SMSG_RETURNMAPLIST spkt = new SMSG_RETURNMAPLIST();
spkt.ToMap = lpos.map;
spkt.FromMap = this.character.currentzone.CathelayaLocation.map;
spkt.IsSaveLocationSet = (lpos.map > 0) ? (byte)1 : (byte)0;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
else
{
this.character.stance = (byte)StancePosition.Stand;
SMSG_RETURNMAPLIST spkt = new SMSG_RETURNMAPLIST();
spkt.ToMap = spos.map;
spkt.FromMap = this.character.currentzone.CathelayaLocation.map;
spkt.IsSaveLocationSet = (spos.map > 0) ? (byte)1 : (byte)0;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
}
#endregion Return Points
#region Job Levels
{
SMSG_JOBLEVELS spkt2 = new SMSG_JOBLEVELS();
spkt2.SessionId = this.character.id;
spkt2.jobslevels = this.character.CharacterJobLevel;
this.Send((byte[])spkt2);
}
#endregion Job Levels
#region Change Actors state
{
/*
* Change the actors state
*
* This is used to change the actors state to a non-active-battle position.
* Note we will not warp the player back on their x and y coords if they were dead.
* This would result in double loading a map. This should be handeld before processing
* the character.
*/
this.character.stance = (byte)StancePosition.Reborn;
this.character.ISONBATTLE = false;
SMSG_ACTORCHANGESTATE spkt = new SMSG_ACTORCHANGESTATE();
spkt.ActorID = this.character.id;
spkt.SessionId = this.character.id;
spkt.Stance = this.character.stance;
spkt.State = (this.character.ISONBATTLE) ? (byte)1 : (byte)0;
this.Send((byte[])spkt);
}
#endregion Change Actors state
#region Party Update
if (this.character.sessionParty != null)
{
foreach (Character partyTarget in this.character.sessionParty._Characters)
{
//Only process if we're on the same map
if (partyTarget.id != this.character.id)
if (partyTarget.map == this.character.map)
{
//Retrieve positions people that are loaded
SMSG_PARTYMEMBERLOCATION spkt2 = new SMSG_PARTYMEMBERLOCATION();
spkt2.Index = 1;
spkt2.ActorId = partyTarget.id;
spkt2.SessionId = this.character.id;
spkt2.X = (partyTarget.Position.x / 1000);
spkt2.Y = (partyTarget.Position.y / 1000);
this.Send((byte[])spkt2);
//Update the position of myself to loaded characters
SMSG_PARTYMEMBERLOCATION spkt3 = new SMSG_PARTYMEMBERLOCATION();
spkt3.Index = 1;
spkt3.ActorId = this.character.id;
spkt3.SessionId = partyTarget.id;
spkt3.X = (this.character.Position.x / 1000);
spkt3.Y = (this.character.Position.y / 1000);
partyTarget.client.Send((byte[])spkt3);
}
}
}
#endregion Party Update
#region Static Objects
try
{
//SEND OVER ALL CHARACTERS THAT ARE ALWAYS VISIBLE
foreach (MapObject regionObject in this.character.currentzone.Regiontree.SearchActors(SearchFlags.StaticObjects))
{
Console.WriteLine("Show object: {0}", regionObject.ToString());
regionObject.ShowObject(this.character);
regionObject.Appears(this.character);
}
}
catch (Exception)
{
//Do nothing
}
#endregion Static Objects
}
catch (Exception e)
{
Console.WriteLine(e);
this.Close();
}
finally
{
this.character.ISONBATTLE = false;
isloaded = true;
IsFirstTimeLoad = false;
this.character.LastPositionTick = Environment.TickCount;
}
}
/// <summary>
/// Checks for position updates.
/// </summary>
/// <remarks>
/// First we'll check to see if we could see, actor x from
/// our old position. After that we'll check if can see actor x
/// from our new position. If we can see him, we'll forward our movement
/// packet. If we can't see him we'll sent a actor disappearance packet.
///
/// Once that's done, we'll check if we can see a non-former visible actor
/// is now visible in our new position. Which will cause us to invoke a appearance
/// packet.
/// </remarks>
/// <param name="cpkt"></param>
private void CM_CHARACTER_MOVEMENTSTART(CMSG_MOVEMENTSTART cpkt)
{
if (this.isloaded == false)
{
return;
}
//If character was previous walking/running
if (this.character.IsMoving)
{
long time = (long)((uint)Environment.TickCount) - (long)((uint)this.character.LastPositionTick);
//Sending packet to late
if (time > 10000)
{
CommonFunctions.Warp(this.character, this.character.Position, this.character.currentzone);
this.character.LastPositionTick = Environment.TickCount;
return;
}
else
{
this.character.LastPositionTick = Environment.TickCount;
}
}
else
{
this.character.LastPositionTick = Environment.TickCount;
}
//CALCULATE CURRENT MOVING SPEED
ushort speed = (ushort)this.character._status.WalkingSpeed;
if (cpkt.MovementType != 1)
{
if (speed > 0) speed /= 2;
}
//Get new actors for next-tick
uint delay = cpkt.DelayTime;
byte movement = cpkt.MovementType;
float ax = cpkt.AccelerationX;
float ay = cpkt.AccelerationY;
float az = cpkt.AccelerationZ;
Point oldP = this.character.Position;
Point newP = new Point(cpkt.X, cpkt.Y, cpkt.Z);
this.character.stance = (byte)StancePosition.Walk;
this.character.Yaw = cpkt.Yaw;
Regiontree tree = this.character.currentzone.Regiontree;
try
{
foreach (MapObject regionObject in tree.SearchActors(this.character, SearchFlags.Npcs | SearchFlags.Characters | SearchFlags.MapItems, newP))
{
bool CanSeePrev = Point.IsInSightRangeByRadius(regionObject.Position, oldP);
bool CanSeeNext = Point.IsInSightRangeByRadius(regionObject.Position, newP);
if (CanSeeNext && !CanSeePrev)
{
//Show object to other characters
if (MapObject.IsPlayer(regionObject))
{
Character current = (Character)regionObject;
this.character.ShowObject(current);
}
//Show object to self
regionObject.ShowObject(this.character);
regionObject.Appears(this.character);
}
else if (CanSeePrev && !CanSeeNext)
{
//Hide Object to other characters
if (MapObject.IsPlayer(regionObject))
{
Character current = (Character)regionObject;
this.character.HideObject(current);
}
//Hide Object to myself
regionObject.HideObject(this.character);
regionObject.Disappear(this.character);
}
else if (CanSeeNext && CanSeePrev)
{
//Update movment
if (MapObject.IsPlayer(regionObject))
{
Character current = (Character)regionObject;
if (current.client.isloaded == false) continue;
SMSG_MOVEMENTSTART spkt = new SMSG_MOVEMENTSTART();
spkt.SourceActorID = this.character.id;
spkt.Speed = speed;
spkt.X = oldP.x;
spkt.Y = oldP.y;
spkt.Z = oldP.z;
spkt.Yaw = this.character.Yaw;
spkt.MovementType = movement;
spkt.Delay0 = delay;
spkt.TargetActor = this.character._targetid;
spkt.AccelerationX = ax;
spkt.AccelerationY = ay;
spkt.AccelerationZ = az;
spkt.SessionId = current.id;
current.client.Send((byte[])spkt);
}
//Console.WriteLine("Disappear: {0}", regionObject.ToString());
}
}
}
catch (Exception)
{
Trace.WriteLine("Error on local region");
}
finally
{
if (this.character.sessionParty != null)
{
foreach (Character target in this.character.sessionParty._Characters)
{
try
{
if (target.id == this.character.id) continue;
SMSG_PARTYMEMBERLOCATION spkt3 = new SMSG_PARTYMEMBERLOCATION();
spkt3.Index = 1;
spkt3.ActorId = this.character.id;
spkt3.SessionId = target.id;
spkt3.X = (this.character.Position.x / 1000);
spkt3.Y = (this.character.Position.y / 1000);
target.client.Send((byte[])spkt3);
}
catch (SocketException)
{
Trace.WriteLine("Party network error");
}
catch (Exception)
{
Trace.WriteLine("Unknown error");
}
}
}
}
this.character.Position = newP;
Regiontree.UpdateRegion(this.character);
QuestBase.UserCheckPosition(this.character);
}
/// <summary>
/// Checks for position updates.
/// </summary>
/// <remarks>
/// First we'll check to see if we could see, actor x from
/// our old position. After that we'll check if can see actor x
/// from our new position. If we can see him, we'll forward our movement
/// packet. If we can't see him we'll sent a actor disappearance packet.
///
/// Once that's done, we'll check if we can see a non-former visible actor
/// is now visible in our new position. Which will cause us to invoke a appearance
/// packet.
/// </remarks>
/// <param name="cpkt"></param>
private void CM_CHARACTER_MOVEMENTSTOPPED(CMSG_MOVEMENTSTOPPED cpkt)
{
if (this.isloaded == false) return;
//If character was previous walking/running
if (!this.character.IsMoving)
{
this.character.LastPositionTick = Environment.TickCount;
return;
}
else
{
//Sending packet to late
int time = Environment.TickCount - this.character.LastPositionTick;
if (time > 10000)
{
CommonFunctions.Warp(this.character, this.character.Position, this.character.currentzone);
this.character.LastPositionTick = Environment.TickCount;
return;
}
else
{
this.character.LastPositionTick = Environment.TickCount;
}
}
// GENERATE NEW PACKETS, WE PREPROCESS
SMSG_MOVEMENTSTOPPED spkt = new SMSG_MOVEMENTSTOPPED();
spkt.ActorID = this.character.id;
spkt.speed = cpkt.Speed;
spkt.X = cpkt.X;
spkt.Y = cpkt.Y;
spkt.Z = cpkt.Z;
spkt.yaw = cpkt.Yaw;
spkt.TargetActor = this.character._targetid;
spkt.DelayTime = cpkt.DelayTime;
//Get new actors for next-tick
Point oldP = this.character.Position;
Point newP = new Point(cpkt.X, cpkt.Y, cpkt.Z);
this.character.stance = (byte)StancePosition.Stand;
this.character.Position = newP;
Regiontree.UpdateRegion(this.character);
Regiontree tree = this.character.currentzone.Regiontree;
try
{
foreach (MapObject regionObject in tree.SearchActors(this.character, SearchFlags.Npcs | SearchFlags.Characters | SearchFlags.MapItems))
{
bool CanSeePrev = Point.IsInSightRangeByRadius(regionObject.Position, oldP);
bool CanSeeNext = Point.IsInSightRangeByRadius(regionObject.Position, newP);
if (CanSeeNext && !CanSeePrev)
{
if (MapObject.IsPlayer(regionObject))
{
Character current = (Character)regionObject;
this.character.ShowObject(current);
}
regionObject.ShowObject(this.character);
regionObject.Appears(this.character);
}
else if (CanSeePrev && !CanSeeNext)
{
//Hide Object to other characters
if (MapObject.IsPlayer(regionObject))
{
Character current = (Character)regionObject;
this.character.HideObject(current);
}
//Hide Object to myself
regionObject.HideObject(this.character);
regionObject.Disappear(this.character);
}
else if (CanSeeNext && CanSeePrev)
{
if (MapObject.IsPlayer(regionObject))
{
Character current = (Character)regionObject;
if (current.client.isloaded == false) continue;
spkt.SessionId = current.id;
current.client.Send((byte[])spkt);
}
}
}
}
catch (Exception)
{
Trace.WriteLine("Error network code");
}
finally
{
if (this.character.sessionParty != null)
{
foreach (Character target in this.character.sessionParty._Characters)
{
try
{
if (target.id == this.character.id) continue;
SMSG_PARTYMEMBERLOCATION spkt3 = new SMSG_PARTYMEMBERLOCATION();
spkt3.Index = 1;
spkt3.ActorId = this.character.id;
spkt3.SessionId = target.id;
spkt3.X = (this.character.Position.x / 1000);
spkt3.Y = (this.character.Position.y / 1000);
target.client.Send((byte[])spkt3);
}
catch (SocketException)
{
Trace.WriteLine("Network error");
}
catch (Exception)
{
Trace.WriteLine("Unknown error");
}
}
}
}
}
/// <summary>
/// Updates the Yaw
/// </summary>
/// <remarks>
/// Yaw defines the angle of which a user is facing. This angle is expressed in
/// yaw which has a maximum value of 65535 (size of ushort).
///
/// And should be used to double check casting purposes. You're allowed to talk to a
/// npc, attack a monster, use openbox skills only when delta angle meets ~35 degrees
/// </remarks>
/// <param name="cpkt"></param>
private void CM_CHARACTER_UPDATEYAW(CMSG_SENDYAW cpkt)
{
if (this.isloaded == false) return;
Regiontree tree = this.character.currentzone.Regiontree;
this.character.Yaw = cpkt.Yaw;
foreach (Character regionObject in tree.SearchActors(SearchFlags.Characters))
if (regionObject.client.isloaded == true
&& Point.IsInSightRangeByRadius(this.character.Position, regionObject.Position))
{
SMSG_UPDATEYAW spkt = new SMSG_UPDATEYAW();
spkt.ActorID = this.character.id;
spkt.Yaw = this.character.Yaw;
spkt.SessionId = regionObject.id;
regionObject.client.Send((byte[])spkt);
}
}
/// <summary>
/// Makes your character jump in the air.
/// </summary>
private void CM_CHARACTER_JUMP()
{
SMSG_ACTORCHANGESTATE spkt = new SMSG_ACTORCHANGESTATE();
spkt.ActorID = this.character.id;
spkt.TargetActor = this.character._targetid;
spkt.Stance = (byte)StancePosition.Jump;
spkt.State = (byte)((this.character.ISONBATTLE == true) ? 1 : 0);
foreach (MapObject myObject in this.character.currentzone.GetObjectsInRegionalRange(this.character))
if (this.character.currentzone.IsInSightRangeBySquare(this.character.Position, myObject.Position))
if (MapObject.IsPlayer(myObject))
{
Character current = myObject as Character;
if (current.client.isloaded == true)
{
spkt.SessionId = current.id;
current.client.Send((byte[])spkt);
}
}
}
/// <summary>
/// This packet is sent when the user goed underwater
///
/// This invokes the starting of a the oxygen task, this task will
/// take each seccond 1 LC from the Current LC state. This task will
/// process all the required packets.
/// </summary>
private void CM_CHARACTER_DIVEDOWN()
{
this.character.IsDiving = true;
SMSG_ACTORDIVE spkt = new SMSG_ACTORDIVE();
spkt.SessionId = this.character.id;
spkt.Direction = 0;
spkt.Oxygen = this.character._status.CurrentOxygen;
this.Send((byte[])spkt);
}
/// <summary>
/// This packet is sent when the user reaches the surface/height is
/// same as the water level.
/// </summary>
private void CM_CHARACTER_DIVEUP()
{
this.character.IsDiving = false;
SMSG_ACTORDIVE spkt = new SMSG_ACTORDIVE();
spkt.SessionId = this.character.id;
spkt.Direction = 1;
spkt.Oxygen = this.character._status.CurrentOxygen;
this.Send((byte[])spkt);
}
/// <summary>
/// Occurs after a player fell from a large distance
/// </summary>
/// <param name="cpkt"></param>
private void CM_CHARACTER_FALL(CMSG_ACTORFALL cpkt)
{
if (this.isloaded == false) return;
//HELPER VARIBALES
uint value = cpkt.TargetActor / 8;
ushort NewHP = (ushort)(this.character.HP - value);
SMSG_TAKEDAMAGE spkt = new SMSG_TAKEDAMAGE();
spkt.SessionId = this.character.id;
//Update last hp tick
this.character.LASTHP_TICK = Environment.TickCount;
//Get the falling reason
if (value >= this.character.HP)
spkt.Reason = (byte)TakeDamageReason.FallenDead;
else if (NewHP < (this.character.HPMAX / 10))
spkt.Reason = (byte)TakeDamageReason.Survive;
else
spkt.Reason = (byte)TakeDamageReason.Falling;
//Update some stuff
bool isdead = value > this.character._status.CurrentHp;
if (isdead)
{
spkt.Damage = this.character._status.CurrentHp;
this.Send((byte[])spkt);
this.character.stance = (byte)StancePosition.Dead;
this.character.UpdateReason |= 1;
this.character._status.CurrentHp = 0;
this.character.OnDie();
this.character._status.Updates |= 1;
LifeCycle.Update(this.character);
}
else
{
spkt.Damage = value;
this.Send((byte[])spkt);
this.character._status.CurrentHp = NewHP;
Common.Skills.UpdateAddition(this.character, 201, 30000);
this.character._status.Updates |= 1;
LifeCycle.Update(this.character);
}
//Update life cycle
LifeCycle.Update(this.character);
Regiontree tree = this.character.currentzone.Regiontree;
foreach (Character sTarget in tree.SearchActors(SearchFlags.Characters))
{
if (isdead)
Common.Actions.UpdateStance(sTarget, this.character);
}
}
/// <summary>
/// Changes the state of the player.
/// </summary>
/// <remarks>
/// This functions is invoked when the user changes his/hers p
/// players state. For example when the players is laying down
///or is sitting down. This packet is called.
///
/// When a player is going to sit down, the regen bonusses are
/// changed. The regeneration bonussed are since the 26dec patch
/// 2007:
///
/// Players battle stance: 0-HP 0.35MSP-SP
/// Player standing: 15-HP 0.35MSP-SP
/// Player sitting: 15-HP 0.35MSP-SP
/// Player laying: 15-HP 0.35MSP-SP
/// </remarks>
/// <param name="cpkt"></param>
private void CM_CHARACTER_CHANGESTATE(CMSG_ACTORCHANGESTATE cpkt)
{
if (cpkt.Stance > 12) return;
//Checks if the old position was a valentine lay
Regiontree tree = this.character.currentzone.Regiontree;
bool LeaveLove = (this.character.stance == 9 || this.character.stance == 10);
if (LeaveLove)
{
Character target;
if (LifeCycle.TryGetById(this.character._ShowLoveDialog, out target))
{
//Update the stance
switch ((StancePosition)target.stance)
{
case StancePosition.VALENTINE_SIT: target.stance = (byte)StancePosition.Sit; break;
case StancePosition.VALENTINE_LAY: target.stance = (byte)StancePosition.Lie; break;
default: target.stance = (byte)StancePosition.Stand; break;
}
//Release the showlove
this.character._ShowLoveDialog = 0;
//Reset the stance
foreach (Character current in tree.SearchActors(this.character, SearchFlags.Characters))
{
if (current.client.isloaded == false || !Point.IsInSightRangeByRadius(current.Position, this.character.Position)) continue;
SMSG_ACTORCHANGESTATE spkt2 = new SMSG_ACTORCHANGESTATE();
spkt2.ActorID = target.id;
spkt2.State = (byte)((target.ISONBATTLE) ? 1 : 0);
spkt2.Stance = target.stance;
spkt2.TargetActor = target._targetid;
spkt2.SessionId = current.id;
current.client.Send((byte[])spkt2);
}
}
}
//Update my information
this.character.stance = cpkt.Stance;
this.character.ISONBATTLE = cpkt.State > 0;
//Create packet
SMSG_ACTORCHANGESTATE spkt = new SMSG_ACTORCHANGESTATE();
spkt.ActorID = this.character.id;
spkt.State = cpkt.State;
spkt.Stance = cpkt.Stance;
spkt.TargetActor = cpkt.TargetActor;
foreach (Character current in tree.SearchActors(this.character, SearchFlags.Characters))
{
if (current.client.isloaded == false) continue;
spkt.SessionId = current.id;
current.client.Send((byte[])spkt);
}
}
/// <summary>
/// Character uses a portal
/// </summary>
/// <remarks>
///This function is invoked when a players used a portal
///to warp to another place. Because we made a common function of the
///warp, it safe for use to invoke that.
/// </remarks>
/// <param name="cpkt"></param>
private void CM_CHARACTER_USEPORTAL(CMSG_USEPORTAL cpkt)
{
try
{
Saga.Factory.Portals.Portal portal;
if (Singleton.portal.TryFind(cpkt.PortalID, this.character.map, out portal))
{
CommonFunctions.Warp(this.character, portal.mapID, portal.destinaton);
}
else
{
Trace.TraceInformation("Portal not found: {0}", cpkt.PortalID);
SMSG_PORTALFAIL spkt = new SMSG_PORTALFAIL();
spkt.Reason = 1;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
}
catch (Exception)
{
SMSG_PORTALFAIL spkt = new SMSG_PORTALFAIL();
spkt.Reason = 2;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
}
/// <summary>
/// Changes the stats of a character
/// </summary>
/// <remarks>
/// This function updates the characters stats with
/// (read as synchorinisation) the client.
///
/// Momentairly we do no checking if for cheating or
/// packet injection. Todo: do checks for packet
/// injection.
/// </remarks>
/// <param name="cpkt"></param>
private void CM_CHARACTER_STATPOINTUPDATE(CMSG_STATUPDATE cpkt)
{
Saga.PrimaryTypes.CharacterStats.Stats stats = this.character.stats.CHARACTER;
int maxwantedstats = cpkt.Strength + cpkt.Dextericty + cpkt.Intellect + cpkt.Concentration + cpkt.PointsLeft;
int maxcharstats = stats.strength + stats.dexterity + stats.intelligence + stats.concentration + this.character.stats.REMAINING;
//Cannot alter the stats is starting stats isnt equal with ending stats.
//Prevents hacking etc to gain more stats.
if (maxwantedstats != maxcharstats) return;
lock (character._status)
{
//Update strength
character._status.MaxPAttack -= (ushort)(2 * stats.strength);
character._status.MinPAttack -= (ushort)(1 * stats.strength);
character._status.MaxHP -= (ushort)(10 * stats.strength);
character._status.MaxPAttack += (ushort)(2 * cpkt.Strength);
character._status.MaxPAttack += (ushort)(1 * cpkt.Strength);
character._status.MaxHP += (ushort)(10 * cpkt.Strength);
stats.strength = cpkt.Strength;
//Update Dextericty
character._status.BasePHitrate -= (ushort)(1 * stats.dexterity);
character._status.BasePHitrate += (ushort)(1 * cpkt.Dextericty);
stats.dexterity = cpkt.Dextericty;
//Update Intellect
character._status.MaxMAttack -= (ushort)(6 * stats.intelligence);
character._status.MinMAttack -= (ushort)(3 * stats.intelligence);
character._status.BaseRHitrate -= (ushort)(1 * stats.intelligence);
character._status.MaxMAttack += (ushort)(6 * cpkt.Intellect);
character._status.MinMAttack += (ushort)(3 * cpkt.Intellect);
character._status.BaseRHitrate += (ushort)(1 * cpkt.Intellect);
stats.intelligence = cpkt.Intellect;
//Update Concentration
character._status.MaxRAttack -= (ushort)(4 * stats.concentration);
character._status.MinRAttack -= (ushort)(2 * stats.concentration);
character._status.BasePHitrate -= (ushort)(2 * stats.concentration);
character._status.MaxRAttack += (ushort)(4 * cpkt.Concentration);
character._status.MinRAttack += (ushort)(2 * cpkt.Concentration);
character._status.BasePHitrate += (ushort)(2 * cpkt.Concentration);
stats.concentration = cpkt.Concentration;
}
//Update points left
this.character.stats.REMAINING = cpkt.PointsLeft;
//Update the client
CommonFunctions.SendExtStats(this.character);
CommonFunctions.UpdateCharacterInfo(this.character, 0);
CommonFunctions.SendBattleStatus(this.character);
}
/// <summary>
/// Is invoked when a character chooses one of the options in
/// their homepoint button.
/// </summary>
/// <param name="cpkt"></param>
private void CM_CHARACTER_RETURNTOHOMEPOINT(CMSG_SENDHOMEPOINT cpkt)
{
if (this.character.savelocation.map > 0 && cpkt.Type == 0)
{
WorldCoordinate world = this.character.savelocation;
this.character.HP = 1;
this.character.ISONBATTLE = false;
CommonFunctions.Warp(this.character, world.map, world.coords);
this.character.lastlocation = this.character.savelocation;
}
else
{
//this.character.promise_map = this.character.currentzone.CathelayaMap;
//this.character.promiseposition = this.character.currentzone.CathelayaLocation;
WorldCoordinate world = this.character.currentzone.CathelayaLocation;
this.character.HP = 1;
this.character.ISONBATTLE = false;
CommonFunctions.Warp(this.character, world.map, world.coords);
this.character.lastlocation = this.character.savelocation;
}
}
/// <summary>
/// Occurs when requesting to show love to somebody. It forwards a packet to the
/// desired end-user.
/// </summary>
/// <param name="cpkt"></param>
private void CM_CHARACTER_SHOWLOVE(CMSG_SHOWLOVE cpkt)
{
Character target;
bool isfound = LifeCycle.TryGetById(cpkt.ActorId, out target);
if (isfound && target._ShowLoveDialog == 0)
{
SMSG_REQUESTSHOWLOVE spkt = new SMSG_REQUESTSHOWLOVE();
spkt.ActorID = this.character.id;
spkt.SessionId = target.id;
target._ShowLoveDialog = this.character.id;
this.character._ShowLoveDialog = target.id;
if (target.client != null)
target.client.Send((byte[])spkt);
}
else if (isfound && target._ShowLoveDialog > 0)
{
SMSG_RESPONSESHOWLOVE spkt = new SMSG_RESPONSESHOWLOVE();
spkt.Result = 3;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
//PLAYER DOES NOT EXISTS
else
{
SMSG_RESPONSESHOWLOVE spkt = new SMSG_RESPONSESHOWLOVE();
spkt.Result = 2;
spkt.SessionId = this.character.id;
this.Send((byte[])spkt);
}
}
/// <summary>
/// Occurs when confirming or decling to show love you've
/// recieve from a person.
/// </summary>
/// <param name="cpkt"></param>
private void CM_CHARACTER_CONFIRMSHOWLOVE(CMSG_SHOWLOVECONFIRM cpkt)
{
Character target;
if (LifeCycle.TryGetById(this.character._ShowLoveDialog, out target))
{
if (cpkt.Response == 0)
{
SMSG_ACTORCHANGESTATE spkt3 = new SMSG_ACTORCHANGESTATE();
spkt3.ActorID = this.character.id;
spkt3.State = 0;
spkt3.Stance = (byte)StancePosition.VALENTINE_LAY;
spkt3.TargetActor = target.id;
SMSG_ACTORCHANGESTATE spkt2 = new SMSG_ACTORCHANGESTATE();
spkt2.ActorID = target.id;
spkt2.State = 0;
spkt2.Stance = (byte)StancePosition.VALENTINE_SIT;
spkt2.TargetActor = this.character.id;
foreach (MapObject myObject in this.character.currentzone.GetObjectsInRegionalRange(this.character))
{
if (this.character.currentzone.IsInSightRangeBySquare(this.character.Position, myObject.Position))
{
if (MapObject.IsPlayer(myObject))
{
Character current = myObject as Character;
if (current.client != null && current.client.isloaded == true)
{
spkt3.SessionId = current.id;
spkt2.SessionId = current.id;
current.client.Send((byte[])spkt3);
current.client.Send((byte[])spkt2);
}
}
}
}
}
else
{
character._ShowLoveDialog = 0;
}
if (target.client != null)
{
SMSG_RESPONSESHOWLOVE spkt = new SMSG_RESPONSESHOWLOVE();
spkt.Result = cpkt.Response;
spkt.SessionId = target.id;
target.client.Send((byte[])spkt);
}
}
}
/// <summary>
/// Requests to change the job.
/// </summary>
/// <param name="cpkt"></param>
private void CM_CHARACTER_JOBCHANGE(CMSG_CHANGEJOB cpkt)
{
JobChangeCollection collection = this.character.Tag as JobChangeCollection;
if (collection == null || !collection.IsJobAvailable(cpkt.Job))
{
//Job change failed
SMSG_JOBCHANGED spkt = new SMSG_JOBCHANGED();
spkt.Job = this.character.job;
spkt.Result = 1;
spkt.SessionId = this.character.id;
spkt.SourceActor = this.character.id;
this.Send((byte[])spkt);
return;
}
else if (collection.GetJobTrasferFee(cpkt.Job) > this.character.ZENY)
{
//Not enough money
Common.Errors.GeneralErrorMessage(this.character, (uint)Generalerror.NotEnoughMoney);
SMSG_JOBCHANGED spkt = new SMSG_JOBCHANGED();
spkt.Job = this.character.job;
spkt.Result = 1;
spkt.SessionId = this.character.id;
spkt.SourceActor = this.character.id;
this.Send((byte[])spkt);
return;
}
else
{
this.character.ZENY -= collection.GetJobTrasferFee(cpkt.Job);
CommonFunctions.UpdateZeny(this.character);
}
//Helper variables
List<int> EnabledEquipment = new List<int>();
List<int> DisabledEquipment = new List<int>();
bool ChangeWeapon = cpkt.ChangeWeapon == 1;
bool IsActiveWeapon = this.character.weapons.IsActiveSlot(cpkt.WeaponSlot);
Weapon selectedWeapon = this.character.weapons[cpkt.WeaponSlot];
#region Update Character Information
lock (this.character)
{
//Change the job and joblevel
int hpbefore = Singleton.CharacterConfiguration.CalculateMaximumHP(this.character);
int spbefore = Singleton.CharacterConfiguration.CalculateMaximumSP(this.character);
this.character.CharacterJobLevel[this.character.job] = this.character.jlvl;
this.character.jlvl = this.character.CharacterJobLevel[cpkt.Job];
this.character.job = cpkt.Job;
this.character.Jexp = Singleton.experience.FindRequiredJexp(this.character.jlvl);
int hpafter = Singleton.CharacterConfiguration.CalculateMaximumHP(this.character);
int spafter = Singleton.CharacterConfiguration.CalculateMaximumSP(this.character);
this.character._status.CurrentHp += (ushort)(hpbefore - hpafter);
this.character._status.CurrentSp += (ushort)(spbefore - spafter);
this.character._status.Updates |= 1;
}
#endregion Update Character Information
#region Refresh Weapon
//Deapply current weapon info
if (ChangeWeapon && IsActiveWeapon && selectedWeapon != null)
{
BattleStatus status = this.character._status;
status.MaxWMAttack -= (ushort)selectedWeapon.Info.max_magic_attack;
status.MinWMAttack -= (ushort)selectedWeapon.Info.min_magic_attack;
status.MaxWPAttack -= (ushort)selectedWeapon.Info.max_short_attack;
status.MinWPAttack -= (ushort)selectedWeapon.Info.min_short_attack;
status.MaxWRAttack -= (ushort)selectedWeapon.Info.max_range_attack;
status.MinWRAttack -= (ushort)selectedWeapon.Info.min_range_attack;
status.Updates |= 2;
//Reapplies alterstone additions
for (int i = 0; i < 8; i++)
{
uint addition = selectedWeapon.Slots[i];
if (addition > 0)
{
Singleton.Additions.DeapplyAddition(addition, character);
}
}
}
#endregion Refresh Weapon
#region Refresh Weapon
if (ChangeWeapon && selectedWeapon != null)
{
Singleton.Weapons.ChangeWeapon(cpkt.Job, cpkt.PostFix, selectedWeapon);
SMSG_WEAPONCHANGE spkt = new SMSG_WEAPONCHANGE();
spkt.Auge = selectedWeapon._augeskill;
spkt.SessionId = this.character.id;
spkt.Suffix = cpkt.PostFix;
spkt.Index = cpkt.WeaponSlot;
spkt.WeaponType = (byte)selectedWeapon._type;
this.Send((byte[])spkt);
}
#endregion Refresh Weapon
#region Refresh Skills
{
//Remove all skills
foreach (Skill skill in this.character.learnedskills)
{
//Remove the skill
SMSG_SKILLREMOVE spkt = new SMSG_SKILLREMOVE();
spkt.Unknown = skill.info.skilltype;
spkt.SessionId = this.character.id;
spkt.SkillId = skill.info.skillid;
this.Send((byte[])spkt);
//Save only experience if it's maxed-out.
Singleton.Database.UpdateSkill(this.character, skill.Id,
(skill.Experience == skill.info.maximumexperience) ? skill.info.maximumexperience : 0);
//Deapply passive skills
bool canUse = Singleton.SpellManager.CanUse(this.character, skill.info);
if (skill.info.skilltype == 2 && canUse)
Singleton.Additions.DeapplyAddition(skill.info.addition, character);
}
//Remove all learned skills in an instant
this.character.learnedskills.Clear();
Singleton.Database.LoadSkills(this.character);
//Retrieve job speciafic skills
foreach (Skill skill in this.character.learnedskills)
{
//Add the skill
SMSG_SKILLADD spkt = new SMSG_SKILLADD();
spkt.SessionId = this.character.id;
spkt.SkillId = skill.info.skillid;
spkt.Slot = 0;
this.Send((byte[])spkt);
//Deapply passive skills
bool canUse = Singleton.SpellManager.CanUse(this.character, skill.info);
if (skill.info.skilltype == 2 && canUse)
Singleton.Additions.ApplyAddition(skill.info.addition, character);
}
}
#endregion Refresh Skills
#region Refresh Weapon
//Apply current weapon info
if (ChangeWeapon && IsActiveWeapon && selectedWeapon != null)
{
//Apply status
BattleStatus status = this.character._status;
status.MaxWMAttack += (ushort)selectedWeapon.Info.max_magic_attack;
status.MinWMAttack += (ushort)selectedWeapon.Info.min_magic_attack;
status.MaxWPAttack += (ushort)selectedWeapon.Info.max_short_attack;
status.MinWPAttack += (ushort)selectedWeapon.Info.min_short_attack;
status.MaxWRAttack += (ushort)selectedWeapon.Info.max_range_attack;
status.MinWRAttack += (ushort)selectedWeapon.Info.min_range_attack;
status.Updates |= 2;
//Reapplies alterstone additions
for (int i = 0; i < 8; i++)
{
uint addition = selectedWeapon.Slots[i];
if (addition > 0)
{
Singleton.Additions.ApplyAddition(addition, character);
}
}
}
#endregion Refresh Weapon
#region Refresh Equipment
{
//Disable equipment
for (int i = 0; i < 16; i++)
{
//Verify if item exists
Rag2Item item = this.character.Equipment[i];
if (item == null || item.info == null) continue;
//Verify if the item changed states
bool Active = item.active == 1;
bool NewActive = this.character.jlvl >= item.info.JobRequirement[cpkt.Job - 1];
if (Active == NewActive) continue;
item.active = (byte)((NewActive == true) ? 1 : 0);
//Adjust the item
SMSG_ITEMADJUST spkt = new SMSG_ITEMADJUST();
spkt.Container = 1;
spkt.Function = 5;
spkt.Slot = (byte)i;
spkt.SessionId = this.character.id;
spkt.Value = item.active;
this.Send((byte[])spkt);
//Deapply additions
if (NewActive)
{
EnabledEquipment.Add(i);
Singleton.Additions.ApplyAddition(item.info.option_id, character);
}
else
{
DisabledEquipment.Add(i);
Singleton.Additions.DeapplyAddition(item.info.option_id, character);
}
}
//Update other stats
//Common.Internal.CheckWeaponary(this.character);
//CommonFunctions.UpdateCharacterInfo(this.character, 0);
//CommonFunctions.SendBattleStatus(this.character);
}
#endregion Refresh Equipment
#region Refresh Appereance
{
Regiontree tree = this.character.currentzone.Regiontree;
foreach (Character regionObject in tree.SearchActors(SearchFlags.Characters))
{
SMSG_JOBCHANGED spkt = new SMSG_JOBCHANGED();
spkt.SessionId = regionObject.id;
spkt.SourceActor = this.character.id;
spkt.Job = cpkt.Job;
regionObject.client.Send((byte[])spkt);
if (regionObject.id != this.character.id)
{
if (IsActiveWeapon)
{
uint auge = (character.FindRequiredRootSkill(selectedWeapon.Info.weapon_skill)) ? selectedWeapon._augeskill : 0;
SMSG_SHOWWEAPON spkt2 = new SMSG_SHOWWEAPON();
spkt2.ActorID = this.character.id;
spkt2.AugeID = auge;
spkt2.SessionId = regionObject.id;
regionObject.client.Send((byte[])spkt2);
}
foreach (byte i in EnabledEquipment)
{
Rag2Item item = this.character.Equipment[i];
SMSG_CHANGEEQUIPMENT spkt2 = new SMSG_CHANGEEQUIPMENT();
spkt2.SessionId = regionObject.id;
spkt2.ActorID = this.character.id;
spkt2.Slot = i;
spkt2.ItemID = item.info.item;
spkt2.Dye = item.dyecolor;
regionObject.client.Send((byte[])spkt2);
}
foreach (byte i in DisabledEquipment)
{
SMSG_CHANGEEQUIPMENT spkt2 = new SMSG_CHANGEEQUIPMENT();
spkt2.SessionId = regionObject.id;
spkt2.ActorID = this.character.id;
spkt2.Slot = i;
spkt2.ItemID = 0;
spkt2.Dye = 0;
regionObject.client.Send((byte[])spkt2);
}
}
}
}
#endregion Refresh Appereance
#region Refresh Party
{
//Process party members
SMSG_PARTYMEMBERJOB spkt = new SMSG_PARTYMEMBERJOB();
spkt.Job = cpkt.Job;
spkt.SessionId = this.character.id;
spkt.ActorId = this.character.id;
spkt.Index = 1;
SMSG_PARTYMEMBERJLVL spkt2 = new SMSG_PARTYMEMBERJLVL();
spkt2.Jvl = this.character.jlvl;
spkt2.ActorId = this.character.id;
spkt2.Index = 1;
if (this.character.sessionParty != null)
{
foreach (Character target in this.character.sessionParty.GetCharacters())
{
//Send over Job change
spkt.SessionId = target.id;
target.client.Send((byte[])spkt);
//Send over jlvl change
spkt2.SessionId = target.id;
target.client.Send((byte[])spkt2);
}
}
}
#endregion Refresh Party
#region Refresh LifeCycle
Tasks.LifeCycle.Update(this.character);
#endregion Refresh LifeCycle
}
/// <summary>
///
/// </summary>
/// <param name="cpkt"></param>
private void CM_CHARACTER_EXPENSIVESFORJOBCHANGE(CMSG_SELECTJOB cpkt)
{
//Get's the job change collection
JobChangeCollection collection = this.character.Tag as JobChangeCollection;
if (collection != null)
{
SMSG_SENDMONEYFORJOB spkt = new SMSG_SENDMONEYFORJOB();
spkt.SessionId = this.character.id;
spkt.Zeny = collection.GetJobTrasferFee(cpkt.Job);
this.Send((byte[])spkt);
}
/*
int Price = 200;
try
{
Price += (character.CharacterJobLevel[cpkt.Job] * 300);
List<uint> Skills = Singleton.Database.GetJobSpeciaficSkills(this.character, cpkt.Job);
for (int i = 0; i < Skills.Count; i++)
{
int Lvl = (int)(Skills[i] % 100);
Price += ((Lvl - 1) * 100);
}
}
finally
{
SMSG_SENDMONEYFORJOB spkt = new SMSG_SENDMONEYFORJOB();
spkt.SessionId = this.character.id;
spkt.Zeny = (uint)Price;
this.Send((byte[])spkt);
}*/
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
namespace Apache.Ignite.Core.Tests.Cache.Query
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Queries tests.
/// </summary>
public class CacheQueriesTest
{
/** Grid count. */
private const int GridCnt = 2;
/** Cache name. */
private const string CacheName = "cache";
/** Path to XML configuration. */
private const string CfgPath = "Config\\cache-query.xml";
/** Maximum amount of items in cache. */
private const int MaxItemCnt = 100;
/// <summary>
/// Fixture setup.
/// </summary>
[TestFixtureSetUp]
public void StartGrids()
{
for (int i = 0; i < GridCnt; i++)
{
Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
NameMapper = GetNameMapper()
},
SpringConfigUrl = CfgPath,
IgniteInstanceName = "grid-" + i
});
}
}
/// <summary>
/// Gets the name mapper.
/// </summary>
protected virtual IBinaryNameMapper GetNameMapper()
{
return new BinaryBasicNameMapper {IsSimpleName = false};
}
/// <summary>
/// Fixture teardown.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
[TearDown]
public void AfterTest()
{
var cache = Cache();
for (int i = 0; i < GridCnt; i++)
{
cache.Clear();
Assert.IsTrue(cache.IsEmpty());
}
TestUtils.AssertHandleRegistryIsEmpty(300,
Enumerable.Range(0, GridCnt).Select(x => Ignition.GetIgnite("grid-" + x)).ToArray());
Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Gets the ignite.
/// </summary>
private static IIgnite GetIgnite()
{
return Ignition.GetIgnite("grid-0");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static ICache<int, QueryPerson> Cache()
{
return GetIgnite().GetCache<int, QueryPerson>(CacheName);
}
/// <summary>
/// Test arguments validation for SQL queries.
/// </summary>
[Test]
public void TestValidationSql()
{
#pragma warning disable 618
// 1. No sql.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new SqlQuery((string)null, "age >= 50")); });
#pragma warning restore 618
}
/// <summary>
/// Test arguments validation for SQL fields queries.
/// </summary>
[Test]
public void TestValidationSqlFields()
{
// 1. No sql.
Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlFieldsQuery(null)); });
}
/// <summary>
/// Test arguments validation for TEXT queries.
/// </summary>
[Test]
public void TestValidationText()
{
// 1. No text.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery(typeof(QueryPerson), null)); });
// 2. No type.
Assert.Throws<ArgumentException>(() =>
{ Cache().Query(new TextQuery((string)null, "Ivanov")); });
}
/// <summary>
/// Cursor tests.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
public void TestCursor()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(1, new QueryPerson("Petrov", 40));
Cache().Put(1, new QueryPerson("Sidorov", 50));
#pragma warning disable 618
SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20");
#pragma warning restore 618
// 1. Test GetAll().
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetAll();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
// 2. Test GetEnumerator.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); });
Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); });
}
}
/// <summary>
/// Test enumerator.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "UnusedVariable")]
public void TestEnumerator()
{
#pragma warning disable 618
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
Cache().Put(4, new QueryPerson("Unknown", 60));
// 1. Empty result set.
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor =
Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100")))
{
IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator();
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.IsFalse(e.MoveNext());
Assert.Throws<InvalidOperationException>(() =>
{ ICacheEntry<int, QueryPerson> entry = e.Current; });
Assert.Throws<NotSupportedException>(() => e.Reset());
e.Dispose();
}
SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60");
Assert.AreEqual(QueryBase.DefaultPageSize, qry.PageSize);
// 2. Page size is bigger than result set.
qry.PageSize = 4;
CheckEnumeratorQuery(qry);
// 3. Page size equal to result set.
qry.PageSize = 3;
CheckEnumeratorQuery(qry);
// 4. Page size if less than result set.
qry.PageSize = 2;
CheckEnumeratorQuery(qry);
#pragma warning restore 618
}
/// <summary>
/// Test SQL query arguments passing.
/// </summary>
[Test]
public void TestSqlQueryArguments()
{
#pragma warning disable 618
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (var cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50)))
{
foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll())
Assert.IsTrue(entry.Key == 1 || entry.Key == 2);
}
#pragma warning restore 618
}
/// <summary>
/// Test SQL fields query arguments passing.
/// </summary>
[Test]
public void TestSqlFieldsQueryArguments()
{
Cache().Put(1, new QueryPerson("Ivanov", 30));
Cache().Put(2, new QueryPerson("Petrov", 40));
Cache().Put(3, new QueryPerson("Sidorov", 50));
// 1. Empty result set.
using (var cursor = Cache().Query(new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50)))
{
foreach (var entry in cursor.GetAll())
Assert.IsTrue((int) entry[0] < 50);
}
}
/// <summary>
/// Check query result for enumerator test.
/// </summary>
/// <param name="qry">QUery.</param>
#pragma warning disable 618
private void CheckEnumeratorQuery(SqlQuery qry)
{
using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry))
{
bool first = false;
bool second = false;
bool third = false;
foreach (var entry in cursor)
{
if (entry.Key == 1)
{
first = true;
Assert.AreEqual("Ivanov", entry.Value.Name);
Assert.AreEqual(30, entry.Value.Age);
}
else if (entry.Key == 2)
{
second = true;
Assert.AreEqual("Petrov", entry.Value.Name);
Assert.AreEqual(40, entry.Value.Age);
}
else if (entry.Key == 3)
{
third = true;
Assert.AreEqual("Sidorov", entry.Value.Name);
Assert.AreEqual(50, entry.Value.Age);
}
else
Assert.Fail("Unexpected value: " + entry);
}
Assert.IsTrue(first && second && third);
}
}
#pragma warning restore 618
/// <summary>
/// Check SQL query.
/// </summary>
[Test]
public void TestSqlQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary,
[Values(true, false)] bool distrJoin)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x < 50);
// 2. Validate results.
#pragma warning disable 618
var qry = new SqlQuery(typeof(QueryPerson), "age < 50", loc)
{
EnableDistributedJoins = distrJoin,
ReplicatedOnly = false,
Timeout = TimeSpan.FromSeconds(3)
};
#pragma warning restore 618
Assert.AreEqual(string.Format("SqlQuery [Sql=age < 50, Arguments=[], Local={0}, " +
"PageSize=1024, EnableDistributedJoins={1}, Timeout={2}, " +
"ReplicatedOnly=False]", loc, distrJoin, qry.Timeout), qry.ToString());
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check SQL fields query.
/// </summary>
[Test]
public void TestSqlFieldsQuery([Values(true, false)] bool loc, [Values(true, false)] bool distrJoin,
[Values(true, false)] bool enforceJoinOrder, [Values(true, false)] bool lazy)
{
int cnt = MaxItemCnt;
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, cnt, x => x < 50);
// 2. Validate results.
var qry = new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50")
{
EnableDistributedJoins = distrJoin,
EnforceJoinOrder = enforceJoinOrder,
Colocated = !distrJoin,
#pragma warning disable 618
ReplicatedOnly = false,
#pragma warning restore 618
Local = loc,
Timeout = TimeSpan.FromSeconds(2),
Lazy = lazy
};
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor.GetAll())
{
Assert.AreEqual(2, entry.Count);
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
Assert.AreEqual(new[] {"NAME", "AGE"}, cursor.FieldNames);
}
// Test old API as well.
#pragma warning disable 618
using (var cursor = cache.QueryFields(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
foreach (var entry in cursor)
{
Assert.AreEqual(entry[0].ToString(), entry[1].ToString());
exp0.Remove((int)entry[1]);
}
Assert.AreEqual(0, exp0.Count);
}
#pragma warning restore 618
}
/// <summary>
/// Tests that query configuration propagates from Spring XML correctly.
/// </summary>
[Test]
public void TestQueryConfiguration()
{
var qe = Cache().GetConfiguration().QueryEntities.Single();
Assert.AreEqual(typeof(QueryPerson).FullName, qe.ValueTypeName);
var age = qe.Fields.First();
Assert.AreEqual("age", age.Name);
Assert.AreEqual(typeof(int), age.FieldType);
Assert.IsFalse(age.IsKeyField);
var name = qe.Fields.Last();
Assert.AreEqual("name", name.Name);
Assert.AreEqual(typeof(string), name.FieldType);
Assert.IsFalse(name.IsKeyField);
var textIdx = qe.Indexes.First();
Assert.AreEqual(QueryIndexType.FullText, textIdx.IndexType);
Assert.AreEqual("name", textIdx.Fields.Single().Name);
Assert.AreEqual(QueryIndex.DefaultInlineSize, textIdx.InlineSize);
var sqlIdx = qe.Indexes.Last();
Assert.AreEqual(QueryIndexType.Sorted, sqlIdx.IndexType);
Assert.AreEqual("age", sqlIdx.Fields.Single().Name);
Assert.AreEqual(2345, sqlIdx.InlineSize);
}
/// <summary>
/// Check text query.
/// </summary>
[Test]
public void TestTextQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary)
{
var cache = Cache();
// 1. Populate cache with data, calculating expected count in parallel.
var exp = PopulateCache(cache, loc, MaxItemCnt, x => x.ToString().StartsWith("1"));
// 2. Validate results.
var qry = new TextQuery(typeof(QueryPerson), "1*", loc);
ValidateQueryResults(cache, qry, exp, keepBinary);
}
/// <summary>
/// Check scan query.
/// </summary>
[Test]
public void TestScanQuery([Values(true, false)] bool loc)
{
CheckScanQuery<QueryPerson>(loc, false);
}
/// <summary>
/// Check scan query in binary mode.
/// </summary>
[Test]
public void TestScanQueryBinary([Values(true, false)] bool loc)
{
CheckScanQuery<IBinaryObject>(loc, true);
}
/// <summary>
/// Check scan query with partitions.
/// </summary>
[Test]
public void TestScanQueryPartitions([Values(true, false)] bool loc)
{
CheckScanQueryPartitions<QueryPerson>(loc, false);
}
/// <summary>
/// Check scan query with partitions in binary mode.
/// </summary>
[Test]
public void TestScanQueryPartitionsBinary([Values(true, false)] bool loc)
{
CheckScanQueryPartitions<IBinaryObject>(loc, true);
}
/// <summary>
/// Tests that query attempt on non-indexed cache causes an exception.
/// </summary>
[Test]
public void TestIndexingDisabledError()
{
var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>("nonindexed_cache");
// Text query.
var err = Assert.Throws<IgniteException>(() => cache.Query(new TextQuery(typeof(QueryPerson), "1*")));
Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " +
"Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message);
// SQL query.
#pragma warning disable 618
err = Assert.Throws<IgniteException>(() => cache.Query(new SqlQuery(typeof(QueryPerson), "age < 50")));
#pragma warning restore 618
Assert.AreEqual("Failed to find SQL table for type: QueryPerson", err.Message);
}
/// <summary>
/// Check scan query.
/// </summary>
/// <param name="loc">Local query flag.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void CheckScanQuery<TV>(bool loc, bool keepBinary)
{
var cache = Cache();
int cnt = MaxItemCnt;
// No predicate
var exp = PopulateCache(cache, loc, cnt, x => true);
var qry = new ScanQuery<int, TV>();
ValidateQueryResults(cache, qry, exp, keepBinary);
// Serializable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Binarizable
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new BinarizableScanQueryFilter<TV>());
ValidateQueryResults(cache, qry, exp, keepBinary);
// Invalid
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new InvalidScanQueryFilter<TV>());
Assert.Throws<BinaryObjectException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
// Exception
exp = PopulateCache(cache, loc, cnt, x => x < 50);
qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true});
var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepBinary));
Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message);
}
/// <summary>
/// Checks scan query with partitions.
/// </summary>
/// <param name="loc">Local query flag.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private void CheckScanQueryPartitions<TV>(bool loc, bool keepBinary)
{
StopGrids();
StartGrids();
var cache = Cache();
int cnt = MaxItemCnt;
var aff = cache.Ignite.GetAffinity(CacheName);
var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV> { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
// Partitions with predicate
exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow)
for (var part = 0; part < aff.Partitions; part++)
{
//var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys
var exp0 = new HashSet<int>();
foreach (var x in exp)
if (aff.GetPartition(x) == part)
exp0.Add(x);
var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part };
ValidateQueryResults(cache, qry, exp0, keepBinary);
}
}
/// <summary>
/// Tests custom schema name.
/// </summary>
[Test]
public void TestCustomSchema()
{
var doubles = GetIgnite().GetOrCreateCache<int, double>(new CacheConfiguration("doubles",
new QueryEntity(typeof(int), typeof(double))));
var strings = GetIgnite().GetOrCreateCache<int, string>(new CacheConfiguration("strings",
new QueryEntity(typeof(int), typeof(string))));
doubles[1] = 36.6;
strings[1] = "foo";
// Default schema.
var res = doubles.Query(new SqlFieldsQuery(
"select S._val from double as D join \"strings\".string as S on S._key = D._key"))
.Select(x => (string) x[0])
.Single();
Assert.AreEqual("foo", res);
// Custom schema.
res = doubles.Query(new SqlFieldsQuery(
"select S._val from \"doubles\".double as D join string as S on S._key = D._key")
{
Schema = strings.Name
})
.Select(x => (string)x[0])
.Single();
Assert.AreEqual("foo", res);
}
/// <summary>
/// Tests the distributed joins flag.
/// </summary>
[Test]
public void TestDistributedJoins()
{
var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("replicatedCache")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[] {new QueryField("age", "int")}
}
}
});
const int count = 100;
cache.PutAll(Enumerable.Range(0, count).ToDictionary(x => x, x => new QueryPerson("Name" + x, x)));
// Test non-distributed join: returns partial results
var sql = "select T0.Age from QueryPerson as T0 " +
"inner join QueryPerson as T1 on ((? - T1.Age - 1) = T0._key)";
var res = cache.Query(new SqlFieldsQuery(sql, count)).GetAll().Distinct().Count();
Assert.Greater(res, 0);
Assert.Less(res, count);
// Test distributed join: returns complete results
res = cache.Query(new SqlFieldsQuery(sql, count) {EnableDistributedJoins = true})
.GetAll().Distinct().Count();
Assert.AreEqual(count, res);
}
/// <summary>
/// Tests the get configuration.
/// </summary>
[Test]
public void TestGetConfiguration()
{
var entity = Cache().GetConfiguration().QueryEntities.Single();
var ageField = entity.Fields.Single(x => x.Name == "age");
Assert.AreEqual(typeof(int), ageField.FieldType);
Assert.IsFalse(ageField.NotNull);
Assert.IsFalse(ageField.IsKeyField);
var nameField = entity.Fields.Single(x => x.Name == "name");
Assert.AreEqual(typeof(string), nameField.FieldType);
Assert.IsTrue(nameField.NotNull);
Assert.IsFalse(nameField.IsKeyField);
}
/// <summary>
/// Tests custom key and value field names.
/// </summary>
[Test]
public void TestCustomKeyValueFieldNames()
{
// Check select * with default config - does not include _key, _val.
var cache = Cache();
cache[1] = new QueryPerson("Joe", 48);
var row = cache.Query(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0];
Assert.AreEqual(2, row.Count);
Assert.AreEqual(48, row[0]);
Assert.AreEqual("Joe", row[1]);
// Check select * with custom names - fields are included.
cache = GetIgnite().GetOrCreateCache<int, QueryPerson>(
new CacheConfiguration("customKeyVal")
{
QueryEntities = new[]
{
new QueryEntity(typeof(int), typeof(QueryPerson))
{
Fields = new[]
{
new QueryField("age", "int"),
new QueryField("FullKey", "int"),
new QueryField("FullVal", "QueryPerson")
},
KeyFieldName = "FullKey",
ValueFieldName = "FullVal"
}
}
});
cache[1] = new QueryPerson("John", 33);
row = cache.Query(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0];
Assert.AreEqual(3, row.Count);
Assert.AreEqual(33, row[0]);
Assert.AreEqual(1, row[1]);
var person = (QueryPerson) row[2];
Assert.AreEqual("John", person.Name);
// Check explicit select.
row = cache.Query(new SqlFieldsQuery("select FullKey from QueryPerson")).GetAll()[0];
Assert.AreEqual(1, row[0]);
}
/// <summary>
/// Tests query timeouts.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestSqlQueryTimeout()
{
var cache = Cache();
PopulateCache(cache, false, 30000, x => true);
#pragma warning disable 618
var sqlQry = new SqlQuery(typeof(QueryPerson), "WHERE age < 2000")
{
Timeout = TimeSpan.FromMilliseconds(1)
};
#pragma warning restore 618
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<CacheException>(() => cache.Query(sqlQry).ToArray());
Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing."));
}
/// <summary>
/// Tests fields query timeouts.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestSqlFieldsQueryTimeout()
{
var cache = Cache();
PopulateCache(cache, false, 20000, x => true);
var fieldsQry = new SqlFieldsQuery("SELECT * FROM QueryPerson WHERE age < 5000 AND name like '%0%'")
{
Timeout = TimeSpan.FromMilliseconds(3)
};
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
var ex = Assert.Throws<CacheException>(() => cache.Query(fieldsQry).ToArray());
Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing."));
}
/// <summary>
/// Tests the FieldNames property.
/// </summary>
[Test]
public void TestFieldNames()
{
var cache = Cache();
PopulateCache(cache, false, 5, x => true);
// Get before iteration.
var qry = new SqlFieldsQuery("SELECT * FROM QueryPerson");
var cur = cache.Query(qry);
var names = cur.FieldNames;
Assert.AreEqual(new[] {"AGE", "NAME" }, names);
cur.Dispose();
Assert.AreSame(names, cur.FieldNames);
Assert.Throws<NotSupportedException>(() => cur.FieldNames.Add("x"));
// Custom order, key-val, get after iteration.
qry.Sql = "SELECT NAME, _key, AGE, _val FROM QueryPerson";
cur = cache.Query(qry);
cur.GetAll();
Assert.AreEqual(new[] { "NAME", "_KEY", "AGE", "_VAL" }, cur.FieldNames);
// Get after disposal.
qry.Sql = "SELECT 1, AGE FROM QueryPerson";
cur = cache.Query(qry);
cur.Dispose();
Assert.AreEqual(new[] { "1", "AGE" }, cur.FieldNames);
}
/// <summary>
/// Validates the query results.
/// </summary>
/// <param name="cache">Cache.</param>
/// <param name="qry">Query.</param>
/// <param name="exp">Expected keys.</param>
/// <param name="keepBinary">Keep binary flag.</param>
private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp,
bool keepBinary)
{
if (keepBinary)
{
var cache0 = cache.WithKeepBinary<int, IBinaryObject>();
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache0.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name"));
Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age"));
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
else
{
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor.GetAll())
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
using (var cursor = cache.Query(qry))
{
HashSet<int> exp0 = new HashSet<int>(exp);
var all = new List<ICacheEntry<int, object>>();
foreach (var entry in cursor)
{
all.Add(entry);
Assert.AreEqual(entry.Key.ToString(), entry.Value.Name);
Assert.AreEqual(entry.Key, entry.Value.Age);
exp0.Remove(entry.Key);
}
AssertMissingExpectedKeys(exp0, cache, all);
}
}
}
/// <summary>
/// Asserts that all expected entries have been received.
/// </summary>
private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache,
IList<ICacheEntry<int, object>> all)
{
if (exp.Count == 0)
return;
var sb = new StringBuilder();
var aff = cache.Ignite.GetAffinity(cache.Name);
foreach (var key in exp)
{
var part = aff.GetPartition(key);
sb.AppendFormat(
"Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ",
key, cache.Get(key) != null, part);
var partNodes = aff.MapPartitionToPrimaryAndBackups(part);
foreach (var node in partNodes)
sb.Append(node).Append(" ");
sb.AppendLine(";");
}
sb.Append("Returned keys: ");
foreach (var e in all)
sb.Append(e.Key).Append(" ");
sb.AppendLine(";");
Assert.Fail(sb.ToString());
}
/// <summary>
/// Populates the cache with random entries and returns expected results set according to filter.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="cnt">Amount of cache entries to create.</param>
/// <param name="loc">Local query flag.</param>
/// <param name="expectedEntryFilter">The expected entry filter.</param>
/// <returns>Expected results set.</returns>
private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt,
Func<int, bool> expectedEntryFilter)
{
var rand = new Random();
for (var i = 0; i < cnt; i++)
{
var val = rand.Next(cnt);
cache.Put(val, new QueryPerson(val.ToString(), val));
}
var entries = loc
? cache.GetLocalEntries(CachePeekMode.Primary)
: cache;
return new HashSet<int>(entries.Select(x => x.Key).Where(expectedEntryFilter));
}
}
/// <summary>
/// Person.
/// </summary>
public class QueryPerson
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="age">Age.</param>
public QueryPerson(string name, int age)
{
Name = name;
Age = age % 2000;
Birthday = DateTime.UtcNow.AddYears(-Age);
}
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Age.
/// </summary>
public int Age { get; set; }
/// <summary>
/// Gets or sets the birthday.
/// </summary>
[QuerySqlField] // Enforce Timestamp serialization
public DateTime Birthday { get; set; }
}
/// <summary>
/// Query filter.
/// </summary>
[Serializable]
public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV>
{
// Error message
public const string ErrMessage = "Error in ScanQueryFilter.Invoke";
// Error flag
public bool ThrowErr { get; set; }
// Injection test
[InstanceResource]
public IIgnite Ignite { get; set; }
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, TV> entry)
{
Assert.IsNotNull(Ignite);
if (ThrowErr)
throw new Exception(ErrMessage);
return entry.Key < 50;
}
}
/// <summary>
/// binary query filter.
/// </summary>
public class BinarizableScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
/** <inheritdoc /> */
public void WriteBinary(IBinaryWriter writer)
{
var w = writer.GetRawWriter();
w.WriteBoolean(ThrowErr);
}
/** <inheritdoc /> */
public void ReadBinary(IBinaryReader reader)
{
var r = reader.GetRawReader();
ThrowErr = r.ReadBoolean();
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
}
| |
// System.IO.BufferedStream
// Updated to work with .NET Micro Framework
// Changes by:
// Chris Taylor (taylorza) - 26/08/2012
// System.IO.BufferedStream
//
// Author:
// Matt Kimball (matt@kimball.net)
// Ville Palo <vi64pa@kolumbus.fi>
//
// Copyright (C) 2004 Novell (http://www.novell.com)
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
namespace IngenuityMicro.Hardware.Silicon
{
public sealed class BufferedStream : Stream
{
Stream m_stream;
byte[] m_buffer;
int m_buffer_pos;
int m_buffer_read_ahead;
bool m_buffer_reading;
private bool disposed = false;
public BufferedStream(Stream stream)
: this(stream, 4096)
{
}
public BufferedStream(Stream stream, int buffer_size)
{
if (stream == null)
throw new ArgumentNullException("stream");
// LAMESPEC: documented as < 0
if (buffer_size <= 0)
throw new ArgumentOutOfRangeException("buffer_size", "<= 0");
if (!stream.CanRead && !stream.CanWrite)
{
throw new ObjectDisposedException("Cannot access a closed Stream.");
}
m_stream = stream;
m_buffer = new byte[buffer_size];
}
public override bool CanRead
{
get
{
return m_stream.CanRead;
}
}
public override bool CanWrite
{
get
{
return m_stream.CanWrite;
}
}
public override bool CanSeek
{
get
{
return m_stream.CanSeek;
}
}
public override long Length
{
get
{
Flush();
return m_stream.Length;
}
}
public override long Position
{
get
{
CheckObjectDisposedException();
return m_stream.Position - m_buffer_read_ahead + m_buffer_pos;
}
set
{
if (value < Position && (Position - value <= m_buffer_pos) && m_buffer_reading)
{
m_buffer_pos -= (int)(Position - value);
}
else if (value > Position && (value - Position < m_buffer_read_ahead - m_buffer_pos) && m_buffer_reading)
{
m_buffer_pos += (int)(value - Position);
}
else
{
Flush();
m_stream.Position = value;
}
}
}
public override void Close()
{
try
{
if (m_buffer != null)
Flush();
}
finally
{
m_stream.Close();
m_buffer = null;
disposed = true;
}
}
public override void Flush()
{
CheckObjectDisposedException();
if (m_buffer_reading)
{
if (CanSeek)
m_stream.Position = Position;
}
else if (m_buffer_pos > 0)
{
m_stream.Write(m_buffer, 0, m_buffer_pos);
}
m_buffer_read_ahead = 0;
m_buffer_pos = 0;
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckObjectDisposedException();
if (!CanSeek)
{
throw new NotSupportedException("Non seekable stream.");
}
Flush();
return m_stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
CheckObjectDisposedException();
if (value < 0)
throw new ArgumentOutOfRangeException("value must be positive");
if (!m_stream.CanWrite && !m_stream.CanSeek)
throw new NotSupportedException("the stream cannot seek nor write.");
if ((m_stream == null) || (!m_stream.CanRead && !m_stream.CanWrite))
throw new IOException("the stream is not open");
m_stream.SetLength(value);
if (Position > value)
Position = value;
}
public override int ReadByte()
{
CheckObjectDisposedException();
byte[] b = new byte[1];
if (Read(b, 0, 1) == 1)
{
return b[0];
}
else
{
return -1;
}
}
public override void WriteByte(byte value)
{
CheckObjectDisposedException();
byte[] b = new byte[1];
b[0] = value;
Write(b, 0, 1);
}
public override int Read(byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException("array");
CheckObjectDisposedException();
if (!m_stream.CanRead)
{
throw new NotSupportedException("Cannot read from stream");
}
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException("count", "< 0");
// re-ordered to avoid possible integer overflow
if (array.Length - offset < count)
throw new ArgumentException("array.Length - offset < count");
if (!m_buffer_reading)
{
Flush();
m_buffer_reading = true;
}
if (count <= m_buffer_read_ahead - m_buffer_pos)
{
Array.Copy(m_buffer, m_buffer_pos, array, offset, count);
m_buffer_pos += count;
if (m_buffer_pos == m_buffer_read_ahead)
{
m_buffer_pos = 0;
m_buffer_read_ahead = 0;
}
return count;
}
int ret = m_buffer_read_ahead - m_buffer_pos;
Array.Copy(m_buffer, m_buffer_pos, array, offset, ret);
m_buffer_pos = 0;
m_buffer_read_ahead = 0;
offset += ret;
count -= ret;
if (count >= m_buffer.Length)
{
ret += m_stream.Read(array, offset, count);
}
else
{
m_buffer_read_ahead = m_stream.Read(m_buffer, 0, m_buffer.Length);
if (count < m_buffer_read_ahead)
{
Array.Copy(m_buffer, 0, array, offset, count);
m_buffer_pos = count;
ret += count;
}
else
{
Array.Copy(m_buffer, 0, array, offset, m_buffer_read_ahead);
ret += m_buffer_read_ahead;
m_buffer_read_ahead = 0;
}
}
return ret;
}
public override void Write(byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException("array");
CheckObjectDisposedException();
if (!m_stream.CanWrite)
{
throw new NotSupportedException("Cannot write to stream");
}
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", "< 0");
if (count < 0)
throw new ArgumentOutOfRangeException("count", "< 0");
// avoid possible integer overflow
if (array.Length - offset < count)
throw new ArgumentException("array.Length - offset < count");
if (m_buffer_reading)
{
Flush();
m_buffer_reading = false;
}
// reordered to avoid possible integer overflow
if (m_buffer_pos >= m_buffer.Length - count)
{
Flush();
m_stream.Write(array, offset, count);
}
else
{
Array.Copy(array, offset, m_buffer, m_buffer_pos, count);
m_buffer_pos += count;
}
}
private void CheckObjectDisposedException()
{
if (disposed)
{
throw new ObjectDisposedException("Stream is closed");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.