context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Umb.CastleWindsor;
using Glass.Mapper.Umb.Configuration;
using Glass.Mapper.Umb.DataMappers;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Services;
namespace Glass.Mapper.Umb.Integration.DataMappers
{
[TestFixture]
public class UmbracoInfoMapperFixture
{
private PetaPocoUnitOfWorkProvider _unitOfWork;
private RepositoryFactory _repoFactory;
#region Method - MapToProperty
[Test]
[Sequential]
public void MapToProperty_UmbracoInfoType_GetsExpectedValueFromUmbraco(
[Values(
//UmbracoInfoType.Url,
UmbracoInfoType.ContentTypeAlias,
UmbracoInfoType.ContentTypeName,
UmbracoInfoType.Name,
UmbracoInfoType.Creator
)] UmbracoInfoType type,
[Values(
//"target", //Url
"TestType", //ContentTypeAlias
"Test Type", //ContentTypeName
"Target", //Name
"admin" //Creator
)] object expected
)
{
//Assign
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
Console.WriteLine(type);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
[ExpectedException(typeof(MapperException))]
public void MapToProperty_UmbracoInfoTypeNotSet_ThrowsException()
{
//Assign
UmbracoInfoType type = UmbracoInfoType.NotSet;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
//No asserts expect exception
}
[Test]
public void MapToProperty_UmbracoInfoTypeVersion_ReturnsVersionIdAsGuid()
{
//Assign
var type = UmbracoInfoType.Version;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.Version;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_UmbracoInfoTypePath_ReturnsPathAsString()
{
//Assign
var type = UmbracoInfoType.Path;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.Path;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_UmbracoInfoTypeCreateDate_ReturnsCreateDateAsDateTime()
{
//Assign
var type = UmbracoInfoType.CreateDate;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.CreateDate;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_UmbracoInfoTypeUpdateDate_ReturnsUpdateDateAsDateTime()
{
//Assign
var type = UmbracoInfoType.UpdateDate;
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var expected = content.UpdateDate;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var dataContext = new UmbracoDataMappingContext(null, content, null, false);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
#endregion
#region Method - MapToCms
[Test]
public void MapToCms_SavingName_UpdatesTheItemName()
{
//Assign
var type = UmbracoInfoType.Name;
var expected = "new name";
var mapper = new UmbracoInfoMapper();
var config = new UmbracoInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null, config));
var contentService = new ContentService(_unitOfWork, _repoFactory);
var content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
var oldName = content.Name;
Assert.IsNotNull(content, "Content is null, check in Umbraco that item exists");
var context = Context.Create(DependencyResolver.CreateStandardResolver());
var dataContext = new UmbracoDataMappingContext(null, content, new UmbracoService(contentService, context), false);
dataContext.PropertyValue = expected;
string actual = string.Empty;
//Act
mapper.MapToCms(dataContext);
content = contentService.GetById(new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}"));
actual = content.Name;
//Assert
Assert.AreEqual(expected, actual);
content.Name = oldName;
contentService.Save(content);
}
#endregion
#region Stubs
[TestFixtureSetUp]
public void CreateStub()
{
string name = "Target";
string contentTypeAlias = "TestType";
string contentTypeName = "Test Type";
_unitOfWork = Global.CreateUnitOfWork();
_repoFactory = new RepositoryFactory();
var contentService = new ContentService(_unitOfWork, _repoFactory);
var contentTypeService = new ContentTypeService(_unitOfWork, _repoFactory,
new ContentService(_unitOfWork),
new MediaService(_unitOfWork, _repoFactory));
var contentType = new ContentType(-1);
contentType.Name = contentTypeName;
contentType.Alias = contentTypeAlias;
contentType.Thumbnail = string.Empty;
contentTypeService.Save(contentType);
Assert.Greater(contentType.Id, 0);
var content = new Content(name, -1, contentType);
content.Key = new Guid("{FB6A8073-48B4-4B85-B80C-09CBDECC27C9}");
contentService.Save(content);
contentService.Publish(content);
}
public class Stub
{
public Guid TemplateId { get; set; }
}
#endregion
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* 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 holder is ArangoDB GmbH, Cologne, Germany
*/
namespace VelocyPack
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using VelocyPack.Exceptions;
using VelocyPack.Internal;
using VelocyPack.Internal.Util;
using VelocyPack.Migration.Util;
using NumberUtil = VelocyPack.Internal.Util.NumberUtil;
using ArrayUtil = Migration.Util.ArrayUtil;
/// <author>Mark - mark at arangodb.com</author>
public class VPackSlice
{
public static readonly VPackAttributeTranslator attributeTranslator = new VPackAttributeTranslatorImpl();
private readonly byte[] vpack;
private readonly int start;
protected internal VPackSlice()
: this(new byte[] { 0x00 }, 0)
{
}
public VPackSlice(byte[] vpack)
: this(vpack, 0)
{
}
public VPackSlice(byte[] vpack, int start)
{
this.vpack = vpack;
this.start = start;
}
public virtual byte Head
{
get
{
return this.vpack[this.start];
}
}
public virtual byte[] Buffer
{
get
{
return this.vpack;
}
}
public virtual int Start
{
get
{
return this.start;
}
}
internal virtual ValueType Type()
{
return ValueTypeUtil.Get(this.Head);
}
internal int GetLength()
{
return ValueLengthUtil.Get(this.Head) - 1;
}
internal bool IsType(ValueType type)
{
return Type() == type;
}
public virtual bool IsNone
{
get
{
return this.IsType(ValueType.NONE);
}
}
public virtual bool IsNull
{
get
{
return this.IsType(ValueType.NULL);
}
}
public virtual bool IsIllegal
{
get
{
return this.IsType(ValueType.ILLEGAL);
}
}
public virtual bool IsBoolean
{
get
{
return this.IsType(ValueType.BOOL);
}
}
public virtual bool IsTrue
{
get
{
return this.Head == 0x1a;
}
}
public virtual bool IsFalse
{
get
{
return this.Head == 0x19;
}
}
public virtual bool IsArray
{
get
{
return this.IsType(ValueType.ARRAY);
}
}
public virtual bool IsObject
{
get
{
return this.IsType(ValueType.OBJECT);
}
}
public virtual bool IsDouble
{
get
{
return this.IsType(ValueType.DOUBLE);
}
}
public virtual bool IsDate
{
get
{
return this.IsType(ValueType.UTC_DATE);
}
}
public virtual bool IsExternal
{
get
{
return this.IsType(ValueType.EXTERNAL);
}
}
public virtual bool IsMinKey
{
get
{
return this.IsType(ValueType.MIN_KEY);
}
}
public virtual bool IsMaxKey
{
get
{
return this.IsType(ValueType.MAX_KEY);
}
}
public virtual bool IsInt
{
get
{
return this.IsType(ValueType.INT);
}
}
public virtual bool IsUInt
{
get
{
return this.IsType(ValueType.UINT);
}
}
public virtual bool IsSmallInt
{
get
{
return this.IsType(ValueType.SMALLINT);
}
}
public virtual bool IsInteger
{
get
{
return this.IsInt || this.IsUInt || this.IsSmallInt;
}
}
public virtual bool IsNumber
{
get
{
return this.IsInteger || this.IsDouble;
}
}
public virtual bool IsString
{
get
{
return this.IsType(ValueType.STRING);
}
}
public virtual bool IsBinary
{
get
{
return this.IsType(ValueType.BINARY);
}
}
public virtual bool IsBcd
{
get
{
return this.IsType(ValueType.BCD);
}
}
public virtual bool IsCustom
{
get
{
return this.IsType(ValueType.CUSTOM);
}
}
public virtual bool AsBoolean
{
get
{
if (!this.IsBoolean)
{
throw new VPackValueTypeException(ValueType.BOOL);
}
return this.IsTrue;
}
}
public virtual double AsDouble
{
get
{
if (!this.IsDouble)
{
throw new VPackValueTypeException(ValueType.DOUBLE);
}
return this.AsDoubleUnchecked;
}
}
private double AsDoubleUnchecked
{
get
{
return NumberUtil.ToDouble(this.vpack, this.start + 1, this.GetLength());
}
}
private long SmallInt
{
get
{
byte head = Head;
long smallInt;
if (head >= 0x30 && (sbyte)head <= 0x39)
{
smallInt = head - 0x30;
}
else
{
/* if (head >= 0x3a && head <= 0x3f) */
smallInt = head - 0x3a - 6;
}
return smallInt;
}
}
private long Int
{
get
{
return NumberUtil.ToLong(this.vpack, this.start + 1, this.GetLength());
}
}
private long UInt
{
get
{
return NumberUtil.ToLong(this.vpack, this.start + 1, this.GetLength());
}
}
public virtual decimal AsNumber
{
get
{
decimal result;
if (this.IsSmallInt)
{
result = this.SmallInt;
}
else
{
if (this.IsInt)
{
result = this.Int;
}
else
{
if (this.IsUInt)
{
result = this.UInt;
}
else
{
if (this.IsDouble)
{
result = (decimal)this.AsDouble;
}
else
{
throw new VPackValueTypeException(ValueType.INT, ValueType.UINT, ValueType.SMALLINT);
}
}
}
}
return result;
}
}
public virtual long AsLong
{
get
{
return (long)this.AsNumber;
}
}
public virtual int AsInt
{
get
{
return (int)this.AsNumber;
}
}
public virtual float AsFloat
{
get
{
return (float)this.AsDoubleUnchecked;
}
}
public virtual short AsShort
{
get
{
return (short)this.AsNumber;
}
}
public virtual BigInteger AsBigInteger
{
get
{
if (this.IsSmallInt || this.IsInt)
{
return new BigInteger(this.AsLong);
}
if (this.IsUInt)
{
return NumberUtil.ToBigInteger(this.vpack, this.start + 1, this.GetLength());
}
throw new VPackValueTypeException(ValueType.INT, ValueType.UINT, ValueType.SMALLINT);
}
}
public virtual DateTime AsDate
{
get
{
if (!this.IsDate)
{
throw new VPackValueTypeException(ValueType.UTC_DATE);
}
return DateUtil.ToDate(this.vpack, this.start + 1, this.GetLength());
}
}
public virtual string AsString
{
get
{
if (!this.IsString)
{
throw new VPackValueTypeException(ValueType.STRING);
}
return this.IsLongString ? this.LongString : this.ShortString;
}
}
public virtual char AsChar
{
get
{
return this.AsString[0];
}
}
private bool IsLongString
{
get
{
return this.Head == 0xbf;
}
}
private string ShortString
{
get
{
return StringUtil.ToString(this.vpack, this.start + 1, this.GetLength());
}
}
private string LongString
{
get
{
return StringUtil.ToString(this.vpack, this.start + 9, this.LongStringLength);
}
}
private int LongStringLength
{
get
{
return (int)NumberUtil.ToLong(this.vpack, this.start + 1, 8);
}
}
private int StringLength
{
get
{
return this.IsLongString ? this.LongStringLength : this.Head - 0x40;
}
}
public virtual byte[] AsBinary
{
get
{
if (!this.IsBinary)
{
throw new VPackValueTypeException(ValueType.BINARY);
}
byte[] binary = BinaryUtil.ToBinary(this.vpack, this.start + 1 + this.Head - 0xbf, this.BinaryLength);
return binary;
}
}
public virtual int BinaryLength
{
get
{
if (!this.IsBinary)
{
throw new VPackValueTypeException(ValueType.BINARY);
}
return this.BinaryLengthUnchecked;
}
}
private int BinaryLengthUnchecked
{
get
{
return (int)NumberUtil.ToLong(this.vpack, this.start + 1, this.Head - 0xbf);
}
}
/// <returns>the number of members for an Array, Object or String</returns>
public virtual int Length
{
get
{
long length;
if (this.IsString)
{
length = this.StringLength;
}
else
{
if (!this.IsArray && !this.IsObject)
{
throw new VPackValueTypeException(ValueType.ARRAY, ValueType.OBJECT, ValueType.STRING);
}
byte head = this.Head;
if (head == 0x01 || head == 0x0a)
{
// empty
length = 0;
}
else
{
if (head == 0x13 || head == 0x14)
{
// compact array or object
long end = NumberUtil.ReadVariableValueLength(this.vpack, this.start + 1, false);
length = NumberUtil.ReadVariableValueLength(this.vpack, (int)(this.start + end - 1), true);
}
else
{
int offsetsize = ObjectArrayUtil.GetOffsetSize(head);
long end = NumberUtil.ToLong(this.vpack, this.start + 1, offsetsize);
if ((sbyte)head <= 0x05)
{
// array with no offset table or length
int dataOffset = this.FindDataOffset();
VPackSlice first = new VPackSlice(this.vpack, this.start + dataOffset);
length = (end - dataOffset) / first.ByteSize;
}
else
{
if (offsetsize < 8)
{
length = NumberUtil.ToLong(this.vpack, this.start + 1 + offsetsize, offsetsize);
}
else
{
length = NumberUtil.ToLong(
this.vpack,
(int)(this.start + end - offsetsize),
offsetsize);
}
}
}
}
}
return (int)length;
}
}
/// <summary>Must be called for a nonempty array or object at start():</summary>
protected internal virtual int FindDataOffset()
{
int fsm = ObjectArrayUtil.GetFirstSubMap(this.Head);
int offset;
if (fsm <= 2 && this.vpack[this.start + 2] != 0)
{
offset = 2;
}
else
{
if (fsm <= 3 && this.vpack[this.start + 3] != 0)
{
offset = 3;
}
else
{
if (fsm <= 5 && this.vpack[this.start + 6] != 0)
{
offset = 5;
}
else
{
offset = 9;
}
}
}
return offset;
}
public virtual int ByteSize
{
get
{
long size;
byte head = Head;
int valueLength = ValueLengthUtil.Get(head);
if (valueLength != 0)
{
size = valueLength;
}
else
{
switch (this.Type())
{
case ValueType.ARRAY:
case ValueType.OBJECT:
{
if (head == 0x13 || head == 0x14)
{
// compact Array or Object
size = NumberUtil.ReadVariableValueLength(this.vpack, this.start + 1, false);
}
else
{
/* if (head <= 0x14) */
size = NumberUtil.ToLong(
this.vpack,
this.start + 1,
ObjectArrayUtil.GetOffsetSize(head));
}
break;
}
case ValueType.STRING:
{
// long UTF-8 String
size = this.LongStringLength + 1 + 8;
break;
}
case ValueType.BINARY:
{
size = 1 + head - 0xbf + this.BinaryLengthUnchecked;
break;
}
case ValueType.BCD:
{
if ((sbyte)head <= 0xcf)
{
size = 1 + head + 0xc7 + NumberUtil.ToLong(this.vpack, this.start + 1, head - 0xc7);
}
else
{
size = 1 + head - 0xcf + NumberUtil.ToLong(this.vpack, this.start + 1, head - 0xcf);
}
break;
}
case ValueType.CUSTOM:
{
if (head == 0xf4 || head == 0xf5 || head == 0xf6)
{
size = 2 + NumberUtil.ToLong(this.vpack, this.start + 1, 1);
}
else
{
if (head == 0xf7 || head == 0xf8 || head == 0xf9)
{
size = 3 + NumberUtil.ToLong(this.vpack, this.start + 1, 2);
}
else
{
if (head == 0xfa || head == 0xfb || head == 0xfc)
{
size = 5 + NumberUtil.ToLong(this.vpack, this.start + 1, 4);
}
else
{
/* if (head == 0xfd || head == 0xfe || head == 0xff) */
size = 9 + NumberUtil.ToLong(this.vpack, this.start + 1, 8);
}
}
}
break;
}
default:
{
// TODO
throw new InvalidOperationException();
}
}
}
return (int)size;
}
}
/// <returns>array value at the specified index</returns>
/// <exception cref="VPackValueTypeException"/>
public virtual VPackSlice Get(int index)
{
if (!this.IsArray)
{
throw new VPackValueTypeException(ValueType.ARRAY);
}
return this.GetNth(index);
}
/// <exception cref="VPackException"/>
public virtual VPackSlice Get(string attribute)
{
if (!this.IsObject)
{
throw new VPackValueTypeException(ValueType.OBJECT);
}
byte head = Head;
VPackSlice result = new VPackSlice();
if (head == 0x0a)
{
// special case, empty object
result = new VPackSlice();
}
else
{
if (head == 0x14)
{
// compact Object
result = this.GetFromCompactObject(attribute);
}
else
{
int offsetsize = ObjectArrayUtil.GetOffsetSize(head);
long end = NumberUtil.ToLong(this.vpack, this.start + 1, offsetsize);
long n;
if (offsetsize < 8)
{
n = NumberUtil.ToLong(this.vpack, this.start + 1 + offsetsize, offsetsize);
}
else
{
n = NumberUtil.ToLong(this.vpack, (int)(this.start + end - offsetsize), offsetsize);
}
if (n == 1)
{
// Just one attribute, there is no index table!
VPackSlice key = new VPackSlice(this.vpack, this.start + this.FindDataOffset());
if (key.IsString)
{
if (key.IsEqualString(attribute))
{
result = new VPackSlice(this.vpack, key.start + key.ByteSize);
}
else
{
// no match
result = new VPackSlice();
}
}
else
{
if (key.IsInteger)
{
// translate key
if (attributeTranslator == null)
{
throw new VPackNeedAttributeTranslatorException();
}
if (key.TranslateUnchecked().IsEqualString(attribute))
{
result = new VPackSlice(this.vpack, key.start + key.ByteSize);
}
else
{
// no match
result = new VPackSlice();
}
}
else
{
// no match
result = new VPackSlice();
}
}
}
else
{
long ieBase = end - n * offsetsize - (offsetsize == 8 ? 8 : 0);
// only use binary search for attributes if we have at least
// this many entries
// otherwise we'll always use the linear search
long sortedSearchEntriesThreshold = 4;
bool sorted = head >= 0x0b && (sbyte)head <= 0x0e;
if (sorted && n >= sortedSearchEntriesThreshold)
{
// This means, we have to handle the special case n == 1
// only in the linear search!
result = this.SearchObjectKeyBinary(attribute, ieBase, offsetsize, n);
}
else
{
result = this.SearchObjectKeyLinear(attribute, ieBase, offsetsize, n);
}
}
}
}
return result;
}
/// <summary>translates an integer key into a string, without checks</summary>
internal virtual VPackSlice TranslateUnchecked()
{
VPackSlice result = attributeTranslator.Translate(this.AsInt);
return result != null ? result : new VPackSlice();
}
/// <exception cref="VPackKeyTypeException"/>
/// <exception cref="VPackNeedAttributeTranslatorException
/// "/>
internal virtual VPackSlice MakeKey()
{
if (this.IsString)
{
return this;
}
if (this.IsInteger)
{
if (attributeTranslator == null)
{
throw new VPackNeedAttributeTranslatorException();
}
return this.TranslateUnchecked();
}
throw new VPackKeyTypeException("Cannot translate key of this type");
}
/// <exception cref="VPackKeyTypeException"/>
/// <exception cref="VPackNeedAttributeTranslatorException
/// "/>
private VPackSlice GetFromCompactObject(string attribute)
{
for (IEnumerator<IEntry<string, VPackSlice>> iterator = this.ObjectIterator(); iterator.MoveNext();)
{
IEntry<string, VPackSlice> next = iterator.Current;
if (next.Key.Equals(attribute))
{
return next.Value;
}
}
// not found
return new VPackSlice();
}
/// <exception cref="VPackValueTypeException"/>
/// <exception cref="VPackNeedAttributeTranslatorException
/// "/>
private VPackSlice SearchObjectKeyBinary(string attribute, long ieBase, int offsetsize, long n)
{
bool useTranslator = attributeTranslator != null;
VPackSlice result;
long l = 0;
long r = n - 1;
for (;;)
{
// midpoint
long index = l + (r - l) / 2;
long offset = ieBase + index * offsetsize;
long keyIndex = NumberUtil.ToLong(this.vpack, (int)(this.start + offset), offsetsize);
VPackSlice key = new VPackSlice(this.vpack, (int)(this.start + keyIndex));
int res = 0;
if (key.IsString)
{
res = key.CompareString(attribute);
}
else
{
if (key.IsInteger)
{
// translate key
if (!useTranslator)
{
// no attribute translator
throw new VPackNeedAttributeTranslatorException();
}
res = key.TranslateUnchecked().CompareString(attribute);
}
else
{
// invalid key
result = new VPackSlice();
break;
}
}
if (res == 0)
{
// found
result = new VPackSlice(this.vpack, key.start + key.ByteSize);
break;
}
if (res > 0)
{
if (index == 0)
{
result = new VPackSlice();
break;
}
r = index - 1;
}
else
{
l = index + 1;
}
if (r < l)
{
result = new VPackSlice();
break;
}
}
return result;
}
/// <exception cref="VPackValueTypeException"/>
/// <exception cref="VPackNeedAttributeTranslatorException
/// "/>
private VPackSlice SearchObjectKeyLinear(string attribute, long ieBase, int offsetsize, long n)
{
bool useTranslator = attributeTranslator != null;
VPackSlice result = new VPackSlice();
for (long index = 0; index < n; index++)
{
long offset = ieBase + index * offsetsize;
long keyIndex = NumberUtil.ToLong(this.vpack, (int)(this.start + offset), offsetsize);
VPackSlice key = new VPackSlice(this.vpack, (int)(this.start + keyIndex));
if (key.IsString)
{
if (!key.IsEqualString(attribute))
{
continue;
}
}
else
{
if (key.IsInteger)
{
// translate key
if (!useTranslator)
{
// no attribute translator
throw new VPackNeedAttributeTranslatorException();
}
if (!key.TranslateUnchecked().IsEqualString(attribute))
{
continue;
}
}
else
{
// invalid key type
result = new VPackSlice();
break;
}
}
// key is identical. now return value
result = new VPackSlice(this.vpack, key.start + key.ByteSize);
break;
}
return result;
}
public virtual VPackSlice KeyAt(int index)
{
if (!this.IsObject)
{
throw new VPackValueTypeException(ValueType.OBJECT);
}
return this.GetNthKey(index);
}
public virtual VPackSlice ValueAt(int index)
{
if (!this.IsObject)
{
throw new VPackValueTypeException(ValueType.OBJECT);
}
VPackSlice key = this.GetNthKey(index);
return new VPackSlice(this.vpack, key.start + key.ByteSize);
}
private VPackSlice GetNthKey(int index)
{
return new VPackSlice(this.vpack, this.start + this.GetNthOffset(index));
}
private VPackSlice GetNth(int index)
{
return new VPackSlice(this.vpack, this.start + this.GetNthOffset(index));
}
/// <returns>the offset for the nth member from an Array or Object type</returns>
private int GetNthOffset(int index)
{
int offset;
byte head = Head;
if (head == 0x13 || head == 0x14)
{
// compact Array or Object
offset = this.GetNthOffsetFromCompact(index);
}
else
{
if (head == 0x01 || head == 0x0a)
{
// special case: empty Array or empty Object
throw new IndexOutOfRangeException();
}
long n;
int offsetsize = ObjectArrayUtil.GetOffsetSize(head);
long end = NumberUtil.ToLong(this.vpack, this.start + 1, offsetsize);
int dataOffset = this.FindDataOffset();
if ((sbyte)head <= 0x05)
{
// array with no offset table or length
VPackSlice first = new VPackSlice(this.vpack, this.start + dataOffset);
n = (end - dataOffset) / first.ByteSize;
}
else
{
if (offsetsize < 8)
{
n = NumberUtil.ToLong(this.vpack, this.start + 1 + offsetsize, offsetsize);
}
else
{
n = NumberUtil.ToLong(this.vpack, (int)(this.start + end - offsetsize), offsetsize);
}
}
if (index >= n)
{
throw new IndexOutOfRangeException();
}
if ((sbyte)head <= 0x05 || n == 1)
{
// no index table, but all array items have the same length
// or only one item is in the array
// now fetch first item and determine its length
if (dataOffset == 0)
{
dataOffset = this.FindDataOffset();
}
offset = dataOffset + index * new VPackSlice(this.vpack, this.start + dataOffset).ByteSize;
}
else
{
long ieBase = end - n * offsetsize + index * offsetsize - (offsetsize == 8 ? 8 : 0);
offset = (int)NumberUtil.ToLong(this.vpack, (int)(this.start + ieBase), offsetsize);
}
}
return offset;
}
/// <returns>the offset for the nth member from a compact Array or Object type</returns>
private int GetNthOffsetFromCompact(int index)
{
long end = NumberUtil.ReadVariableValueLength(this.vpack, this.start + 1, false);
long n = NumberUtil.ReadVariableValueLength(this.vpack, (int)(this.start + end - 1), true);
if (index >= n)
{
throw new IndexOutOfRangeException();
}
byte head = Head;
long offset = 1 + NumberUtil.GetVariableValueLength(end);
long current = 0;
while (current != index)
{
long byteSize = new VPackSlice(this.vpack, (int)(this.start + offset)).ByteSize;
offset += byteSize;
if (head == 0x14)
{
offset += byteSize;
}
++current;
}
return (int)offset;
}
private bool IsEqualString(string s)
{
string @string = this.AsString;
return @string.Equals(s);
}
private int CompareString(string s)
{
string @string = this.AsString;
return string.CompareOrdinal(@string, s);
}
public virtual IEnumerator<VPackSlice> ArrayIterator()
{
if (this.IsArray)
{
return new ArrayIterator(this);
}
throw new VPackValueTypeException(ValueType.ARRAY);
}
public virtual IEnumerator<IEntry<string, VPackSlice>> ObjectIterator()
{
if (this.IsObject)
{
return new ObjectIterator(this);
}
throw new VPackValueTypeException(ValueType.OBJECT);
}
protected internal virtual byte[] GetRawVPack()
{
return ArrayUtil.CopyOfRange(this.vpack, this.start, this.start + this.ByteSize);
}
public override string ToString()
{
try
{
return new VPackParser().ToJson(this, true);
}
catch (VPackException)
{
return base.ToString();
}
}
public override int GetHashCode()
{
int prime = 31;
int result = 1;
result = prime * result + this.start;
result = prime * result + this.GetRawVPack().ByteArrayHashCode();
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
VPackSlice other = (VPackSlice)obj;
if (this.start != other.start)
{
return false;
}
if (!this.GetRawVPack().SequenceEqual(other.GetRawVPack()))
{
return false;
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.LineSeparators
{
/// <summary>
/// UI manager for graphic overlay tags. These tags will simply paint something related to the text.
/// </summary>
internal class AdornmentManager<T> where T : GraphicsTag
{
private readonly object _invalidatedSpansLock = new object();
/// <summary>View that created us.</summary>
private readonly IWpfTextView _textView;
/// <summary>Layer where we draw adornments.</summary>
private readonly IAdornmentLayer _adornmentLayer;
/// <summary>Aggregator that tells us where to draw.</summary>
private readonly ITagAggregator<T> _tagAggregator;
/// <summary>Notification system about operations we do</summary>
private readonly IAsynchronousOperationListener _asyncListener;
/// <summary>Spans that are invalidated, and need to be removed from the layer..</summary>
private List<IMappingSpan> _invalidatedSpans;
public static AdornmentManager<T> Create(
IWpfTextView textView,
IViewTagAggregatorFactoryService aggregatorService,
IAsynchronousOperationListener asyncListener,
string adornmentLayerName)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(aggregatorService);
Contract.ThrowIfNull(adornmentLayerName);
Contract.ThrowIfNull(asyncListener);
return new AdornmentManager<T>(textView, aggregatorService, asyncListener, adornmentLayerName);
}
internal AdornmentManager(
IWpfTextView textView,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListener asyncListener,
string adornmentLayerName)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(tagAggregatorFactoryService);
Contract.ThrowIfNull(adornmentLayerName);
Contract.ThrowIfNull(asyncListener);
_textView = textView;
_adornmentLayer = textView.GetAdornmentLayer(adornmentLayerName);
textView.LayoutChanged += OnLayoutChanged;
_asyncListener = asyncListener;
// If we are not on the UI thread, we are at race with Close, but we should be on UI thread
Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess());
textView.Closed += OnTextViewClosed;
_tagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView);
_tagAggregator.TagsChanged += OnTagsChanged;
}
private void OnTextViewClosed(object sender, System.EventArgs e)
{
// release the aggregator
_tagAggregator.TagsChanged -= OnTagsChanged;
_tagAggregator.Dispose();
// unhook from view
_textView.Closed -= OnTextViewClosed;
_textView.LayoutChanged -= OnLayoutChanged;
// At this point, this object should be available for garbage collection.
}
/// <summary>
/// This handler gets called whenever there is a visual change in the view.
/// Example: edit or a scroll.
/// </summary>
private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None))
using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged"))
{
// Make sure we're on the UI thread.
Contract.ThrowIfFalse(_textView.VisualElement.Dispatcher.CheckAccess());
var reformattedSpans = e.NewOrReformattedSpans;
var viewSnapshot = _textView.TextSnapshot;
// No need to remove tags as these spans are reformatted anyways.
UpdateSpans_CallOnlyOnUIThread(reformattedSpans, viewSnapshot, removeOldTags: false);
// Compute any spans that had been invalidated but were not affected by layout.
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (invalidated != null)
{
var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference(
invalidatedAndNormalized,
e.NewOrReformattedSpans);
UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, viewSnapshot, removeOldTags: true);
}
}
}
private static NormalizedSnapshotSpanCollection TranslateAndNormalize(
IEnumerable<IMappingSpan> spans,
ITextSnapshot targetSnapshot)
{
Contract.ThrowIfNull(spans);
var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot));
return new NormalizedSnapshotSpanCollection(translated);
}
/// <summary>
/// This handler is called when tag aggregator notifies us about tag changes.
/// </summary>
private void OnTagsChanged(object sender, TagsChangedEventArgs e)
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1"))
{
var changedSpan = e.Span;
if (changedSpan == null)
{
return; // nothing changed
}
var needToScheduleUpdate = false;
lock (_invalidatedSpansLock)
{
if (_invalidatedSpans == null)
{
// set invalidated spans
var newInvalidatedSpans = new List<IMappingSpan>();
newInvalidatedSpans.Add(changedSpan);
_invalidatedSpans = newInvalidatedSpans;
needToScheduleUpdate = true;
}
else
{
// add to existing invalidated spans
_invalidatedSpans.Add(changedSpan);
}
}
if (needToScheduleUpdate)
{
// schedule an update
var asyncToken = _asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2");
_textView.VisualElement.Dispatcher.BeginInvoke(
new System.Action(() =>
{
try
{
UpdateInvalidSpans();
}
finally
{
asyncToken.Dispose();
}
}), DispatcherPriority.Render);
}
}
}
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This function is used to update invalidates spans.
/// </summary>
private void UpdateInvalidSpans()
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1"))
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None))
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(_textView.VisualElement.Dispatcher.CheckAccess());
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (_textView.IsClosed)
{
return; // already closed
}
if (invalidated != null)
{
var viewSnapshot = _textView.TextSnapshot;
var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, viewSnapshot, removeOldTags: true);
}
}
}
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This is where we apply visuals to the text.
///
/// It happens when another region of the view becomes visible or there is a change in tags.
/// For us the end result is the same - get tags from tagger and update visuals correspondingly.
/// </summary>
private void UpdateSpans_CallOnlyOnUIThread(
NormalizedSnapshotSpanCollection changedSpanCollection,
ITextSnapshot viewSnapshot,
bool removeOldTags)
{
Contract.ThrowIfNull(changedSpanCollection);
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(_textView.VisualElement.Dispatcher.CheckAccess());
var viewLines = _textView.TextViewLines;
if (viewLines == null || viewLines.Count == 0)
{
return; // nothing to draw on
}
// removing is a separate pass from adding so that new stuff is not removed.
if (removeOldTags)
{
foreach (var changedSpan in changedSpanCollection)
{
// is there any effect on the view?
if (viewLines.IntersectsBufferSpan(changedSpan))
{
_adornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan);
}
}
}
foreach (var changedSpan in changedSpanCollection)
{
// is there any effect on the view?
if (!viewLines.IntersectsBufferSpan(changedSpan))
{
continue;
}
var tagSpans = _tagAggregator.GetTags(changedSpan);
foreach (var tagMappingSpan in tagSpans)
{
SnapshotSpan span;
if (!TryMapToSingleSnapshotSpan(tagMappingSpan.Span, viewSnapshot, out span))
{
continue;
}
if (!viewLines.IntersectsBufferSpan(span))
{
// span is outside of the view so we will not get geometry for it, but may spent a lot of time trying
continue;
}
// add the visual to the adornment layer.
var geometry = viewLines.GetMarkerGeometry(span);
if (geometry != null)
{
var tag = tagMappingSpan.Tag;
var graphicsResult = tag.GetGraphics(_textView, geometry);
_adornmentLayer.AddAdornment(
behavior: AdornmentPositioningBehavior.TextRelative,
visualSpan: span,
tag: tag,
adornment: graphicsResult.VisualElement,
removedCallback: delegate { graphicsResult.Dispose(); });
}
}
}
}
// Map the mapping span to the visual snapshot. note that as a result of projection
// topology, originally single span may be mapped into several spans. Visual adornments do
// not make much sense on disjoint spans. We will not decorate spans that could not make it
// in one piece.
private bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span)
{
// IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple
// lists and collection if the view buffer is same as anchor we could just map the
// anchor to the viewSnapshot however, since the _anchor is not available, we have to
// map start and end TODO: verify that affinity is correct. If it does not matter we
// should use the cheapest.
if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer)
{
var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value;
var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value;
span = new SnapshotSpan(mappedStart, mappedEnd);
return true;
}
// TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su"
// is it possible to cheaply detect cropping?
var spans = mappingSpan.GetSpans(viewSnapshot);
if (spans.Count != 1)
{
span = default(SnapshotSpan);
return false; // span is unmapped or disjoint.
}
span = spans[0];
return true;
}
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.util.fsm
{
/// <summary>
/// <para>A finite state machine.</para>
/// <para>See <see cref="qx.util.fsm.State"/> for details on creating States,
/// and <see cref="qx.util.fsm.Transition"/> for details on creating
/// transitions between states.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.util.fsm.FiniteStateMachine", OmitOptionalParameters = true, Export = false)]
public partial class FiniteStateMachine : qx.core.Object
{
#region Properties
/// <summary>
/// <para>Debug flags, composed of the bitmask values in the DebugFlags constant.</para>
/// <para>Set the debug flags from the application by or-ing together bits, akin
/// to this:</para>
/// <code>
/// var FSM = qx.util.fsm.FiniteStateMachine;
/// fsm.setDebugFlags(FSM.DebugFlags.EVENTS |
/// FSM.DebugFlags.TRANSITIONS |
/// FSM.DebugFlags.FUNCTION_DETAIL |
/// FSM.DebugFlags.OBJECT_NOT_FOUND);
/// </code>
/// </summary>
[JsProperty(Name = "debugFlags", NativeField = true)]
public double DebugFlags { get; set; }
/// <summary>
/// <para>The maximum number of states which may pushed onto the state-stack. It
/// is generally a poor idea to have very many states saved on a stack.
/// Following program logic becomes very difficult, and the code can be
/// highly unmaintainable. The default should be more than adequate.
/// You’ve been warned.</para>
/// </summary>
[JsProperty(Name = "maxSavedStates", NativeField = true)]
public double MaxSavedStates { get; set; }
/// <summary>
/// <para>The name of this finite state machine (for debug messages)</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "name", NativeField = true)]
public string Name { get; set; }
/// <summary>
/// <para>The state to which we will be transitioning. This property is valid
/// only during a Transition’s ontransition function and a State’s onexit
/// function. At all other times, it is null.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "nextState", NativeField = true)]
public string NextState { get; set; }
/// <summary>
/// <para>The previous state of the finite state machine, i.e. the state from
/// which we most recently transitioned. Note that this could be the same
/// as the current state if a successful transition brought us back to the
/// same state.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "previousState", NativeField = true)]
public string PreviousState { get; set; }
/// <summary>
/// <para>The current state of the finite state machine.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "state", NativeField = true)]
public string State { get; set; }
#endregion Properties
#region Methods
public FiniteStateMachine() { throw new NotImplementedException(); }
/// <param name="machineName">The name of this finite state machine</param>
public FiniteStateMachine(string machineName) { throw new NotImplementedException(); }
/// <summary>
/// <para>Add an object (typically a widget) that is to be accessed during state
/// transitions, to the finite state machine.</para>
/// </summary>
/// <param name="friendlyName">The friendly name to used for access to the object being added.</param>
/// <param name="obj">The object to associate with the specified friendly name</param>
/// <param name="groupNames">An optional list of group names of which this object is a member.</param>
[JsMethod(Name = "addObject")]
public void AddObject(string friendlyName, object obj, JsArray groupNames) { throw new NotImplementedException(); }
/// <summary>
/// <para>Add a state to the finite state machine.</para>
/// </summary>
/// <param name="state">An object of class qx.util.fsm.State representing a state which is to be a part of this finite state machine.</param>
[JsMethod(Name = "addState")]
public void AddState(qx.util.fsm.State state) { throw new NotImplementedException(); }
/// <summary>
/// <para>Display all of the saved objects and their reverse mappings.</para>
/// </summary>
[JsMethod(Name = "displayAllObjects")]
public void DisplayAllObjects() { throw new NotImplementedException(); }
/// <summary>
/// <para>Enqueue an event for processing</para>
/// </summary>
/// <param name="eventx">The event to be enqueued</param>
/// <param name="bAddAtHead">If true, put the event at the head of the queue for immediate processing. If false, place the event at the tail of the queue so that it receives in-order processing.</param>
[JsMethod(Name = "enqueueEvent")]
public void EnqueueEvent(qx.eventx.type.Event eventx, bool bAddAtHead) { throw new NotImplementedException(); }
/// <summary>
/// <para>Event listener for all event types in the finite state machine</para>
/// </summary>
/// <param name="eventx">The event that was dispatched.</param>
[JsMethod(Name = "eventListener")]
public void EventListener(qx.eventx.type.Event eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>Create an event and send it immediately to the finite state machine.</para>
/// </summary>
/// <param name="type">The type of event, e.g. “execute”</param>
/// <param name="target">The target of the event</param>
/// <param name="data">The data, if any, to issue in the event. If this parameter is null then a qx.event.type.Event is instantiated. Otherwise, an event of type qx.event.type.Data is instantiated and this data is applied to it.</param>
[JsMethod(Name = "fireImmediateEvent")]
public void FireImmediateEvent(string type, qx.core.Object target, object data) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property debugFlags.</para>
/// </summary>
[JsMethod(Name = "getDebugFlags")]
public double GetDebugFlags() { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the friendly name of an object.</para>
/// </summary>
/// <param name="obj">The object for which the friendly name is desired</param>
/// <returns>If the object has been previously registered via #addObject, then the friendly name of the object is returned; otherwise, null.</returns>
[JsMethod(Name = "getFriendlyName")]
public string GetFriendlyName(object obj) { throw new NotImplementedException(); }
/// <summary>
/// <para>Retrieve the list of objects which have registered, via {@link
/// #addObject} as being members of the specified group.</para>
/// </summary>
/// <param name="groupName">The name of the group for which the member list is desired.</param>
/// <returns>An array containing the friendly names of any objects which are members of the specified group. The resultant array may be empty.</returns>
[JsMethod(Name = "getGroupObjects")]
public JsArray GetGroupObjects(string groupName) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property maxSavedStates.</para>
/// </summary>
[JsMethod(Name = "getMaxSavedStates")]
public double GetMaxSavedStates() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property name.</para>
/// </summary>
[JsMethod(Name = "getName")]
public string GetName() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property nextState.</para>
/// </summary>
[JsMethod(Name = "getNextState")]
public string GetNextState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Retrieve an object previously saved via <see cref="AddObject"/>, using its
/// Friendly Name.</para>
/// </summary>
/// <param name="friendlyName">The friendly name of the object to be retrieved.</param>
/// <returns>The object which has the specified friendly name, or undefined if no object has been associated with that name.</returns>
[JsMethod(Name = "getObject")]
public object GetObject(string friendlyName) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property previousState.</para>
/// </summary>
[JsMethod(Name = "getPreviousState")]
public string GetPreviousState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property state.</para>
/// </summary>
[JsMethod(Name = "getState")]
public string GetState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property debugFlags
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property debugFlags.</param>
[JsMethod(Name = "initDebugFlags")]
public void InitDebugFlags(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property maxSavedStates
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property maxSavedStates.</param>
[JsMethod(Name = "initMaxSavedStates")]
public void InitMaxSavedStates(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property name
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property name.</param>
[JsMethod(Name = "initName")]
public void InitName(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property nextState
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property nextState.</param>
[JsMethod(Name = "initNextState")]
public void InitNextState(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property previousState
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property previousState.</param>
[JsMethod(Name = "initPreviousState")]
public void InitPreviousState(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property state
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property state.</param>
[JsMethod(Name = "initState")]
public void InitState(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Pop the saved state stack.</para>
/// </summary>
/// <returns>The name of a state or a boolean flag that had most recently been pushed onto the saved-state stack.</returns>
[JsMethod(Name = "popState")]
public object PopState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Add the specified event to a list of events to be passed to the next
/// state following state transition.</para>
/// </summary>
/// <param name="eventx">The event to add to the event queue for processing after state change.</param>
[JsMethod(Name = "postponeEvent")]
public void PostponeEvent(qx.eventx.type.Event eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>Save the current or previous state on the saved-state stack. A future
/// transition can then provide, as its nextState value, the class
/// constant:</para>
///
/// qx.util.fsm.FiniteStateMachine.StateChange.POP_STATE_STACK
///
/// <para>which will cause the next state to be whatever is at the top of the
/// saved-state stack, and remove that top element from the saved-state
/// stack.</para>
/// </summary>
/// <param name="state">When true, then push the current state onto the stack. This might be used in a transition, before the state has changed. When false, then push the previous state onto the stack. This might be used in an on entry function to save the previous state to return to. If this parameter is a string, it is taken to be the name of the state to transition to.</param>
[JsMethod(Name = "pushState")]
public void PushState(object state) { throw new NotImplementedException(); }
/// <summary>
/// <para>Remove an object which had previously been added by <see cref="AddObject"/>.</para>
/// </summary>
/// <param name="friendlyName">The friendly name associated with an object, specifying which object is to be removed.</param>
[JsMethod(Name = "removeObject")]
public void RemoveObject(string friendlyName) { throw new NotImplementedException(); }
/// <summary>
/// <para>Replace a state in the finite state machine. This is useful if
/// initially “dummy” states are created which load the real state table
/// for a series of operations (and possibly also load the gui associated
/// with the new states at the same time). Having portions of the finite
/// state machine and their associated gui pages loaded at run time can
/// help prevent long delays at application start-up time.</para>
/// </summary>
/// <param name="state">An object of class qx.util.fsm.State representing a state which is to be a part of this finite state machine.</param>
/// <param name="bDispose">If true, then dispose the old state object. If false, the old state object is returned for disposing by the caller.</param>
/// <returns>The old state object if it was not disposed; otherwise null.</returns>
[JsMethod(Name = "replaceState")]
public object ReplaceState(qx.util.fsm.State state, bool bDispose) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property debugFlags.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetDebugFlags")]
public void ResetDebugFlags() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property maxSavedStates.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetMaxSavedStates")]
public void ResetMaxSavedStates() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property name.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetName")]
public void ResetName() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property nextState.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetNextState")]
public void ResetNextState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property previousState.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPreviousState")]
public void ResetPreviousState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property state.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetState")]
public void ResetState() { throw new NotImplementedException(); }
/// <summary>
/// <para>Create and schedule an event to be sent to the finite state machine
/// “shortly”. This allows such things as letting a progress cursor
/// display prior to handling the event.</para>
/// </summary>
/// <param name="type">The type of event, e.g. “execute”</param>
/// <param name="target">The target of the event</param>
/// <param name="data">See #fireImmediateEvent for details.</param>
/// <param name="timeout">If provided, this is the number of milliseconds to wait before firing the event. If not provided, a default short interval (on the order of 20 milliseconds) is used.</param>
[JsMethod(Name = "scheduleEvent")]
public void ScheduleEvent(string type, qx.core.Object target, object data, double timeout) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property debugFlags.</para>
/// </summary>
/// <param name="value">New value for property debugFlags.</param>
[JsMethod(Name = "setDebugFlags")]
public void SetDebugFlags(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property maxSavedStates.</para>
/// </summary>
/// <param name="value">New value for property maxSavedStates.</param>
[JsMethod(Name = "setMaxSavedStates")]
public void SetMaxSavedStates(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property name.</para>
/// </summary>
/// <param name="value">New value for property name.</param>
[JsMethod(Name = "setName")]
public void SetName(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property nextState.</para>
/// </summary>
/// <param name="value">New value for property nextState.</param>
[JsMethod(Name = "setNextState")]
public void SetNextState(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property previousState.</para>
/// </summary>
/// <param name="value">New value for property previousState.</param>
[JsMethod(Name = "setPreviousState")]
public void SetPreviousState(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property state.</para>
/// </summary>
/// <param name="value">New value for property state.</param>
[JsMethod(Name = "setState")]
public void SetState(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Start (or restart, after it has terminated) the finite state machine
/// from the starting state. The starting state is defined as the first
/// state added to the finite state machine.</para>
/// </summary>
[JsMethod(Name = "start")]
public void Start() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Store.Models;
namespace Microsoft.WindowsAzure.Management.Store.Models
{
/// <summary>
/// The response structure for the Cloud Service List operation.
/// </summary>
public partial class CloudServiceListResponse : AzureOperationResponse, IEnumerable<CloudServiceListResponse.CloudService>
{
private IList<CloudServiceListResponse.CloudService> _cloudServices;
/// <summary>
/// Optional. The list of cloud service locations for this subscription.
/// </summary>
public IList<CloudServiceListResponse.CloudService> CloudServices
{
get { return this._cloudServices; }
set { this._cloudServices = value; }
}
/// <summary>
/// Initializes a new instance of the CloudServiceListResponse class.
/// </summary>
public CloudServiceListResponse()
{
this.CloudServices = new LazyList<CloudServiceListResponse.CloudService>();
}
/// <summary>
/// Gets the sequence of CloudServices.
/// </summary>
public IEnumerator<CloudServiceListResponse.CloudService> GetEnumerator()
{
return this.CloudServices.GetEnumerator();
}
/// <summary>
/// Gets the sequence of CloudServices.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Defines a cloud service-supporting region in which a storm item is
/// located.
/// </summary>
public partial class CloudService
{
private string _description;
/// <summary>
/// Optional. The description of the cloud service region.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private string _geoRegion;
/// <summary>
/// Optional. The geographical region in which this cloud service
/// can run.
/// </summary>
public string GeoRegion
{
get { return this._geoRegion; }
set { this._geoRegion = value; }
}
private string _label;
/// <summary>
/// Optional. The label of the cloud service region.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _name;
/// <summary>
/// Optional. The name of the cloud service region.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private IList<CloudServiceListResponse.CloudService.AddOnResource> _resources;
/// <summary>
/// Optional. A list of existing store resources installed into a
/// cloud service region.
/// </summary>
public IList<CloudServiceListResponse.CloudService.AddOnResource> Resources
{
get { return this._resources; }
set { this._resources = value; }
}
/// <summary>
/// Initializes a new instance of the CloudService class.
/// </summary>
public CloudService()
{
this.Resources = new LazyList<CloudServiceListResponse.CloudService.AddOnResource>();
}
/// <summary>
/// A store add-on item.
/// </summary>
public partial class AddOnResource
{
private string _eTag;
/// <summary>
/// Optional. The ETag for this store resource.
/// </summary>
public string ETag
{
get { return this._eTag; }
set { this._eTag = value; }
}
private string _name;
/// <summary>
/// Optional. The user-input name of this store item.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _namespace;
/// <summary>
/// Optional. The namespace in which this store item resides.
/// </summary>
public string Namespace
{
get { return this._namespace; }
set { this._namespace = value; }
}
private IDictionary<string, string> _outputItems;
/// <summary>
/// Optional. Output items associated with an individual store
/// resource.
/// </summary>
public IDictionary<string, string> OutputItems
{
get { return this._outputItems; }
set { this._outputItems = value; }
}
private string _plan;
/// <summary>
/// Optional. The plan for this store item as selected by the
/// user.
/// </summary>
public string Plan
{
get { return this._plan; }
set { this._plan = value; }
}
private string _schemaVersion;
/// <summary>
/// Optional. The schema version for this resource.
/// </summary>
public string SchemaVersion
{
get { return this._schemaVersion; }
set { this._schemaVersion = value; }
}
private string _state;
/// <summary>
/// Optional. The state of this store resource.
/// </summary>
public string State
{
get { return this._state; }
set { this._state = value; }
}
private CloudServiceListResponse.CloudService.AddOnResource.OperationStatus _status;
/// <summary>
/// Optional. Operation status items associated with an
/// individual store resource.
/// </summary>
public CloudServiceListResponse.CloudService.AddOnResource.OperationStatus Status
{
get { return this._status; }
set { this._status = value; }
}
private string _type;
/// <summary>
/// Optional. The type of store item.
/// </summary>
public string Type
{
get { return this._type; }
set { this._type = value; }
}
private IList<CloudServiceListResponse.CloudService.AddOnResource.UsageLimit> _usageLimits;
/// <summary>
/// Optional. Usage meters associated with an individual store
/// resource.
/// </summary>
public IList<CloudServiceListResponse.CloudService.AddOnResource.UsageLimit> UsageLimits
{
get { return this._usageLimits; }
set { this._usageLimits = value; }
}
/// <summary>
/// Initializes a new instance of the AddOnResource class.
/// </summary>
public AddOnResource()
{
this.OutputItems = new LazyDictionary<string, string>();
this.UsageLimits = new LazyList<CloudServiceListResponse.CloudService.AddOnResource.UsageLimit>();
}
/// <summary>
/// The operation status of an individual store resource item.
/// </summary>
public partial class OperationStatus
{
private string _result;
/// <summary>
/// Optional. The result of this operation status.
/// </summary>
public string Result
{
get { return this._result; }
set { this._result = value; }
}
private string _type;
/// <summary>
/// Optional. The type of this operation status.
/// </summary>
public string Type
{
get { return this._type; }
set { this._type = value; }
}
/// <summary>
/// Initializes a new instance of the OperationStatus class.
/// </summary>
public OperationStatus()
{
}
}
/// <summary>
/// Describes the current utilization and metering of a store
/// resource item.
/// </summary>
public partial class UsageLimit
{
private long _amountIncluded;
/// <summary>
/// Optional. Defines the limit of this usage included in
/// this store resource's plan.
/// </summary>
public long AmountIncluded
{
get { return this._amountIncluded; }
set { this._amountIncluded = value; }
}
private long _amountUsed;
/// <summary>
/// Optional. The amount of this store resource that has
/// already been used.
/// </summary>
public long AmountUsed
{
get { return this._amountUsed; }
set { this._amountUsed = value; }
}
private string _name;
/// <summary>
/// Optional. The name of this usage limit.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _unit;
/// <summary>
/// Optional. The unit in which this usage limit is
/// measured.
/// </summary>
public string Unit
{
get { return this._unit; }
set { this._unit = value; }
}
/// <summary>
/// Initializes a new instance of the UsageLimit class.
/// </summary>
public UsageLimit()
{
}
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.IO;
using System.Web;
using Mono.Addins;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Messages.Linden;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
using OSD = OpenMetaverse.StructuredData.OSD;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
using OpenSim.Framework.Capabilities;
using ExtraParamType = OpenMetaverse.ExtraParamType;
namespace OpenSim.Region.ClientStack.Linden
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UploadObjectAssetModule")]
public class UploadObjectAssetModule : INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
#region Region Module interfaceBase Members
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
}
public void AddRegion(Scene pScene)
{
m_scene = pScene;
}
public void RemoveRegion(Scene scene)
{
m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
m_scene = null;
}
public void RegionLoaded(Scene scene)
{
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
}
#endregion
#region Region Module interface
public void Close() { }
public string Name { get { return "UploadObjectAssetModuleModule"; } }
public void RegisterCaps(UUID agentID, Caps caps)
{
UUID capID = UUID.Random();
// m_log.Debug("[UPLOAD OBJECT ASSET MODULE]: /CAPS/" + capID);
caps.RegisterHandler(
"UploadObjectAsset",
new RestHTTPHandler(
"POST",
"/CAPS/OA/" + capID + "/",
httpMethod => ProcessAdd(httpMethod, agentID, caps),
"UploadObjectAsset",
agentID.ToString()));
/*
caps.RegisterHandler("NewFileAgentInventoryVariablePrice",
new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDNewFileAngentInventoryVariablePriceReplyResponse>("POST",
"/CAPS/" + capID.ToString(),
delegate(LLSDAssetUploadRequest req)
{
return NewAgentInventoryRequest(req,agentID);
}));
*/
}
#endregion
/// <summary>
/// Parses add request
/// </summary>
/// <param name="request"></param>
/// <param name="AgentId"></param>
/// <param name="cap"></param>
/// <returns></returns>
public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
{
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 400; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Request wasn't what was expected";
ScenePresence avatar;
if (!m_scene.TryGetScenePresence(AgentId, out avatar))
return responsedata;
OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]);
UploadObjectAssetMessage message = new UploadObjectAssetMessage();
try
{
message.Deserialize(r);
}
catch (Exception ex)
{
m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString());
message = null;
}
if (message == null)
{
responsedata["int_response_code"] = 400; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] =
"<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>";
return responsedata;
}
Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
Quaternion rot = Quaternion.Identity;
Vector3 rootpos = Vector3.Zero;
// Quaternion rootrot = Quaternion.Identity;
SceneObjectGroup rootGroup = null;
SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
for (int i = 0; i < message.Objects.Length; i++)
{
UploadObjectAssetMessage.Object obj = message.Objects[i];
PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
if (i == 0)
{
rootpos = obj.Position;
// rootrot = obj.Rotation;
}
// Combine the extraparams data into it's ugly blob again....
//int bytelength = 0;
//for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
//{
// bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
//}
//byte[] extraparams = new byte[bytelength];
//int position = 0;
//for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
//{
// Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
// obj.ExtraParams[extparams].ExtraParamData.Length);
//
// position += obj.ExtraParams[extparams].ExtraParamData.Length;
// }
//pbs.ExtraParams = extraparams;
for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
{
UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams];
switch ((ushort)extraParam.Type)
{
case (ushort)ExtraParamType.Sculpt:
Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);
pbs.SculptEntry = true;
pbs.SculptTexture = obj.SculptID;
pbs.SculptType = (byte)sculpt.Type;
break;
case (ushort)ExtraParamType.Flexible:
Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
pbs.FlexiEntry = true;
pbs.FlexiDrag = flex.Drag;
pbs.FlexiForceX = flex.Force.X;
pbs.FlexiForceY = flex.Force.Y;
pbs.FlexiForceZ = flex.Force.Z;
pbs.FlexiGravity = flex.Gravity;
pbs.FlexiSoftness = flex.Softness;
pbs.FlexiTension = flex.Tension;
pbs.FlexiWind = flex.Wind;
break;
case (ushort)ExtraParamType.Light:
Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
pbs.LightColorA = light.Color.A;
pbs.LightColorB = light.Color.B;
pbs.LightColorG = light.Color.G;
pbs.LightColorR = light.Color.R;
pbs.LightCutoff = light.Cutoff;
pbs.LightEntry = true;
pbs.LightFalloff = light.Falloff;
pbs.LightIntensity = light.Intensity;
pbs.LightRadius = light.Radius;
break;
case 0x40:
pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
break;
}
}
pbs.PathBegin = (ushort) obj.PathBegin;
pbs.PathCurve = (byte) obj.PathCurve;
pbs.PathEnd = (ushort) obj.PathEnd;
pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset;
pbs.PathRevolutions = (byte) obj.Revolutions;
pbs.PathScaleX = (byte) obj.ScaleX;
pbs.PathScaleY = (byte) obj.ScaleY;
pbs.PathShearX = (byte) obj.ShearX;
pbs.PathShearY = (byte) obj.ShearY;
pbs.PathSkew = (sbyte) obj.Skew;
pbs.PathTaperX = (sbyte) obj.TaperX;
pbs.PathTaperY = (sbyte) obj.TaperY;
pbs.PathTwist = (sbyte) obj.Twist;
pbs.PathTwistBegin = (sbyte) obj.TwistBegin;
pbs.HollowShape = (HollowShape) obj.ProfileHollow;
pbs.PCode = (byte) PCode.Prim;
pbs.ProfileBegin = (ushort) obj.ProfileBegin;
pbs.ProfileCurve = (byte) obj.ProfileCurve;
pbs.ProfileEnd = (ushort) obj.ProfileEnd;
pbs.Scale = obj.Scale;
pbs.State = (byte) 0;
pbs.LastAttachPoint = (byte) 0;
SceneObjectPart prim = new SceneObjectPart();
prim.UUID = UUID.Random();
prim.CreatorID = AgentId;
prim.OwnerID = AgentId;
prim.GroupID = obj.GroupID;
prim.LastOwnerID = prim.OwnerID;
prim.CreationDate = Util.UnixTimeSinceEpoch();
prim.Name = obj.Name;
prim.Description = "";
prim.PayPrice[0] = -2;
prim.PayPrice[1] = -2;
prim.PayPrice[2] = -2;
prim.PayPrice[3] = -2;
prim.PayPrice[4] = -2;
Primitive.TextureEntry tmp =
new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));
for (int j = 0; j < obj.Faces.Length; j++)
{
UploadObjectAssetMessage.Object.Face face = obj.Faces[j];
Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j);
primFace.Bump = face.Bump;
primFace.RGBA = face.Color;
primFace.Fullbright = face.Fullbright;
primFace.Glow = face.Glow;
primFace.TextureID = face.ImageID;
primFace.Rotation = face.ImageRot;
primFace.MediaFlags = ((face.MediaFlags & 1) != 0);
primFace.OffsetU = face.OffsetS;
primFace.OffsetV = face.OffsetT;
primFace.RepeatU = face.ScaleS;
primFace.RepeatV = face.ScaleT;
primFace.TexMapType = (MappingType) (face.MediaFlags & 6);
}
pbs.TextureEntry = tmp.GetBytes();
prim.Shape = pbs;
prim.Scale = obj.Scale;
SceneObjectGroup grp = new SceneObjectGroup();
grp.SetRootPart(prim);
prim.ParentID = 0;
if (i == 0)
{
rootGroup = grp;
}
grp.AttachToScene(m_scene);
grp.AbsolutePosition = obj.Position;
prim.RotationOffset = obj.Rotation;
// Required for linking
grp.RootPart.ClearUpdateSchedule();
if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
{
m_scene.AddSceneObject(grp);
grp.AbsolutePosition = obj.Position;
}
allparts[i] = grp;
}
for (int j = 1; j < allparts.Length; j++)
{
// Required for linking
rootGroup.RootPart.ClearUpdateSchedule();
allparts[j].RootPart.ClearUpdateSchedule();
rootGroup.LinkToGroup(allparts[j]);
}
rootGroup.ScheduleGroupForFullUpdate();
pos
= m_scene.GetNewRezLocation(
Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale, false);
responsedata["int_response_code"] = 200; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId));
return responsedata;
}
private string ConvertUintToBytes(uint val)
{
byte[] resultbytes = Utils.UIntToBytes(val);
if (BitConverter.IsLittleEndian)
Array.Reverse(resultbytes);
return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes));
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudfront-2015-04-17.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFront.Model
{
/// <summary>
/// A complex type that describes how CloudFront processes requests. You can create up
/// to 10 cache behaviors.You must create at least as many cache behaviors (including
/// the default cache behavior) as you have origins if you want CloudFront to distribute
/// objects from all of the origins. Each cache behavior specifies the one origin from
/// which you want CloudFront to get objects. If you have two origins and only the default
/// cache behavior, the default cache behavior will cause CloudFront to get objects from
/// one of the origins, but the other origin will never be used. If you don't want to
/// specify any cache behaviors, include only an empty CacheBehaviors element. Don't include
/// an empty CacheBehavior element, or CloudFront returns a MalformedXML error. To delete
/// all cache behaviors in an existing distribution, update the distribution configuration
/// and include only an empty CacheBehaviors element. To add, change, or remove one or
/// more cache behaviors, update the distribution configuration and specify all of the
/// cache behaviors that you want to include in the updated distribution.
/// </summary>
public partial class CacheBehavior
{
private AllowedMethods _allowedMethods;
private long? _defaultTTL;
private ForwardedValues _forwardedValues;
private long? _maxTTL;
private long? _minTTL;
private string _pathPattern;
private bool? _smoothStreaming;
private string _targetOriginId;
private TrustedSigners _trustedSigners;
private ViewerProtocolPolicy _viewerProtocolPolicy;
/// <summary>
/// Gets and sets the property AllowedMethods.
/// </summary>
public AllowedMethods AllowedMethods
{
get { return this._allowedMethods; }
set { this._allowedMethods = value; }
}
// Check to see if AllowedMethods property is set
internal bool IsSetAllowedMethods()
{
return this._allowedMethods != null;
}
/// <summary>
/// Gets and sets the property DefaultTTL. If you don't configure your origin to add a
/// Cache-Control max-age directive or an Expires header, DefaultTTL is the default amount
/// of time (in seconds) that an object is in a CloudFront cache before CloudFront forwards
/// another request to your origin to determine whether the object has been updated. The
/// value that you specify applies only when your origin does not add HTTP headers such
/// as Cache-Control max-age, Cache-Control s-maxage, and Expires to objects. You can
/// specify a value from 0 to 3,153,600,000 seconds (100 years).
/// </summary>
public long DefaultTTL
{
get { return this._defaultTTL.GetValueOrDefault(); }
set { this._defaultTTL = value; }
}
// Check to see if DefaultTTL property is set
internal bool IsSetDefaultTTL()
{
return this._defaultTTL.HasValue;
}
/// <summary>
/// Gets and sets the property ForwardedValues. A complex type that specifies how CloudFront
/// handles query strings, cookies and headers.
/// </summary>
public ForwardedValues ForwardedValues
{
get { return this._forwardedValues; }
set { this._forwardedValues = value; }
}
// Check to see if ForwardedValues property is set
internal bool IsSetForwardedValues()
{
return this._forwardedValues != null;
}
/// <summary>
/// Gets and sets the property MaxTTL. The maximum amount of time (in seconds) that an
/// object is in a CloudFront cache before CloudFront forwards another request to your
/// origin to determine whether the object has been updated. The value that you specify
/// applies only when your origin adds HTTP headers such as Cache-Control max-age, Cache-Control
/// s-maxage, and Expires to objects. You can specify a value from 0 to 3,153,600,000
/// seconds (100 years).
/// </summary>
public long MaxTTL
{
get { return this._maxTTL.GetValueOrDefault(); }
set { this._maxTTL = value; }
}
// Check to see if MaxTTL property is set
internal bool IsSetMaxTTL()
{
return this._maxTTL.HasValue;
}
/// <summary>
/// Gets and sets the property MinTTL. The minimum amount of time that you want objects
/// to stay in CloudFront caches before CloudFront queries your origin to see whether
/// the object has been updated.You can specify a value from 0 to 3,153,600,000 seconds
/// (100 years).
/// </summary>
public long MinTTL
{
get { return this._minTTL.GetValueOrDefault(); }
set { this._minTTL = value; }
}
// Check to see if MinTTL property is set
internal bool IsSetMinTTL()
{
return this._minTTL.HasValue;
}
/// <summary>
/// Gets and sets the property PathPattern. The pattern (for example, images/*.jpg) that
/// specifies which requests you want this cache behavior to apply to. When CloudFront
/// receives an end-user request, the requested path is compared with path patterns in
/// the order in which cache behaviors are listed in the distribution. The path pattern
/// for the default cache behavior is * and cannot be changed. If the request for an object
/// does not match the path pattern for any cache behaviors, CloudFront applies the behavior
/// in the default cache behavior.
/// </summary>
public string PathPattern
{
get { return this._pathPattern; }
set { this._pathPattern = value; }
}
// Check to see if PathPattern property is set
internal bool IsSetPathPattern()
{
return this._pathPattern != null;
}
/// <summary>
/// Gets and sets the property SmoothStreaming. Indicates whether you want to distribute
/// media files in Microsoft Smooth Streaming format using the origin that is associated
/// with this cache behavior. If so, specify true; if not, specify false.
/// </summary>
public bool SmoothStreaming
{
get { return this._smoothStreaming.GetValueOrDefault(); }
set { this._smoothStreaming = value; }
}
// Check to see if SmoothStreaming property is set
internal bool IsSetSmoothStreaming()
{
return this._smoothStreaming.HasValue;
}
/// <summary>
/// Gets and sets the property TargetOriginId. The value of ID for the origin that you
/// want CloudFront to route requests to when a request matches the path pattern either
/// for a cache behavior or for the default cache behavior.
/// </summary>
public string TargetOriginId
{
get { return this._targetOriginId; }
set { this._targetOriginId = value; }
}
// Check to see if TargetOriginId property is set
internal bool IsSetTargetOriginId()
{
return this._targetOriginId != null;
}
/// <summary>
/// Gets and sets the property TrustedSigners. A complex type that specifies the AWS accounts,
/// if any, that you want to allow to create signed URLs for private content. If you want
/// to require signed URLs in requests for objects in the target origin that match the
/// PathPattern for this cache behavior, specify true for Enabled, and specify the applicable
/// values for Quantity and Items. For more information, go to Using a Signed URL to Serve
/// Private Content in the Amazon CloudFront Developer Guide. If you don't want to require
/// signed URLs in requests for objects that match PathPattern, specify false for Enabled
/// and 0 for Quantity. Omit Items. To add, change, or remove one or more trusted signers,
/// change Enabled to true (if it's currently false), change Quantity as applicable, and
/// specify all of the trusted signers that you want to include in the updated distribution.
/// </summary>
public TrustedSigners TrustedSigners
{
get { return this._trustedSigners; }
set { this._trustedSigners = value; }
}
// Check to see if TrustedSigners property is set
internal bool IsSetTrustedSigners()
{
return this._trustedSigners != null;
}
/// <summary>
/// Gets and sets the property ViewerProtocolPolicy. Use this element to specify the protocol
/// that users can use to access the files in the origin specified by TargetOriginId when
/// a request matches the path pattern in PathPattern. If you want CloudFront to allow
/// end users to use any available protocol, specify allow-all. If you want CloudFront
/// to require HTTPS, specify https. If you want CloudFront to respond to an HTTP request
/// with an HTTP status code of 301 (Moved Permanently) and the HTTPS URL, specify redirect-to-https.
/// The viewer then resubmits the request using the HTTPS URL.
/// </summary>
public ViewerProtocolPolicy ViewerProtocolPolicy
{
get { return this._viewerProtocolPolicy; }
set { this._viewerProtocolPolicy = value; }
}
// Check to see if ViewerProtocolPolicy property is set
internal bool IsSetViewerProtocolPolicy()
{
return this._viewerProtocolPolicy != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.ICollection<T>.Clear()
/// </summary>
public class ICollectionClear
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
public static int Main(string[] args)
{
ICollectionClear testObj = new ICollectionClear();
TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.ICollection<T>.Clear())");
if (testObj.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;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Netativ]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the Clear method in ICollection<T> and Type is Byte...";
const string c_TEST_ID = "P001";
Byte[] byteValue = new Byte[10];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).Clear();
if (list.Count != 0)
{
string errorDesc = "ICollection.Count is not " + list.Count.ToString() + " as expected: Actual(0)";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the Clear method in ICollection<T> and Type is a reference type...";
const string c_TEST_ID = "P002";
String[] strValue = new String[10];
for (int i = 0; i < 10; i++)
{
strValue[i] = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
}
List<String> list = new List<String>(strValue);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<String>)list).Clear();
if (list.Count != 0)
{
string errorDesc = "ICollection.Count is not 0 as expected: Actual(" + list.Count.ToString() + ")";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Using List<T> which implemented the Clear method in ICollection<T> and Type is a user-defined type...";
const string c_TEST_ID = "P003";
MyClass[] mcValue = new MyClass[10];
for (int i = 0; i < 10; i++)
{
mcValue[i] = new MyClass();
}
List<MyClass> list = new List<MyClass>(mcValue);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<MyClass>)list).Clear();
if (list.Count != 0)
{
string errorDesc = "ICollection.Count is not 0 as expected: Actual(" + list.Count.ToString() + ")";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Using customer class which implemented the Clear method in ICollection<T> and Type is int...";
const string c_TEST_ID = "P004";
MyCollection<int> myC = new MyCollection<int>();
for (int i = 0; i < 10; i++)
{
myC.Add(TestLibrary.Generator.GetInt32(-55));
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<int>)myC).Clear();
if (myC.Count != 0)
{
string errorDesc = "ICollection.Count is not 0 as expected: Actual(" + myC.Count.ToString() + ")";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: Using user-defined type which is readonly");
MyCollection<int> myC = new MyCollection<int>();
myC.isReadOnly = true;
try
{
((ICollection<int>)myC).Clear();
TestLibrary.TestFramework.LogError("009", "The NotSupportedException was not thrown as expected");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help Class
public class MyCollection<T> : ICollection<T>
{
public T[] _items;
protected int length;
public bool isReadOnly = false;
public MyCollection()
{
_items = new T[10];
length = 0;
}
public T this[int index]
{
get
{
// Fllowing trick can reduce the range check by one
if ((uint)index >= (uint)length)
{
throw new ArgumentOutOfRangeException();
}
return _items[index];
}
}
#region ICollection<T> Members
public void Add(T item)
{
if (isReadOnly)
{
throw new NotSupportedException();
}
else
{
_items[length] = item;
length++;
}
}
public void Clear()
{
if (isReadOnly)
{
throw new NotSupportedException();
}
else
{
Array.Clear(_items, 0, length);
length = 0;
}
}
public bool Contains(T item)
{
throw new Exception("The method or operation is not implemented.");
}
public void CopyTo(T[] array, int arrayIndex)
{
throw new Exception("The method or operation is not implemented.");
}
public int Count
{
get { return length; }
}
public bool IsReadOnly
{
get { return isReadOnly; }
}
public bool Remove(T item)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
public class MyClass
{}
#endregion
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* 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 = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// AutoOrderQuery
/// </summary>
[DataContract]
public partial class AutoOrderQuery : IEquatable<AutoOrderQuery>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="AutoOrderQuery" /> class.
/// </summary>
/// <param name="autoOrderCode">Auto order code.</param>
/// <param name="cardType">Card type.</param>
/// <param name="city">City.</param>
/// <param name="company">Company.</param>
/// <param name="countryCode">ISO-3166 two letter country code.</param>
/// <param name="customerProfileOid">Customer profile object identifier.</param>
/// <param name="email">Email.</param>
/// <param name="firstName">First name.</param>
/// <param name="itemId">Item ID. Deprecated query field. This incorrectly meant the original order contained this item id..</param>
/// <param name="lastName">Last name.</param>
/// <param name="nextItemId">Next Item ID that is supposed to ship. This is calculated based upon the schedule associated with the original item id..</param>
/// <param name="nextShipmentDateBegin">Next shipment date begin.</param>
/// <param name="nextShipmentDateEnd">Next shipment date end.</param>
/// <param name="originalItemId">Original Item ID purchased on auto order..</param>
/// <param name="originalOrderDateBegin">Original order date begin.</param>
/// <param name="originalOrderDateEnd">Original order date end.</param>
/// <param name="originalOrderId">Original order ID.</param>
/// <param name="phone">Phone.</param>
/// <param name="postalCode">Postal code.</param>
/// <param name="state">State.</param>
/// <param name="status">Status.</param>
public AutoOrderQuery(string autoOrderCode = default(string), string cardType = default(string), string city = default(string), string company = default(string), string countryCode = default(string), int? customerProfileOid = default(int?), string email = default(string), string firstName = default(string), string itemId = default(string), string lastName = default(string), string nextItemId = default(string), string nextShipmentDateBegin = default(string), string nextShipmentDateEnd = default(string), string originalItemId = default(string), string originalOrderDateBegin = default(string), string originalOrderDateEnd = default(string), string originalOrderId = default(string), string phone = default(string), string postalCode = default(string), string state = default(string), string status = default(string))
{
this.AutoOrderCode = autoOrderCode;
this.CardType = cardType;
this.City = city;
this.Company = company;
this.CountryCode = countryCode;
this.CustomerProfileOid = customerProfileOid;
this.Email = email;
this.FirstName = firstName;
this.ItemId = itemId;
this.LastName = lastName;
this.NextItemId = nextItemId;
this.NextShipmentDateBegin = nextShipmentDateBegin;
this.NextShipmentDateEnd = nextShipmentDateEnd;
this.OriginalItemId = originalItemId;
this.OriginalOrderDateBegin = originalOrderDateBegin;
this.OriginalOrderDateEnd = originalOrderDateEnd;
this.OriginalOrderId = originalOrderId;
this.Phone = phone;
this.PostalCode = postalCode;
this.State = state;
this.Status = status;
}
/// <summary>
/// Auto order code
/// </summary>
/// <value>Auto order code</value>
[DataMember(Name="auto_order_code", EmitDefaultValue=false)]
public string AutoOrderCode { get; set; }
/// <summary>
/// Card type
/// </summary>
/// <value>Card type</value>
[DataMember(Name="card_type", EmitDefaultValue=false)]
public string CardType { get; set; }
/// <summary>
/// City
/// </summary>
/// <value>City</value>
[DataMember(Name="city", EmitDefaultValue=false)]
public string City { get; set; }
/// <summary>
/// Company
/// </summary>
/// <value>Company</value>
[DataMember(Name="company", EmitDefaultValue=false)]
public string Company { get; set; }
/// <summary>
/// ISO-3166 two letter country code
/// </summary>
/// <value>ISO-3166 two letter country code</value>
[DataMember(Name="country_code", EmitDefaultValue=false)]
public string CountryCode { get; set; }
/// <summary>
/// Customer profile object identifier
/// </summary>
/// <value>Customer profile object identifier</value>
[DataMember(Name="customer_profile_oid", EmitDefaultValue=false)]
public int? CustomerProfileOid { get; set; }
/// <summary>
/// Email
/// </summary>
/// <value>Email</value>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// First name
/// </summary>
/// <value>First name</value>
[DataMember(Name="first_name", EmitDefaultValue=false)]
public string FirstName { get; set; }
/// <summary>
/// Item ID. Deprecated query field. This incorrectly meant the original order contained this item id.
/// </summary>
/// <value>Item ID. Deprecated query field. This incorrectly meant the original order contained this item id.</value>
[DataMember(Name="item_id", EmitDefaultValue=false)]
public string ItemId { get; set; }
/// <summary>
/// Last name
/// </summary>
/// <value>Last name</value>
[DataMember(Name="last_name", EmitDefaultValue=false)]
public string LastName { get; set; }
/// <summary>
/// Next Item ID that is supposed to ship. This is calculated based upon the schedule associated with the original item id.
/// </summary>
/// <value>Next Item ID that is supposed to ship. This is calculated based upon the schedule associated with the original item id.</value>
[DataMember(Name="next_item_id", EmitDefaultValue=false)]
public string NextItemId { get; set; }
/// <summary>
/// Next shipment date begin
/// </summary>
/// <value>Next shipment date begin</value>
[DataMember(Name="next_shipment_date_begin", EmitDefaultValue=false)]
public string NextShipmentDateBegin { get; set; }
/// <summary>
/// Next shipment date end
/// </summary>
/// <value>Next shipment date end</value>
[DataMember(Name="next_shipment_date_end", EmitDefaultValue=false)]
public string NextShipmentDateEnd { get; set; }
/// <summary>
/// Original Item ID purchased on auto order.
/// </summary>
/// <value>Original Item ID purchased on auto order.</value>
[DataMember(Name="original_item_id", EmitDefaultValue=false)]
public string OriginalItemId { get; set; }
/// <summary>
/// Original order date begin
/// </summary>
/// <value>Original order date begin</value>
[DataMember(Name="original_order_date_begin", EmitDefaultValue=false)]
public string OriginalOrderDateBegin { get; set; }
/// <summary>
/// Original order date end
/// </summary>
/// <value>Original order date end</value>
[DataMember(Name="original_order_date_end", EmitDefaultValue=false)]
public string OriginalOrderDateEnd { get; set; }
/// <summary>
/// Original order ID
/// </summary>
/// <value>Original order ID</value>
[DataMember(Name="original_order_id", EmitDefaultValue=false)]
public string OriginalOrderId { get; set; }
/// <summary>
/// Phone
/// </summary>
/// <value>Phone</value>
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/// <summary>
/// Postal code
/// </summary>
/// <value>Postal code</value>
[DataMember(Name="postal_code", EmitDefaultValue=false)]
public string PostalCode { get; set; }
/// <summary>
/// State
/// </summary>
/// <value>State</value>
[DataMember(Name="state", EmitDefaultValue=false)]
public string State { get; set; }
/// <summary>
/// Status
/// </summary>
/// <value>Status</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { 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 AutoOrderQuery {\n");
sb.Append(" AutoOrderCode: ").Append(AutoOrderCode).Append("\n");
sb.Append(" CardType: ").Append(CardType).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" Company: ").Append(Company).Append("\n");
sb.Append(" CountryCode: ").Append(CountryCode).Append("\n");
sb.Append(" CustomerProfileOid: ").Append(CustomerProfileOid).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" ItemId: ").Append(ItemId).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" NextItemId: ").Append(NextItemId).Append("\n");
sb.Append(" NextShipmentDateBegin: ").Append(NextShipmentDateBegin).Append("\n");
sb.Append(" NextShipmentDateEnd: ").Append(NextShipmentDateEnd).Append("\n");
sb.Append(" OriginalItemId: ").Append(OriginalItemId).Append("\n");
sb.Append(" OriginalOrderDateBegin: ").Append(OriginalOrderDateBegin).Append("\n");
sb.Append(" OriginalOrderDateEnd: ").Append(OriginalOrderDateEnd).Append("\n");
sb.Append(" OriginalOrderId: ").Append(OriginalOrderId).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" PostalCode: ").Append(PostalCode).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Status: ").Append(Status).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as AutoOrderQuery);
}
/// <summary>
/// Returns true if AutoOrderQuery instances are equal
/// </summary>
/// <param name="input">Instance of AutoOrderQuery to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AutoOrderQuery input)
{
if (input == null)
return false;
return
(
this.AutoOrderCode == input.AutoOrderCode ||
(this.AutoOrderCode != null &&
this.AutoOrderCode.Equals(input.AutoOrderCode))
) &&
(
this.CardType == input.CardType ||
(this.CardType != null &&
this.CardType.Equals(input.CardType))
) &&
(
this.City == input.City ||
(this.City != null &&
this.City.Equals(input.City))
) &&
(
this.Company == input.Company ||
(this.Company != null &&
this.Company.Equals(input.Company))
) &&
(
this.CountryCode == input.CountryCode ||
(this.CountryCode != null &&
this.CountryCode.Equals(input.CountryCode))
) &&
(
this.CustomerProfileOid == input.CustomerProfileOid ||
(this.CustomerProfileOid != null &&
this.CustomerProfileOid.Equals(input.CustomerProfileOid))
) &&
(
this.Email == input.Email ||
(this.Email != null &&
this.Email.Equals(input.Email))
) &&
(
this.FirstName == input.FirstName ||
(this.FirstName != null &&
this.FirstName.Equals(input.FirstName))
) &&
(
this.ItemId == input.ItemId ||
(this.ItemId != null &&
this.ItemId.Equals(input.ItemId))
) &&
(
this.LastName == input.LastName ||
(this.LastName != null &&
this.LastName.Equals(input.LastName))
) &&
(
this.NextItemId == input.NextItemId ||
(this.NextItemId != null &&
this.NextItemId.Equals(input.NextItemId))
) &&
(
this.NextShipmentDateBegin == input.NextShipmentDateBegin ||
(this.NextShipmentDateBegin != null &&
this.NextShipmentDateBegin.Equals(input.NextShipmentDateBegin))
) &&
(
this.NextShipmentDateEnd == input.NextShipmentDateEnd ||
(this.NextShipmentDateEnd != null &&
this.NextShipmentDateEnd.Equals(input.NextShipmentDateEnd))
) &&
(
this.OriginalItemId == input.OriginalItemId ||
(this.OriginalItemId != null &&
this.OriginalItemId.Equals(input.OriginalItemId))
) &&
(
this.OriginalOrderDateBegin == input.OriginalOrderDateBegin ||
(this.OriginalOrderDateBegin != null &&
this.OriginalOrderDateBegin.Equals(input.OriginalOrderDateBegin))
) &&
(
this.OriginalOrderDateEnd == input.OriginalOrderDateEnd ||
(this.OriginalOrderDateEnd != null &&
this.OriginalOrderDateEnd.Equals(input.OriginalOrderDateEnd))
) &&
(
this.OriginalOrderId == input.OriginalOrderId ||
(this.OriginalOrderId != null &&
this.OriginalOrderId.Equals(input.OriginalOrderId))
) &&
(
this.Phone == input.Phone ||
(this.Phone != null &&
this.Phone.Equals(input.Phone))
) &&
(
this.PostalCode == input.PostalCode ||
(this.PostalCode != null &&
this.PostalCode.Equals(input.PostalCode))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AutoOrderCode != null)
hashCode = hashCode * 59 + this.AutoOrderCode.GetHashCode();
if (this.CardType != null)
hashCode = hashCode * 59 + this.CardType.GetHashCode();
if (this.City != null)
hashCode = hashCode * 59 + this.City.GetHashCode();
if (this.Company != null)
hashCode = hashCode * 59 + this.Company.GetHashCode();
if (this.CountryCode != null)
hashCode = hashCode * 59 + this.CountryCode.GetHashCode();
if (this.CustomerProfileOid != null)
hashCode = hashCode * 59 + this.CustomerProfileOid.GetHashCode();
if (this.Email != null)
hashCode = hashCode * 59 + this.Email.GetHashCode();
if (this.FirstName != null)
hashCode = hashCode * 59 + this.FirstName.GetHashCode();
if (this.ItemId != null)
hashCode = hashCode * 59 + this.ItemId.GetHashCode();
if (this.LastName != null)
hashCode = hashCode * 59 + this.LastName.GetHashCode();
if (this.NextItemId != null)
hashCode = hashCode * 59 + this.NextItemId.GetHashCode();
if (this.NextShipmentDateBegin != null)
hashCode = hashCode * 59 + this.NextShipmentDateBegin.GetHashCode();
if (this.NextShipmentDateEnd != null)
hashCode = hashCode * 59 + this.NextShipmentDateEnd.GetHashCode();
if (this.OriginalItemId != null)
hashCode = hashCode * 59 + this.OriginalItemId.GetHashCode();
if (this.OriginalOrderDateBegin != null)
hashCode = hashCode * 59 + this.OriginalOrderDateBegin.GetHashCode();
if (this.OriginalOrderDateEnd != null)
hashCode = hashCode * 59 + this.OriginalOrderDateEnd.GetHashCode();
if (this.OriginalOrderId != null)
hashCode = hashCode * 59 + this.OriginalOrderId.GetHashCode();
if (this.Phone != null)
hashCode = hashCode * 59 + this.Phone.GetHashCode();
if (this.PostalCode != null)
hashCode = hashCode * 59 + this.PostalCode.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
return hashCode;
}
}
/// <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)
{
// CardType (string) maxLength
if(this.CardType != null && this.CardType.Length > 100)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CardType, length must be less than 100.", new [] { "CardType" });
}
// CountryCode (string) maxLength
if(this.CountryCode != null && this.CountryCode.Length > 2)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CountryCode, length must be less than 2.", new [] { "CountryCode" });
}
// Email (string) maxLength
if(this.Email != null && this.Email.Length > 100)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Email, length must be less than 100.", new [] { "Email" });
}
// Phone (string) maxLength
if(this.Phone != null && this.Phone.Length > 25)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Phone, length must be less than 25.", new [] { "Phone" });
}
yield break;
}
}
}
| |
using Elizabeth;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace mogate
{
public class HallOfFameEntry
{
public string PlayerName;
public int PlayerSpriteID;
public long TotalPlaytime;
}
public enum GameProgressState { Win, Death, InGame };
public interface IGameState
{
int Level { get; }
TimeSpan Playtime { get; }
string PlayerName { get; }
int PlayerSpriteID { get; set; }
int PlayerHealth { get; set; }
int PlayerHealthMax { get; set; }
int PlayerMoney { get; set; }
int PlayerMoveSpeed { get; set; }
int PlayerAttackSpeed { get; set; }
int PlayerViewDistanceType { get; set; }
int PlayerAntitodPotions { get; set; }
int PlayerAntitodPotionsMax { get; set; }
int PlayerWeaponID { get; set; }
int PlayerArmorID { get; set; }
float PlayerAttackMultiplier { get; set; }
float PlayerMoneyMultiplier { get; set; }
float PlayerPoisonChanceMultiplier { get; set; }
float PlayerAttackDistanceMultiplier { get; set; }
GameProgressState GameProgress { get; set; }
bool CountPlaytime { get; set; }
List<HallOfFameEntry> HallOfFame { get; }
bool IsLoaded { get; }
void NewGame ();
void ContinueGame ();
void NextLevel ();
void ApplyArchetype (Dictionary<string, float> archetype);
}
[DataContract]
public class MogateSaveData
{
[DataMember]
public int Level;
[DataMember]
public long PlaytimeTicks;
[DataMember]
public int PlayerHealth;
[DataMember]
public int PlayerHealthMax;
[DataMember]
public int PlayerAntitodPotions;
[DataMember]
public int PlayerAntitodPotionsMax;
[DataMember]
public int PlayerMoney;
[DataMember]
public int PlayerViewDistanceType;
[DataMember]
public int PlayerAttackSpeed;
[DataMember]
public int PlayerMoveSpeed;
[DataMember]
public int PlayerSpriteID;
[DataMember]
public int PlayerWeaponID;
[DataMember]
public int PlayerArmorID;
[DataMember]
public float PlayerAttackMultiplier;
[DataMember]
public float PlayerMoneyMultiplier;
[DataMember]
public float PlayerPoisonChanceMultiplier;
[DataMember]
public float PlayerAttackDistanceMultiplier;
[DataMember]
public string PlayerName;
[DataMember]
public List<HallOfFameEntry> HallOfFame;
}
public class GameState : GameComponent, IGameState
{
public bool IsLoaded { get; private set; }
public int Level { get; private set; }
public TimeSpan Playtime { get; private set; }
public GameProgressState GameProgress { get; set; }
public int PlayerSpriteID { get; set; }
public int PlayerHealth { get; set; }
public int PlayerHealthMax { get; set; }
public int PlayerViewDistanceType { get; set; }
public int PlayerMoney { get; set; }
public int PlayerMoveSpeed { get; set; }
public int PlayerAttackSpeed { get; set; }
public int PlayerAntitodPotions { get; set; }
public int PlayerAntitodPotionsMax { get; set; }
public float PlayerAttackMultiplier { get; set; }
public float PlayerMoneyMultiplier { get; set; }
public float PlayerPoisonChanceMultiplier { get; set; }
public float PlayerAttackDistanceMultiplier { get; set; }
public int PlayerWeaponID { get; set; }
public int PlayerArmorID { get; set; }
public string PlayerName { get; private set; }
public bool CountPlaytime { get; set; }
public List<HallOfFameEntry> HallOfFame { get; private set; }
private ICheckpoint<MogateSaveData> Checkpoint { get; }
public GameState(Game game) : base(game)
{
CountPlaytime = false;
HallOfFame = new List<HallOfFameEntry>();
InitGame();
IsLoaded = false;
Checkpoint = new Checkpoint<MogateSaveData>();
}
public override void Update (GameTime gameTime)
{
if (!IsLoaded) {
LoadGame ();
}
if (CountPlaytime) {
Playtime += gameTime.ElapsedGameTime;
}
base.Update(gameTime);
}
public void NewGame()
{
var world = (IWorld)Game.Services.GetService(typeof(IWorld));
world.GenerateLevels (Globals.MAX_LEVELS);
InitGame ();
SaveGame ();
}
public void ContinueGame()
{
var world = (IWorld)Game.Services.GetService(typeof(IWorld));
world.GenerateLevels (Globals.MAX_LEVELS);
}
public void NextLevel()
{
Level = Level + 1;
if (Level == Globals.MAX_LEVELS) {
GameProgress = GameProgressState.Win;
Level = 0;
UpdateHallOfFame ();
}
SaveGame ();
}
public void ApplyArchetype(Dictionary<string, float> archetype)
{
PlayerHealth = (int)archetype ["health_packs"] * Globals.HEALTH_PACK;
PlayerHealthMax = (int)archetype ["health_packs_max"] * Globals.HEALTH_PACK;
PlayerMoveSpeed = (int)archetype ["move_duration_msec"];
PlayerWeaponID = 0;
PlayerArmorID = -1;
PlayerMoney = 0;
PlayerAntitodPotions = 0;
PlayerSpriteID = (int)archetype ["sprite_index"];
PlayerName = NameGenerator.Generate ();
PlayerAttackSpeed = (int)archetype ["attack_duration_msec"];
PlayerViewDistanceType = (int)archetype ["view_distance_type"];
PlayerAntitodPotionsMax = (int)archetype ["antitod_potions_max"];
PlayerMoneyMultiplier = archetype ["money_multiplier"];
PlayerAttackMultiplier = archetype ["attack_multiplier"];
PlayerPoisonChanceMultiplier = archetype ["poison_chance_multiplier"];
PlayerAttackDistanceMultiplier = archetype ["attack_distance_multiplier"];
}
void UpdateHallOfFame()
{
HallOfFame.Add (new HallOfFameEntry {
PlayerName = this.PlayerName,
PlayerSpriteID = this.PlayerSpriteID,
TotalPlaytime = this.Playtime.Ticks
});
HallOfFame = HallOfFame.OrderBy(o => o.TotalPlaytime).ToList();
int count = HallOfFame.Count;
if (count > Globals.HALL_OF_FAME_SIZE) {
HallOfFame.RemoveRange (Globals.HALL_OF_FAME_SIZE, count - Globals.HALL_OF_FAME_SIZE);
}
}
void InitGame()
{
Level = 0;
GameProgress = GameProgressState.InGame;
Playtime = TimeSpan.Zero;
var arch = Archetypes.Players.First ();
ApplyArchetype (arch);
}
void LoadGame()
{
var save = Checkpoint.Load("mogate.sav");
if (save != null)
{
Level = save.Level;
PlayerName = save.PlayerName;
Playtime = TimeSpan.FromTicks(save.PlaytimeTicks);
PlayerHealth = save.PlayerHealth;
PlayerHealthMax = save.PlayerHealthMax;
PlayerAntitodPotions = save.PlayerAntitodPotions;
PlayerAntitodPotionsMax = save.PlayerAntitodPotionsMax;
PlayerMoney = save.PlayerMoney;
PlayerViewDistanceType = save.PlayerViewDistanceType;
PlayerAttackDistanceMultiplier = save.PlayerAttackDistanceMultiplier;
PlayerMoneyMultiplier = save.PlayerMoneyMultiplier;
PlayerAttackMultiplier = save.PlayerAttackMultiplier;
PlayerPoisonChanceMultiplier = save.PlayerPoisonChanceMultiplier;
PlayerAttackSpeed = save.PlayerAttackSpeed;
PlayerMoveSpeed = save.PlayerMoveSpeed;
PlayerSpriteID = save.PlayerSpriteID;
PlayerArmorID = save.PlayerArmorID;
PlayerWeaponID = save.PlayerWeaponID;
HallOfFame = save.HallOfFame;
}
IsLoaded = true;
}
void SaveGame()
{
var save = new MogateSaveData {
Level = this.Level,
PlayerName = this.PlayerName,
PlaytimeTicks = this.Playtime.Ticks,
PlayerHealth = this.PlayerHealth,
PlayerHealthMax = this.PlayerHealthMax,
PlayerAntitodPotions = this.PlayerAntitodPotions,
PlayerAntitodPotionsMax = this.PlayerAntitodPotionsMax,
PlayerMoney = this.PlayerMoney,
PlayerViewDistanceType = this.PlayerViewDistanceType,
PlayerAttackDistanceMultiplier = this.PlayerAttackDistanceMultiplier,
PlayerMoneyMultiplier = this.PlayerMoneyMultiplier,
PlayerAttackMultiplier = this.PlayerAttackMultiplier,
PlayerPoisonChanceMultiplier = this.PlayerPoisonChanceMultiplier,
PlayerAttackSpeed = this.PlayerAttackSpeed,
PlayerMoveSpeed = this.PlayerMoveSpeed,
PlayerSpriteID = this.PlayerSpriteID,
PlayerArmorID= this.PlayerArmorID,
PlayerWeaponID = this.PlayerWeaponID,
HallOfFame = this.HallOfFame
};
Checkpoint.Save(save, "mogate.sav");
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System.Collections;
namespace Soomla.Store {
/// <summary>
/// An upgrade virtual good is one VG in a series of VGs that define an upgrade scale of an
/// associated <c>VirtualGood</c>.
///
/// This type of virtual good is best explained with an example:
/// Let's say there's a strength attribute to one of the characters in your game and that strength is
/// on a scale of 1-5. You want to provide your users with the ability to upgrade that strength.
///
/// This is what you'll need to create:
/// 1. <c>SingleUseVG</c> for 'strength'
/// 2. <c>UpgradeVG</c> for strength 'level 1'
/// 3. <c>UpgradeVG</c> for strength 'level 2'
/// 4. <c>UpgradeVG</c> for strength 'level 3'
/// 5. <c>UpgradeVG</c> for strength 'level 4'
/// 6. <c>UpgradeVG</c> for strength 'level 5'
///
/// When the user buys this <c>UpgradeVG</c>, we check and make sure the appropriate conditions
/// are met and buy it for you (which actually means we upgrade the associated <c>VirtualGood</c>).
///
/// NOTE: In case you want this item to be available for purchase with real money
/// you will need to define the item in the market (App Store, Google Play...).
///
/// Inheritance: UpgradeVG >
/// <see cref="com.soomla.store.domain.virtualGoods.VirtualGood"/> >
/// <see cref="com.soomla.store.domain.PurchasableVirtualItem"/> >
/// <see cref="com.soomla.store.domain.VirtualItem"/>
/// </summary>
public class UpgradeVG : LifetimeVG {
private static string TAG = "SOOMLA UpgradeVG";
/// <summary>
/// The itemId of the associated <c>VirtualGood</c>.
/// </summary>
public string GoodItemId;
/// <summary>
/// The itemId of the <c>UpgradeVG</c> that comes after this one (or null this is the last one)
/// </summary>
public string NextItemId;
/// <summary>
/// The itemId of the <c>UpgradeVG</c> that comes before this one (or null this is the first one)
/// </summary>
public string PrevItemId;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="goodItemId">The itemId of the <c>VirtualGood</c> associated with this upgrade.</param>
/// <param name="nextItemId">The itemId of the <c>UpgradeVG</c> after, or if this is the last
/// <c>UpgradeVG</c> in the scale then the value is null.</param>
/// <param name="prevItemId">The itemId of the <c>UpgradeVG</c> before, or if this is the first
/// <c>UpgradeVG</c> in the scale then the value is null.</param>
/// <param name="name">nName.</param>
/// <param name="description">Description.</param>
/// <param name="itemId">Item id.</param>
/// <param name="purchaseType">Purchase type.</param>
public UpgradeVG(string goodItemId, string nextItemId, string prevItemId, string name, string description, string itemId, PurchaseType purchaseType)
: base(name, description, itemId, purchaseType)
{
this.GoodItemId = goodItemId;
this.PrevItemId = prevItemId;
this.NextItemId = nextItemId;
}
/// <summary>
/// see parent.
/// </summary>
public UpgradeVG(JSONObject jsonItem)
: base(jsonItem)
{
GoodItemId = jsonItem[StoreJSONConsts.VGU_GOOD_ITEMID].str;
PrevItemId = jsonItem[StoreJSONConsts.VGU_PREV_ITEMID].str;
NextItemId = jsonItem[StoreJSONConsts.VGU_NEXT_ITEMID].str;
}
/// <summary>
/// see parent.
/// </summary>
public override JSONObject toJSONObject()
{
JSONObject jsonObject = base.toJSONObject();
jsonObject.AddField(StoreJSONConsts.VGU_GOOD_ITEMID, this.GoodItemId);
jsonObject.AddField(StoreJSONConsts.VGU_PREV_ITEMID, string.IsNullOrEmpty(this.PrevItemId) ? "" : this.PrevItemId);
jsonObject.AddField(StoreJSONConsts.VGU_NEXT_ITEMID, string.IsNullOrEmpty(this.NextItemId) ? "" : this.NextItemId);
return jsonObject;
}
/// <summary>
/// Determines if the user is in a state that allows him/her to buy an <code>UpgradeVG</code>
/// This method enforces allowing/rejecting of upgrades here so users won't buy them when
/// they are not supposed to.
/// If you want to give your users free upgrades, use the <code>give</code> function.
/// </summary>
/// <returns><c>true</c>, if can buy, <c>false</c> otherwise.</returns>
protected override bool canBuy() {
VirtualGood good = null;
try {
good = (VirtualGood) StoreInfo.GetItemByItemId(GoodItemId);
} catch (VirtualItemNotFoundException) {
SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + GoodItemId +
" doesn't exist! Returning NO (can't buy).");
return false;
}
UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good);
return ((upgradeVG == null && string.IsNullOrEmpty(PrevItemId)) ||
(upgradeVG != null && ((upgradeVG.NextItemId == this.ItemId) ||
(upgradeVG.PrevItemId == this.ItemId))))
&& base.canBuy();
}
/// <summary>
/// Assigns the current upgrade to the associated <code>VirtualGood</code> (mGood).
/// </summary>
/// <param name="amount">NOT USED HERE!</param>
/// <param name="notify">notify of change in user's balance of current virtual item.</param>
public override int Give(int amount, bool notify) {
SoomlaUtils.LogDebug(TAG, "Assigning " + Name + " to: " + GoodItemId);
VirtualGood good = null;
try {
good = (VirtualGood) StoreInfo.GetItemByItemId(GoodItemId);
} catch (VirtualItemNotFoundException) {
SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + GoodItemId +
" doesn't exist! Can't upgrade.");
return 0;
}
VirtualGoodsStorage.AssignCurrentUpgrade(good, this, notify);
return base.Give(amount, notify);
}
/// <summary>
/// Takes upgrade from the user, or in other words DOWNGRADES the associated
/// <code>VirtualGood</code> (mGood).
/// Checks if the current Upgrade is really associated with the <code>VirtualGood</code> and:
/// </summary>
/// <param name="amount">NOT USED HERE!.</param>
/// <param name="notify">see parent.</param>
public override int Take(int amount, bool notify) {
VirtualGood good = null;
try {
good = (VirtualGood) StoreInfo.GetItemByItemId(GoodItemId);
} catch (VirtualItemNotFoundException) {
SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + GoodItemId
+ " doesn't exist! Can't downgrade.");
return 0;
}
UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good);
// Case: Upgrade is not assigned to this Virtual Good
if (upgradeVG != this) {
SoomlaUtils.LogError(TAG, "You can't take an upgrade that's not currently assigned."
+ "The UpgradeVG " + Name + " is not assigned to " + "the VirtualGood: "
+ good.Name);
return 0;
}
if (!string.IsNullOrEmpty(PrevItemId)) {
UpgradeVG prevUpgradeVG = null;
// Case: downgrade is not possible because previous upgrade does not exist
try {
prevUpgradeVG = (UpgradeVG)StoreInfo.GetItemByItemId(PrevItemId);
} catch (VirtualItemNotFoundException) {
SoomlaUtils.LogError(TAG, "Previous UpgradeVG with itemId: " + PrevItemId
+ " doesn't exist! Can't downgrade.");
return 0;
}
// Case: downgrade is successful!
SoomlaUtils.LogDebug(TAG, "Downgrading " + good.Name + " to: "
+ prevUpgradeVG.Name);
VirtualGoodsStorage.AssignCurrentUpgrade(good, prevUpgradeVG, notify);
}
// Case: first Upgrade in the series - so we downgrade to NO upgrade.
else {
SoomlaUtils.LogDebug(TAG, "Downgrading " + good.Name + " to NO-UPGRADE");
VirtualGoodsStorage.RemoveUpgrades(good, notify);
}
return base.Take(amount, notify);
}
}
}
| |
namespace Appleseed.Framework.Content.Security
{
using System;
using System.Security.Cryptography;
/// <summary>
/// The random password.
/// </summary>
public class RandomPassword
{
#region Constants and Fields
/// <summary>
/// The default max password length.
/// </summary>
private const int DefaultMaxPasswordLength = 10;
/// <summary>
/// The default min password length.
/// </summary>
private const int DefaultMinPasswordLength = 8;
/// <summary>
/// The password chars lcase.
/// </summary>
private const string PasswordCharsLcase = "abcdefgijkmnopqrstwxyz";
/// <summary>
/// The password chars numeric.
/// </summary>
private const string PasswordCharsNumeric = "23456789";
/// <summary>
/// The password chars special.
/// </summary>
private const string PasswordCharsSpecial = "*$-+?_&=!%{}/";
/// <summary>
/// The password chars ucase.
/// </summary>
private const string PasswordCharsUcase = "ABCDEFGHJKLMNPQRSTWXYZ";
#endregion
#region Public Methods
/// <summary>
/// Generates a random password.
/// </summary>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random. It will be no shorter than the minimum default and
/// no longer than maximum default.
/// </remarks>
public static string Generate()
{
return Generate(DefaultMinPasswordLength, DefaultMaxPasswordLength);
}
/// <summary>
/// Generates a random password of the exact length.
/// </summary>
/// <param name="length">
/// Exact password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
public static string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password.
/// </summary>
/// <param name="minLength">
/// Minimum password length.
/// </param>
/// <param name="maxLength">
/// Maximum password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random and it will fall with the range determined by the
/// function parameters.
/// </remarks>
public static string Generate(int minLength, int maxLength)
{
// Make sure that input parameters are valid.
if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
{
return null;
}
// Create a local array containing supported password characters
// grouped by types. You can remove character groups from this
// array, but doing so will weaken the password strength.
var charGroups = new[]
{
PasswordCharsLcase.ToCharArray(),
PasswordCharsUcase.ToCharArray(),
PasswordCharsNumeric.ToCharArray(),
PasswordCharsSpecial.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
var charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (var i = 0; i < charsLeftInGroup.Length; i++)
{
charsLeftInGroup[i] = charGroups[i].Length;
}
// Use this array to track (iterate through) unused character groups.
var leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (var i = 0; i < leftGroupsOrder.Length; i++)
{
leftGroupsOrder[i] = i;
}
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
var randomBytes = new byte[4];
// Generate 4 random bytes.
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
var seed = (randomBytes[0] & 0x7f) << 24 | randomBytes[1] << 16 | randomBytes[2] << 8 | randomBytes[3];
// Now, this is real randomization.
var random = new Random(seed);
// This array will hold password characters.
// Allocate appropriate memory for the password.
var password = minLength < maxLength ? new char[random.Next(minLength, maxLength + 1)] : new char[minLength];
// Index of the last non-processed group.
var lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for (var i = 0; i < password.Length; i++)
{
// Index which will be used to track not processed character groups.
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
var nextLeftGroupsOrderIdx = lastLeftGroupsOrderIdx == 0 ? 0 : random.Next(0, lastLeftGroupsOrderIdx);
// Index of the next character group to be processed.
// Get the actual index of the character group, from which we will
// pick the next character.
var nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Index of the last non-processed character in a group.
// Get the index of the last unprocessed characters in this group.
var lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// Index of the next character to be added to password.
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
var nextCharIdx = lastCharIdx == 0 ? 0 : random.Next(0, lastCharIdx + 1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
{
charsLeftInGroup[nextGroupIdx] = charGroups[nextGroupIdx].Length;
}
else
{
// There are more unprocessed characters left.
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
{
var temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] = charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
{
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
}
else
{
// There are more unprocessed groups left.
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
var temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] = leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using ModernHttpClient;
using RealtimeFramework.Messaging.Ext;
using RealtimeFramework.Messaging.Exceptions;
namespace RealtimeFramework.Messaging {
/// <summary>
/// Class with static methods for authentication and presence management.
/// </summary>
public static class Ortc {
/// <summary>
/// The channel permission.
/// </summary>
public enum ChannelPermissions {
/// <summary>
/// Read permission
/// </summary>
Read = 'r',
/// <summary>
/// Read and Write permission
/// </summary>
Write = 'w',
/// <summary>
/// Presence permission
/// </summary>
Presence = 'p'
}
/// <summary>
/// Saves the authentication token channels permissions in the ORTC server.
/// </summary>
/// <param name="url">ORTC server URL.</param>
/// <param name="isCluster">Indicates whether the ORTC server is in a cluster.</param>
/// <param name="authenticationToken">Authentication Token which is generated by the application server, for instance a unique session ID.</param>
/// <param name="authenticationTokenIsPrivate">Indicates whether the authentication token is private (1) or not (0).</param>
/// <param name="applicationKey">Application Key that was provided to you together with the ORTC service purchasing.</param>
/// <param name="timeToLive">The authentication token time to live, in other words, the allowed activity time (in seconds).</param>
/// <param name="privateKey">The private key provided to you together with the ORTC service purchasing.</param>
/// <param name="permissions">The channels and their permissions (w: write/read or r: read, case sensitive).</param>
/// <returns>True if the authentication was successful or false if it was not.</returns>
/// <exception cref="OrtcEmptyFieldException">Server URL can not be null or empty.</exception>
/// <exception cref="OrtcAuthenticationNotAuthorizedException">Unauthorized by the server.</exception>
/// <exception cref="OrtcNotConnectedException">Unable to connect to the authentication server.</exception>
/// <example>
/// <code>
/// // Permissions
/// Dictionary;string, ChannelPermissions; permissions = new Dictionary;string, ChannelPermissions;();
///
/// permissions.Add("channel1", ChannelPermissions.Read);
/// permissions.Add("channel2", ChannelPermissions.Write);
///
/// string url = "http://ortc-developers.realtime.co/server/2.1";
/// bool isCluster = true;
/// string authenticationToken = "myAuthenticationToken";
/// bool authenticationTokenIsPrivate = true;
/// string applicationKey = "myApplicationKey";
/// int timeToLive = 1800; // 30 minutes
/// string privateKey = "myPrivateKey";
///
/// bool authSaved = Ibt.Ortc.Api.Ortc.SaveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions))
/// </code>
/// </example>
public static bool SaveAuthentication(string url, bool isCluster, string authenticationToken, bool authenticationTokenIsPrivate,
string applicationKey, int timeToLive, string privateKey, Dictionary<string, ChannelPermissions> permissions) {
var result = false;
if (permissions != null && permissions.Count > 0) {
var multiPermissions = new Dictionary<string, List<ChannelPermissions>>();
foreach (var permission in permissions) {
var permissionList = new List<ChannelPermissions>();
permissionList.Add(permission.Value);
multiPermissions.Add(permission.Key, permissionList);
}
result = Ortc.SaveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, multiPermissions);
}
return result;
}
/// <summary>
/// Saves the authentication token channels permissions in the ORTC server.
/// </summary>
/// <param name="url">ORTC server URL.</param>
/// <param name="isCluster">Indicates whether the ORTC server is in a cluster.</param>
/// <param name="authenticationToken">Authentication Token which is generated by the application server, for instance a unique session ID.</param>
/// <param name="authenticationTokenIsPrivate">Indicates whether the authentication token is private (1) or not (0).</param>
/// <param name="applicationKey">Application Key that was provided to you together with the ORTC service purchasing.</param>
/// <param name="timeToLive">The authentication token time to live, in other words, the allowed activity time (in seconds).</param>
/// <param name="privateKey">The private key provided to you together with the ORTC service purchasing.</param>
/// <param name="permissions">The channels and their permissions (w: write/read or r: read, case sensitive).</param>
/// <returns>True if the authentication was successful or false if it was not.</returns>
/// <exception cref="OrtcEmptyFieldException">Server URL can not be null or empty.</exception>
/// <exception cref="OrtcAuthenticationNotAuthorizedException">Unauthorized by the server.</exception>
/// <exception cref="OrtcNotConnectedException">Unable to connect to the authentication server.</exception>
/// <example>
/// <code>
/// // Permissions
/// Dictionary;string, ChannelPermissions; permissions = new Dictionary;string, List;ChannelPermissions;;();
///
/// Dictionary;string, List;ChannelPermissions;; channelPermissions = new Dictionary;string, List;ChannelPermissions;;();
/// var permissionsList = new List;ChannelPermissions;();
///
/// permissionsList.Add(ChannelPermissions.Write);
/// permissionsList.Add(ChannelPermissions.Presence);
///
/// channelPermissions.Add("channel1", permissionsList);
///
/// string url = "http://ortc-developers.realtime.co/server/2.1";
/// bool isCluster = true;
/// string authenticationToken = "myAuthenticationToken";
/// bool authenticationTokenIsPrivate = true;
/// string applicationKey = "myApplicationKey";
/// int timeToLive = 1800; // 30 minutes
/// string privateKey = "myPrivateKey";
///
/// bool authSaved = Ibt.Ortc.Api.Ortc.SaveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, channelPermissions))
/// </code>
/// </example>
public static bool SaveAuthentication(string url, bool isCluster, string authenticationToken, bool authenticationTokenIsPrivate,
string applicationKey, int timeToLive, string privateKey, Dictionary<string, List<ChannelPermissions>> permissions) {
if (String.IsNullOrEmpty(url)) {
throw new OrtcEmptyFieldException("URL is null or empty.");
} else if (String.IsNullOrEmpty(applicationKey)) {
throw new OrtcEmptyFieldException("Application Key is null or empty.");
} else if (String.IsNullOrEmpty(authenticationToken)) {
throw new OrtcEmptyFieldException("Authentication Token is null or empty.");
} else if (String.IsNullOrEmpty(privateKey)) {
throw new OrtcEmptyFieldException("Private Key is null or empty.");
}
string connectionUrl = url;
if (isCluster) {
connectionUrl = Balancer.ResolveClusterUrl(url);
}
if (String.IsNullOrEmpty(connectionUrl)) {
throw new OrtcNotConnectedException("Unable to get URL from cluster");
}
connectionUrl = connectionUrl.EndsWith("/") ? connectionUrl + "authenticate" : connectionUrl + "/authenticate";
string postParameters = String.Format("AT={0}&PVT={1}&AK={2}&TTL={3}&PK={4}", authenticationToken, authenticationTokenIsPrivate ? 1 : 0, applicationKey, timeToLive, privateKey);
if (permissions != null && permissions.Count > 0) {
postParameters += String.Format("&TP={0}", permissions.Count);
foreach (var permission in permissions) {
var permissionItemText = String.Format("{0}=", permission.Key);
foreach (var permissionItemValue in permission.Value.ToList()) {
permissionItemText += ((char)permissionItemValue).ToString();
}
postParameters += String.Format("&{0}", permissionItemText);
}
}
HttpContent content = new StringContent(postParameters);
using (var client = new HttpClient(new NativeMessageHandler())) {
var response = client.PostAsync(new Uri(connectionUrl), content).Result;
if (response.IsSuccessStatusCode) {
return true;
} else {
throw new OrtcAuthenticationNotAuthorizedException(response.Content.ReadAsStringAsync().Result);
}
}
}
/// <summary>
/// Gets the subscriptions in the specified channel and if active the first 100 unique metadata.
/// </summary>
/// <param name="url">Server containing the presence service.</param>
/// <param name="isCluster">Specifies if url is cluster</param>
/// <param name="applicationKey">Application key with access to presence service.</param>
/// <param name="authenticationToken">Authentication token with access to presence service.</param>
/// <param name="channel">Channel with presence data active.</param>
/// <param name="callback"><see cref="OnPresenceDelegate"/>Callback with error <see cref="OrtcPresenceException"/> and result <see cref="Presence"/>.</param>
/// <example>
/// <code>
/// client.Presence("presence-channel", (error, result) =>
/// {
/// if (error != null)
/// {
/// System.Diagnostics.Debug.Writeline(error.Message);
/// }
/// else
/// {
/// if (result != null)
/// {
/// System.Diagnostics.Debug.Writeline(result.Subscriptions);
///
/// if (result.Metadata != null)
/// {
/// foreach (var metadata in result.Metadata)
/// {
/// System.Diagnostics.Debug.Writeline(metadata.Key + " - " + metadata.Value);
/// }
/// }
/// }
/// else
/// {
/// System.Diagnostics.Debug.Writeline("There is no presence data");
/// }
/// }
/// });
/// </code>
/// </example>
public static void Presence(String url, Boolean isCluster, String applicationKey, String authenticationToken, String channel, OnPresenceDelegate callback) {
Ext.Presence.GetPresence(url, isCluster, applicationKey, authenticationToken, channel, callback);
}
/// <summary>
/// Enables presence for the specified channel with first 100 unique metadata if metadata is set to true.
/// </summary>
/// <param name="url">Server containing the presence service.</param>
/// <param name="isCluster">Specifies if url is cluster</param>
/// <param name="applicationKey">Application key with access to presence service.</param>
/// <param name="privateKey">The private key provided when the ORTC service is purchased.</param>
/// <param name="channel">Channel to activate presence.</param>
/// <param name="metadata">Defines if to collect first 100 unique metadata.</param>
/// <param name="callback">Callback with error <see cref="OrtcPresenceException"/> and result.</param>
/// /// <example>
/// <code>
/// client.EnablePresence("myPrivateKey", "presence-channel", false, (error, result) =>
/// {
/// if (error != null)
/// {
/// System.Diagnostics.Debug.Writeline(error.Message);
/// }
/// else
/// {
/// System.Diagnostics.Debug.Writeline(result);
/// }
/// });
/// </code>
/// </example>
public static void EnablePresence(String url, Boolean isCluster, String applicationKey, String privateKey, String channel, bool metadata, OnEnablePresenceDelegate callback) {
Ext.Presence.EnablePresence(url, isCluster, applicationKey, privateKey, channel, metadata, callback);
}
/// <summary>
/// Disables presence for the specified channel.
/// </summary>
/// <param name="url">Server containing the presence service.</param>
/// <param name="isCluster">Specifies if url is cluster</param>
/// <param name="applicationKey">Application key with access to presence service.</param>
/// <param name="privateKey">The private key provided when the ORTC service is purchased.</param>
/// <param name="channel">Channel to disable presence.</param>
/// <param name="callback">Callback with error <see cref="OrtcPresenceException"/> and result.</param>
public static void DisablePresence(String url, Boolean isCluster, String applicationKey, String privateKey, String channel, OnDisablePresenceDelegate callback) {
Ext.Presence.DisablePresence(url, isCluster, applicationKey, privateKey, channel, callback);
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog
{
using System;
using System.Collections.Generic;
using NLog.Internal;
/// <summary>
/// Async version of Mapped Diagnostics Context - a logical context structure that keeps a dictionary
/// of strings and provides methods to output them in layouts. Allows for maintaining state across
/// asynchronous tasks and call contexts.
/// </summary>
/// <remarks>
/// Ideally, these changes should be incorporated as a new version of the MappedDiagnosticsContext class in the original
/// NLog library so that state can be maintained for multiple threads in asynchronous situations.
/// </remarks>
public static class MappedDiagnosticsLogicalContext
{
/// <summary>
/// Simulate ImmutableDictionary behavior (which is not yet part of all .NET frameworks).
/// In future the real ImmutableDictionary could be used here to minimize memory usage and copying time.
/// </summary>
/// <param name="clone">Must be true for any subsequent dictionary modification operation</param>
/// <returns></returns>
private static IDictionary<string, object> GetLogicalThreadDictionary(bool clone = false)
{
var dictionary = GetThreadLocal();
if (dictionary == null)
{
if (!clone)
return EmptyDefaultDictionary;
dictionary = new Dictionary<string, object>();
SetThreadLocal(dictionary);
}
else if (clone)
{
dictionary = new Dictionary<string, object>(dictionary);
SetThreadLocal(dictionary);
}
return dictionary;
}
/// <summary>
/// Gets the current logical context named item, as <see cref="string"/>.
/// </summary>
/// <param name="item">Item name.</param>
/// <returns>The value of <paramref name="item"/>, if defined; otherwise <see cref="String.Empty"/>.</returns>
/// <remarks>If the value isn't a <see cref="string"/> already, this call locks the <see cref="LogFactory"/> for reading the <see cref="Config.LoggingConfiguration.DefaultCultureInfo"/> needed for converting to <see cref="string"/>. </remarks>
public static string Get(string item)
{
return Get(item, null);
}
/// <summary>
/// Gets the current logical context named item, as <see cref="string"/>.
/// </summary>
/// <param name="item">Item name.</param>
/// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param>
/// <returns>The value of <paramref name="item"/>, if defined; otherwise <see cref="String.Empty"/>.</returns>
/// <remarks>If <paramref name="formatProvider"/> is <c>null</c> and the value isn't a <see cref="string"/> already, this call locks the <see cref="LogFactory"/> for reading the <see cref="Config.LoggingConfiguration.DefaultCultureInfo"/> needed for converting to <see cref="string"/>. </remarks>
public static string Get(string item, IFormatProvider formatProvider)
{
return FormatHelper.ConvertToString(GetObject(item), formatProvider);
}
/// <summary>
/// Gets the current logical context named item, as <see cref="object"/>.
/// </summary>
/// <param name="item">Item name.</param>
/// <returns>The value of <paramref name="item"/>, if defined; otherwise <c>null</c>.</returns>
public static object GetObject(string item)
{
object value;
GetLogicalThreadDictionary().TryGetValue(item, out value);
return value;
}
/// <summary>
/// Sets the current logical context item to the specified value.
/// </summary>
/// <param name="item">Item name.</param>
/// <param name="value">Item value.</param>
public static void Set(string item, string value)
{
GetLogicalThreadDictionary(true)[item] = value;
}
/// <summary>
/// Sets the current logical context item to the specified value.
/// </summary>
/// <param name="item">Item name.</param>
/// <param name="value">Item value.</param>
public static void Set(string item, object value)
{
GetLogicalThreadDictionary(true)[item] = value;
}
/// <summary>
/// Returns all item names
/// </summary>
/// <returns>A collection of the names of all items in current logical context.</returns>
public static ICollection<string> GetNames()
{
return GetLogicalThreadDictionary().Keys;
}
/// <summary>
/// Checks whether the specified <paramref name="item"/> exists in current logical context.
/// </summary>
/// <param name="item">Item name.</param>
/// <returns>A boolean indicating whether the specified <paramref name="item"/> exists in current logical context.</returns>
public static bool Contains(string item)
{
return GetLogicalThreadDictionary().ContainsKey(item);
}
/// <summary>
/// Removes the specified <paramref name="item"/> from current logical context.
/// </summary>
/// <param name="item">Item name.</param>
public static void Remove(string item)
{
GetLogicalThreadDictionary(true).Remove(item);
}
/// <summary>
/// Clears the content of current logical context.
/// </summary>
public static void Clear()
{
Clear(false);
}
/// <summary>
/// Clears the content of current logical context.
/// </summary>
/// <param name="free">Free the full slot.</param>
public static void Clear(bool free)
{
if (free)
{
SetThreadLocal(null);
}
else
{
GetLogicalThreadDictionary(true).Clear();
}
}
private static void SetThreadLocal(IDictionary<string, object> newValue)
{
#if NET4_6 || NETSTANDARD
AsyncLocalDictionary.Value = newValue;
#else
if (newValue == null)
System.Runtime.Remoting.Messaging.CallContext.FreeNamedDataSlot(LogicalThreadDictionaryKey);
else
System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(LogicalThreadDictionaryKey, newValue);
#endif
}
private static IDictionary<string, object> GetThreadLocal()
{
#if NET4_6 || NETSTANDARD
return AsyncLocalDictionary.Value;
#else
return System.Runtime.Remoting.Messaging.CallContext.LogicalGetData(LogicalThreadDictionaryKey) as Dictionary<string, object>;
#endif
}
#if NET4_6 || NETSTANDARD
private static readonly System.Threading.AsyncLocal<IDictionary<string, object>> AsyncLocalDictionary = new System.Threading.AsyncLocal<IDictionary<string, object>>();
#else
private const string LogicalThreadDictionaryKey = "NLog.AsyncableMappedDiagnosticsContext";
#endif
private static readonly IDictionary<string, object> EmptyDefaultDictionary = new SortHelpers.ReadOnlySingleBucketDictionary<string, object>();
}
}
#endif
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// InviteResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Chat.V1.Service.Channel
{
public class InviteResource : Resource
{
private static Request BuildFetchRequest(FetchInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Fetch(FetchInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> FetchAsync(FetchInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to fetch belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Fetch(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to fetch belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> FetchAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Create(CreateInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> CreateAsync(CreateInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param>
/// <param name="identity"> The `identity` value that identifies the new resource's User </param>
/// <param name="roleSid"> The Role assigned to the new member </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Create(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateInviteOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to create the resource under </param>
/// <param name="pathChannelSid"> The SID of the Channel the new resource belongs to </param>
/// <param name="identity"> The `identity` value that identifies the new resource's User </param>
/// <param name="roleSid"> The Role assigned to the new member </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> CreateAsync(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateInviteOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static ResourceSet<InviteResource> Read(ReadInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<InviteResource>.FromJson("invites", response.Content);
return new ResourceSet<InviteResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<ResourceSet<InviteResource>> ReadAsync(ReadInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<InviteResource>.FromJson("invites", response.Content);
return new ResourceSet<InviteResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resources to read belong to </param>
/// <param name="identity"> The `identity` value of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static ResourceSet<InviteResource> Read(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadInviteOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the resources from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resources to read belong to </param>
/// <param name="identity"> The `identity` value of the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<ResourceSet<InviteResource>> ReadAsync(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadInviteOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<InviteResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<InviteResource>.FromJson("invites", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<InviteResource> NextPage(Page<InviteResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<InviteResource>.FromJson("invites", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<InviteResource> PreviousPage(Page<InviteResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Chat)
);
var response = client.Request(request);
return Page<InviteResource>.FromJson("invites", response.Content);
}
private static Request BuildDeleteRequest(DeleteInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Chat,
"/v1/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static bool Delete(DeleteInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to delete belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static bool Delete(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param>
/// <param name="pathChannelSid"> The SID of the Channel the resource to delete belongs to </param>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a InviteResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> InviteResource object represented by the provided JSON </returns>
public static InviteResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<InviteResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Channel the new resource belongs to
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The SID of the Service that the resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The string that identifies the resource's User
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The SID of the Role assigned to the member
/// </summary>
[JsonProperty("role_sid")]
public string RoleSid { get; private set; }
/// <summary>
/// The identity of the User that created the invite
/// </summary>
[JsonProperty("created_by")]
public string CreatedBy { get; private set; }
/// <summary>
/// The absolute URL of the Invite resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private InviteResource()
{
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// InviteResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.IpMessaging.V2.Service.Channel
{
public class InviteResource : Resource
{
private static Request BuildFetchRequest(FetchInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Fetch(FetchInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> FetchAsync(FetchInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Fetch(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> FetchAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Create(CreateInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> CreateAsync(CreateInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="roleSid"> The role_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static InviteResource Create(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateInviteOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="roleSid"> The role_sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<InviteResource> CreateAsync(string pathServiceSid,
string pathChannelSid,
string identity,
string roleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateInviteOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static ResourceSet<InviteResource> Read(ReadInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<InviteResource>.FromJson("invites", response.Content);
return new ResourceSet<InviteResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<ResourceSet<InviteResource>> ReadAsync(ReadInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<InviteResource>.FromJson("invites", response.Content);
return new ResourceSet<InviteResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static ResourceSet<InviteResource> Read(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadInviteOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="identity"> The identity </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<ResourceSet<InviteResource>> ReadAsync(string pathServiceSid,
string pathChannelSid,
List<string> identity = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadInviteOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<InviteResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<InviteResource>.FromJson("invites", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<InviteResource> NextPage(Page<InviteResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<InviteResource>.FromJson("invites", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<InviteResource> PreviousPage(Page<InviteResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.IpMessaging)
);
var response = client.Request(request);
return Page<InviteResource>.FromJson("invites", response.Content);
}
private static Request BuildDeleteRequest(DeleteInviteOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.IpMessaging,
"/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Invites/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static bool Delete(DeleteInviteOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Invite parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteInviteOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Invite </returns>
public static bool Delete(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathChannelSid"> The channel_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Invite </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathChannelSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteInviteOptions(pathServiceSid, pathChannelSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a InviteResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> InviteResource object represented by the provided JSON </returns>
public static InviteResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<InviteResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The sid
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The channel_sid
/// </summary>
[JsonProperty("channel_sid")]
public string ChannelSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The identity
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date_updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The role_sid
/// </summary>
[JsonProperty("role_sid")]
public string RoleSid { get; private set; }
/// <summary>
/// The created_by
/// </summary>
[JsonProperty("created_by")]
public string CreatedBy { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private InviteResource()
{
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ServiceModel
{
internal static class ReflectionExtensions
{
#region Type
public static Assembly Assembly(this Type type)
{
return type.GetTypeInfo().Assembly;
}
public static Type BaseType(this Type type)
{
return type.GetTypeInfo().BaseType;
}
public static bool ContainsGenericParameters(this Type type)
{
return type.GetTypeInfo().ContainsGenericParameters;
}
public static ConstructorInfo GetConstructor(this Type type, Type[] types)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingAttr, object binder, Type[] types, object[] modifiers)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingAttr)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GenericTypeArguments;
}
public static Type[] GetInterfaces(this Type type)
{
return Enumerable.ToArray(type.GetTypeInfo().ImplementedInterfaces);
}
public static bool IsAbstract(this Type type)
{
return type.GetTypeInfo().IsAbstract;
}
public static bool IsAssignableFrom(this Type type, Type otherType)
{
return type.GetTypeInfo().IsAssignableFrom(otherType.GetTypeInfo());
}
public static bool IsClass(this Type type)
{
return type.GetTypeInfo().IsClass;
}
public static bool IsDefined(this Type type, Type attributeType, bool inherit)
{
return type.GetTypeInfo().IsDefined(attributeType, inherit);
}
public static bool IsEnum(this Type type)
{
return type.GetTypeInfo().IsEnum;
}
public static bool IsGenericType(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
public static bool IsInterface(this Type type)
{
return type.GetTypeInfo().IsInterface;
}
public static bool IsInstanceOfType(this Type type, object o)
{
return o == null ? false : type.GetTypeInfo().IsAssignableFrom(o.GetType().GetTypeInfo());
}
public static bool IsMarshalByRef(this Type type)
{
return type.GetTypeInfo().IsMarshalByRef;
}
public static bool IsNotPublic(this Type type)
{
return type.GetTypeInfo().IsNotPublic;
}
public static bool IsSealed(this Type type)
{
return type.GetTypeInfo().IsSealed;
}
public static bool IsValueType(this Type type)
{
return type.GetTypeInfo().IsValueType;
}
public static InterfaceMapping GetInterfaceMap(this Type type, Type interfaceType)
{
return type.GetTypeInfo().GetRuntimeInterfaceMap(interfaceType);
}
public static MemberInfo[] GetMember(this Type type, string name, BindingFlags bindingAttr)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static MemberInfo[] GetMembers(this Type type, BindingFlags bindingAttr)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static MethodInfo GetMethod(this Type type, string name)
{
return type.GetTypeInfo().GetDeclaredMethod(name);
}
public static MethodInfo GetMethod(this Type type, string name, Type[] types)
{
return type.GetRuntimeMethod(name, types);
}
// TypeCode does not exist in N, but it is used by ServiceModel.
// This extension method was copied from System.Private.PortableThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs
public static TypeCode GetTypeCode(this Type type)
{
if (type == null)
{
return TypeCode.Empty;
}
if (type == typeof(Boolean))
{
return TypeCode.Boolean;
}
if (type == typeof(Char))
{
return TypeCode.Char;
}
if (type == typeof(SByte))
{
return TypeCode.SByte;
}
if (type == typeof(Byte))
{
return TypeCode.Byte;
}
if (type == typeof(Int16))
{
return TypeCode.Int16;
}
if (type == typeof(UInt16))
{
return TypeCode.UInt16;
}
if (type == typeof(Int32))
{
return TypeCode.Int32;
}
if (type == typeof(UInt32))
{
return TypeCode.UInt32;
}
if (type == typeof(Int64))
{
return TypeCode.Int64;
}
if (type == typeof(UInt64))
{
return TypeCode.UInt64;
}
if (type == typeof(Single))
{
return TypeCode.Single;
}
if (type == typeof(Double))
{
return TypeCode.Double;
}
if (type == typeof(Decimal))
{
return TypeCode.Decimal;
}
if (type == typeof(DateTime))
{
return TypeCode.DateTime;
}
if (type == typeof(String))
{
return TypeCode.String;
}
if (type.GetTypeInfo().IsEnum)
{
return GetTypeCode(Enum.GetUnderlyingType(type));
}
return TypeCode.Object;
}
#endregion Type
#region ConstructorInfo
public static bool IsPublic(this ConstructorInfo ci)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static object Invoke(this ConstructorInfo ci, BindingFlags invokeAttr, object binder, object[] parameters, CultureInfo culture)
{
throw ExceptionHelper.PlatformNotSupported();
}
#endregion ConstructorInfo
#region MethodInfo, MethodBase
public static RuntimeMethodHandle MethodHandle(this MethodBase mb)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static RuntimeMethodHandle MethodHandle(this MethodInfo mi)
{
throw ExceptionHelper.PlatformNotSupported();
}
public static Type ReflectedType(this MethodInfo mi)
{
throw ExceptionHelper.PlatformNotSupported();
}
#endregion MethodInfo, MethodBase
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BusinessBindingListBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>This is the base class from which most business collections</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Csla.Properties;
using Csla.Core;
using System.Threading.Tasks;
namespace Csla
{
/// <summary>
/// This is the base class from which most business collections
/// or lists will be derived.
/// </summary>
/// <typeparam name="T">Type of the business object being defined.</typeparam>
/// <typeparam name="C">Type of the child objects contained in the list.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable()]
public abstract class BusinessBindingListBase<T, C> :
Core.ExtendedBindingList<C>,
Core.IEditableCollection, Core.IUndoableObject, ICloneable,
Core.ISavable, Core.ISavable<T>, Core.IParent, Server.IDataPortalTarget,
INotifyBusy,
Core.IUseApplicationContext
where T : BusinessBindingListBase<T, C>
where C : Core.IEditableBusinessObject
{
/// <summary>
/// Creates an instance of the type.
/// </summary>
protected BusinessBindingListBase()
{
}
private ApplicationContext ApplicationContext { get; set; }
ApplicationContext IUseApplicationContext.ApplicationContext
{
get => ApplicationContext;
set
{
ApplicationContext = value;
InitializeIdentity();
Initialize();
this.AllowNew = true;
}
}
#region Initialize
/// <summary>
/// Override this method to set up event handlers so user
/// code in a partial class can respond to events raised by
/// generated code.
/// </summary>
protected virtual void Initialize()
{ /* allows subclass to initialize events before any other activity occurs */ }
#endregion
#region Identity
private int _identity = -1;
int IBusinessObject.Identity
{
get { return _identity; }
}
private void InitializeIdentity()
{
_identity = ((IParent)this).GetNextIdentity(_identity);
}
[NonSerialized]
[NotUndoable]
private IdentityManager _identityManager;
int IParent.GetNextIdentity(int current)
{
if (this.Parent != null)
{
return this.Parent.GetNextIdentity(current);
}
else
{
if (_identityManager == null)
_identityManager = new IdentityManager();
return _identityManager.GetNextIdentity(current);
}
}
#endregion
#region IsDirty, IsValid, IsSavable
/// <summary>
/// Gets a value indicating whether this object's data has been changed.
/// </summary>
bool Core.ITrackStatus.IsSelfDirty
{
get { return IsDirty; }
}
/// <summary>
/// Gets a value indicating whether this object's data has been changed.
/// </summary>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
public bool IsDirty
{
get
{
// any non-new deletions make us dirty
foreach (C item in DeletedList)
if (!item.IsNew)
return true;
// run through all the child objects
// and if any are dirty then then
// collection is dirty
foreach (C child in this)
if (child.IsDirty)
return true;
return false;
}
}
bool Core.ITrackStatus.IsSelfValid
{
get { return IsSelfValid; }
}
/// <summary>
/// Gets a value indicating whether this object is currently in
/// a valid state (has no broken validation rules).
/// </summary>
protected virtual bool IsSelfValid
{
get { return IsValid; }
}
/// <summary>
/// Gets a value indicating whether this object is currently in
/// a valid state (has no broken validation rules).
/// </summary>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
public virtual bool IsValid
{
get
{
// run through all the child objects
// and if any are invalid then the
// collection is invalid
foreach (C child in this)
if (!child.IsValid)
return false;
return true;
}
}
/// <summary>
/// Returns true if this object is both dirty and valid.
/// </summary>
/// <returns>A value indicating if this object is both dirty and valid.</returns>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public virtual bool IsSavable
{
get
{
bool auth = Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, this);
return (IsDirty && IsValid && auth && !IsBusy);
}
}
#endregion
#region Begin/Cancel/ApplyEdit
/// <summary>
/// Starts a nested edit on the object.
/// </summary>
/// <remarks>
/// <para>
/// When this method is called the object takes a snapshot of
/// its current state (the values of its variables). This snapshot
/// can be restored by calling <see cref="CancelEdit" />
/// or committed by calling <see cref="ApplyEdit" />.
/// </para><para>
/// This is a nested operation. Each call to BeginEdit adds a new
/// snapshot of the object's state to a stack. You should ensure that
/// for each call to BeginEdit there is a corresponding call to either
/// CancelEdit or ApplyEdit to remove that snapshot from the stack.
/// </para><para>
/// See Chapters 2 and 3 for details on n-level undo and state stacking.
/// </para><para>
/// This method triggers the copying of all child object states.
/// </para>
/// </remarks>
public void BeginEdit()
{
if (this.IsChild)
throw new NotSupportedException(Resources.NoBeginEditChildException);
CopyState(this.EditLevel + 1);
}
/// <summary>
/// Cancels the current edit process, restoring the object's state to
/// its previous values.
/// </summary>
/// <remarks>
/// Calling this method causes the most recently taken snapshot of the
/// object's state to be restored. This resets the object's values
/// to the point of the last <see cref="BeginEdit" />
/// call.
/// <para>
/// This method triggers an undo in all child objects.
/// </para>
/// </remarks>
public void CancelEdit()
{
if (this.IsChild)
throw new NotSupportedException(Resources.NoCancelEditChildException);
UndoChanges(this.EditLevel - 1);
}
/// <summary>
/// Commits the current edit process.
/// </summary>
/// <remarks>
/// Calling this method causes the most recently taken snapshot of the
/// object's state to be discarded, thus committing any changes made
/// to the object's state since the last
/// <see cref="BeginEdit" /> call.
/// <para>
/// This method triggers an <see cref="Core.BusinessBase.ApplyEdit"/>
/// in all child objects.
/// </para>
/// </remarks>
public void ApplyEdit()
{
if (this.IsChild)
throw new NotSupportedException(Resources.NoApplyEditChildException);
AcceptChanges(this.EditLevel - 1);
}
void Core.IParent.ApplyEditChild(Core.IEditableBusinessObject child)
{
EditChildComplete(child);
}
IParent Csla.Core.IParent.Parent
{
get { return this.Parent; }
}
/// <summary>
/// Override this method to be notified when a child object's
/// <see cref="Core.BusinessBase.ApplyEdit" /> method has
/// completed.
/// </summary>
/// <param name="child">The child object that was edited.</param>
protected virtual void EditChildComplete(Core.IEditableBusinessObject child)
{
// do nothing, we don't really care
// when a child has its edits applied
}
#endregion
#region N-level undo
void Core.IUndoableObject.CopyState(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
CopyState(parentEditLevel);
}
void Core.IUndoableObject.UndoChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
UndoChanges(parentEditLevel);
}
void Core.IUndoableObject.AcceptChanges(int parentEditLevel, bool parentBindingEdit)
{
if (!parentBindingEdit)
AcceptChanges(parentEditLevel);
}
private void CopyState(int parentEditLevel)
{
if (this.EditLevel + 1 > parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "CopyState"), this.GetType().Name, _parent != null ? _parent.GetType().Name : null, this.EditLevel, parentEditLevel - 1);
// we are going a level deeper in editing
_editLevel += 1;
// cascade the call to all child objects
foreach (C child in this)
child.CopyState(_editLevel, false);
// cascade the call to all deleted child objects
foreach (C child in DeletedList)
child.CopyState(_editLevel, false);
}
private bool _completelyRemoveChild;
private void UndoChanges(int parentEditLevel)
{
C child;
if (this.EditLevel - 1 != parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "UndoChanges"), this.GetType().Name, _parent != null ? _parent.GetType().Name : null, this.EditLevel, parentEditLevel + 1);
// we are coming up one edit level
_editLevel -= 1;
if (_editLevel < 0) _editLevel = 0;
try
{
using (LoadListMode)
{
// Cancel edit on all current items
for (int index = Count - 1; index >= 0; index--)
{
child = this[index];
child.UndoChanges(_editLevel, false);
// if item is below its point of addition, remove
if (child.EditLevelAdded > _editLevel)
{
bool oldAllowRemove = this.AllowRemove;
try
{
this.AllowRemove = true;
_completelyRemoveChild = true;
RemoveAt(index);
}
finally
{
_completelyRemoveChild = false;
this.AllowRemove = oldAllowRemove;
}
}
}
// cancel edit on all deleted items
for (int index = DeletedList.Count - 1; index >= 0; index--)
{
child = DeletedList[index];
child.UndoChanges(_editLevel, false);
if (child.EditLevelAdded > _editLevel)
{
// if item is below its point of addition, remove
DeletedList.RemoveAt(index);
}
else
{
// if item is no longer deleted move back to main list
if (!child.IsDeleted) UnDeleteChild(child);
}
}
}
}
finally
{
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
}
private void AcceptChanges(int parentEditLevel)
{
if (this.EditLevel - 1 != parentEditLevel)
throw new UndoException(string.Format(Resources.EditLevelMismatchException, "AcceptChanges"), this.GetType().Name, _parent != null ? _parent.GetType().Name : null, this.EditLevel, parentEditLevel + 1);
// we are coming up one edit level
_editLevel -= 1;
if (_editLevel < 0) _editLevel = 0;
// cascade the call to all child objects
foreach (C child in this)
{
child.AcceptChanges(_editLevel, false);
// if item is below its point of addition, lower point of addition
if (child.EditLevelAdded > _editLevel) child.EditLevelAdded = _editLevel;
}
// cascade the call to all deleted child objects
for (int index = DeletedList.Count - 1; index >= 0; index--)
{
C child = DeletedList[index];
child.AcceptChanges(_editLevel, false);
// if item is below its point of addition, remove
if (child.EditLevelAdded > _editLevel)
DeletedList.RemoveAt(index);
}
}
#endregion
#region Delete and Undelete child
private MobileList<C> _deletedList;
/// <summary>
/// A collection containing all child objects marked
/// for deletion.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected MobileList<C> DeletedList
{
get
{
if (_deletedList == null)
_deletedList = (MobileList<C>)ApplicationContext.CreateGenericInstanceDI(typeof(MobileList<>), typeof(C));
return _deletedList;
}
}
private void DeleteChild(C child)
{
// set child edit level
Core.UndoableBase.ResetChildEditLevel(child, this.EditLevel, false);
// mark the object as deleted
child.DeleteChild();
// and add it to the deleted collection for storage
DeletedList.Add(child);
}
private void UnDeleteChild(C child)
{
// since the object is no longer deleted, remove it from
// the deleted collection
DeletedList.Remove(child);
// we are inserting an _existing_ object so
// we need to preserve the object's editleveladded value
// because it will be changed by the normal add process
int saveLevel = child.EditLevelAdded;
Add(child);
child.EditLevelAdded = saveLevel;
}
/// <summary>
/// Returns true if the internal deleted list
/// contains the specified child object.
/// </summary>
/// <param name="item">Child object to check.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool ContainsDeleted(C item)
{
return DeletedList.Contains(item);
}
#endregion
#region Insert, Remove, Clear
/// <summary>
/// Override this method to create a new object that is added
/// to the collection.
/// </summary>
protected override object AddNewCore()
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<C>>();
var item = dp.CreateChild();
Add(item);
return item;
}
/// <summary>
/// This method is called by a child object when it
/// wants to be removed from the collection.
/// </summary>
/// <param name="child">The child object to remove.</param>
void Core.IEditableCollection.RemoveChild(Csla.Core.IEditableBusinessObject child)
{
Remove((C)child);
}
object IEditableCollection.GetDeletedList()
{
return DeletedList;
}
/// <summary>
/// This method is called by a child object when it
/// wants to be removed from the collection.
/// </summary>
/// <param name="child">The child object to remove.</param>
void Core.IParent.RemoveChild(Csla.Core.IEditableBusinessObject child)
{
Remove((C)child);
}
/// <summary>
/// Sets the edit level of the child object as it is added.
/// </summary>
/// <param name="index">Index of the item to insert.</param>
/// <param name="item">Item to insert.</param>
protected override void InsertItem(int index, C item)
{
// set parent reference
item.SetParent(this);
// set child edit level
Core.UndoableBase.ResetChildEditLevel(item, this.EditLevel, false);
// when an object is inserted we assume it is
// a new object and so the edit level when it was
// added must be set
item.EditLevelAdded = _editLevel;
base.InsertItem(index, item);
}
/// <summary>
/// Marks the child object for deletion and moves it to
/// the collection of deleted objects.
/// </summary>
/// <param name="index">Index of the item to remove.</param>
protected override void RemoveItem(int index)
{
// when an object is 'removed' it is really
// being deleted, so do the deletion work
C child = this[index];
using (LoadListMode)
{
base.RemoveItem(index);
}
if (!_completelyRemoveChild)
{
// the child shouldn't be completely removed,
// so copy it to the deleted list
DeleteChild(child);
}
if (RaiseListChangedEvents)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
}
/// <summary>
/// Clears the collection, moving all active
/// items to the deleted list.
/// </summary>
protected override void ClearItems()
{
while (base.Count > 0)
RemoveItem(0);
base.ClearItems();
}
/// <summary>
/// Replaces the item at the specified index with
/// the specified item, first moving the original
/// item to the deleted list.
/// </summary>
/// <param name="index">The zero-based index of the item to replace.</param>
/// <param name="item">
/// The new value for the item at the specified index.
/// The value can be null for reference types.
/// </param>
/// <remarks></remarks>
protected override void SetItem(int index, C item)
{
C child = default(C);
if (!(ReferenceEquals((C)(this[index]), item)))
child = this[index];
// replace the original object with this new
// object
using (LoadListMode)
{
// set parent reference
item.SetParent(this);
// set child edit level
Core.UndoableBase.ResetChildEditLevel(item, this.EditLevel, false);
// reset EditLevelAdded
item.EditLevelAdded = this.EditLevel;
// add to list
base.SetItem(index, item);
}
if (child != null)
DeleteChild(child);
if (RaiseListChangedEvents)
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
}
#endregion
#region Cascade child events
/// <summary>
/// Handles any PropertyChanged event from
/// a child object and echoes it up as
/// a ListChanged event.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected override void Child_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (_deserialized && RaiseListChangedEvents && e != null)
{
for (int index = 0; index < Count; index++)
{
if (ReferenceEquals(this[index], sender))
{
PropertyDescriptor descriptor = GetPropertyDescriptor(e.PropertyName);
if (descriptor != null)
OnListChanged(new ListChangedEventArgs(
ListChangedType.ItemChanged, index, descriptor));
else
OnListChanged(new ListChangedEventArgs(
ListChangedType.ItemChanged, index));
}
}
}
base.Child_PropertyChanged(sender, e);
}
private static PropertyDescriptorCollection _propertyDescriptors;
private PropertyDescriptor GetPropertyDescriptor(string propertyName)
{
if (_propertyDescriptors == null)
_propertyDescriptors = TypeDescriptor.GetProperties(typeof(C));
PropertyDescriptor result = null;
foreach (PropertyDescriptor desc in _propertyDescriptors)
if (desc.Name == propertyName)
{
result = desc;
break;
}
return result;
}
#endregion
#region Edit level tracking
// keep track of how many edit levels we have
private int _editLevel;
/// <summary>
/// Returns the current edit level of the object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
protected int EditLevel
{
get { return _editLevel; }
}
int Core.IUndoableObject.EditLevel
{
get
{
return this.EditLevel;
}
}
#endregion
#region IsChild
[NotUndoable()]
private bool _isChild = false;
/// <summary>
/// Indicates whether this collection object is a child object.
/// </summary>
/// <returns>True if this is a child object.</returns>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
public bool IsChild
{
get { return _isChild; }
}
/// <summary>
/// Marks the object as being a child object.
/// </summary>
/// <remarks>
/// <para>
/// By default all business objects are 'parent' objects. This means
/// that they can be directly retrieved and updated into the database.
/// </para><para>
/// We often also need child objects. These are objects which are contained
/// within other objects. For instance, a parent Invoice object will contain
/// child LineItem objects.
/// </para><para>
/// To create a child object, the MarkAsChild method must be called as the
/// object is created. Please see Chapter 7 for details on the use of the
/// MarkAsChild method.
/// </para>
/// </remarks>
protected void MarkAsChild()
{
_identity = -1;
_isChild = true;
}
#endregion
#region ICloneable
object ICloneable.Clone()
{
return GetClone();
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual object GetClone()
{
return Core.ObjectCloner.GetInstance(ApplicationContext).Clone(this);
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
public T Clone()
{
return (T)GetClone();
}
#endregion
#region Serialization Notification
[NonSerialized]
[NotUndoable]
private bool _deserialized = false;
/// <summary>
/// This method is called on a newly deserialized object
/// after deserialization is complete.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnDeserialized()
{
_deserialized = true;
base.OnDeserialized();
foreach (Core.IEditableBusinessObject child in this)
{
child.SetParent(this);
}
foreach (Core.IEditableBusinessObject child in DeletedList)
child.SetParent(this);
}
#endregion
#region Child Data Access
/// <summary>
/// Initializes a new instance of the object
/// with default values.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_Create()
{ /* do nothing - list self-initializes */ }
/// <summary>
/// Saves all items in the list, automatically
/// performing insert, update or delete operations
/// as necessary.
/// </summary>
/// <param name="parameters">
/// Optional parameters passed to child update
/// methods.
/// </param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_Update(params object[] parameters)
{
using (LoadListMode)
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<C>>();
foreach (var child in DeletedList)
dp.UpdateChild(child, parameters);
DeletedList.Clear();
foreach (var child in this)
if (child.IsDirty) dp.UpdateChild(child, parameters);
}
}
#endregion
#region Data Access
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method starts the save operation, causing the all child
/// objects to be inserted, updated or deleted within the database based on the
/// each object's current state.
/// </para><para>
/// All this is contingent on <see cref="IsDirty" />. If
/// this value is false, no data operation occurs.
/// It is also contingent on <see cref="IsValid" />. If this value is
/// false an exception will be thrown to
/// indicate that the UI attempted to save an invalid object.
/// </para><para>
/// It is important to note that this method returns a new version of the
/// business collection that contains any data updated during the save operation.
/// You MUST update all object references to use this new version of the
/// business collection in order to have access to the correct object data.
/// </para><para>
/// You can override this method to add your own custom behaviors to the save
/// operation. For instance, you may add some security checks to make sure
/// the user can save the object. If all security checks pass, you would then
/// invoke the base Save method via <c>MyBase.Save()</c>.
/// </para>
/// </remarks>
/// <returns>A new object containing the saved values.</returns>
public T Save()
{
try
{
return SaveAsync(null, true).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 0)
throw ex.InnerExceptions[0];
else
throw;
}
}
/// <summary>
/// Saves the object to the database.
/// </summary>
public async Task<T> SaveAsync()
{
return await SaveAsync(null, false);
}
/// <summary>
/// Saves the object to the database, merging
/// any resulting updates into the existing
/// object graph.
/// </summary>
public Task SaveAndMergeAsync()
{
throw new NotSupportedException(nameof(SaveAndMergeAsync));
}
/// <summary>
/// Saves the object to the database.
/// </summary>
/// <param name="userState">User state data.</param>
/// <param name="isSync">True if the save operation should be synchronous.</param>
protected virtual async Task<T> SaveAsync(object userState, bool isSync)
{
T result;
if (this.IsChild)
throw new InvalidOperationException(Resources.NoSaveChildException);
if (_editLevel > 0)
throw new InvalidOperationException(Resources.NoSaveEditingException);
if (!IsValid)
throw new Rules.ValidationException(Resources.NoSaveInvalidException);
if (IsBusy)
throw new InvalidOperationException(Resources.BusyObjectsMayNotBeSaved);
if (IsDirty)
{
var dp = ApplicationContext.CreateInstanceDI<DataPortal<T>>();
if (isSync)
{
result = dp.Update((T)this);
}
else
{
result = await dp.UpdateAsync((T)this);
}
}
else
{
result = (T)this;
}
OnSaved(result, null, userState);
return result;
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
#endregion
#region ISavable Members
object Csla.Core.ISavable.Save()
{
return Save();
}
object Csla.Core.ISavable.Save(bool forceUpdate)
{
return Save();
}
async Task<object> ISavable.SaveAsync()
{
return await SaveAsync();
}
async Task<object> ISavable.SaveAsync(bool forceUpdate)
{
return await SaveAsync();
}
async Task ISavable.SaveAndMergeAsync(bool forceUpdate)
{
await SaveAndMergeAsync();
}
void Csla.Core.ISavable.SaveComplete(object newObject)
{
OnSaved((T)newObject, null, null);
}
T Csla.Core.ISavable<T>.Save(bool forceUpdate)
{
return Save();
}
async Task<T> ISavable<T>.SaveAsync(bool forceUpdate)
{
return await SaveAsync();
}
async Task ISavable<T>.SaveAndMergeAsync(bool forceUpdate)
{
await SaveAndMergeAsync();
}
void Csla.Core.ISavable<T>.SaveComplete(T newObject)
{
OnSaved(newObject, null, null);
}
[NonSerialized()]
[NotUndoable]
private EventHandler<Csla.Core.SavedEventArgs> _nonSerializableSavedHandlers;
[NotUndoable]
private EventHandler<Csla.Core.SavedEventArgs> _serializableSavedHandlers;
/// <summary>
/// Event raised when an object has been saved.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
"CA1062:ValidateArgumentsOfPublicMethods")]
public event EventHandler<Csla.Core.SavedEventArgs> Saved
{
add
{
if (value.Method.IsPublic &&
(value.Method.DeclaringType.IsSerializable ||
value.Method.IsStatic))
_serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Combine(_serializableSavedHandlers, value);
else
_nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Combine(_nonSerializableSavedHandlers, value);
}
remove
{
if (value.Method.IsPublic &&
(value.Method.DeclaringType.IsSerializable ||
value.Method.IsStatic))
_serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Remove(_serializableSavedHandlers, value);
else
_nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>)
System.Delegate.Remove(_nonSerializableSavedHandlers, value);
}
}
/// <summary>
/// Raises the <see cref="Saved"/> event, indicating that the
/// object has been saved, and providing a reference
/// to the new object instance.
/// </summary>
/// <param name="newObject">The new object instance.</param>
/// <param name="e">Execption that occurred during the operation.</param>
/// <param name="userState">User state object.</param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnSaved(T newObject, Exception e, object userState)
{
Csla.Core.SavedEventArgs args = new Csla.Core.SavedEventArgs(newObject, e, userState);
if (_nonSerializableSavedHandlers != null)
_nonSerializableSavedHandlers.Invoke(this, args);
if (_serializableSavedHandlers != null)
_serializableSavedHandlers.Invoke(this, args);
}
#endregion
#region Parent/Child link
[NotUndoable(), NonSerialized()]
private Core.IParent _parent;
/// <summary>
/// Provide access to the parent reference for use
/// in child object code.
/// </summary>
/// <remarks>
/// This value will be Nothing for root objects.
/// </remarks>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public Core.IParent Parent
{
get
{
return _parent;
}
}
/// <summary>
/// Used by BusinessListBase as a child object is
/// created to tell the child object about its
/// parent.
/// </summary>
/// <param name="parent">A reference to the parent collection object.</param>
protected virtual void SetParent(Core.IParent parent)
{
_parent = parent;
_identityManager = null;
InitializeIdentity();
}
/// <summary>
/// Used by BusinessListBase as a child object is
/// created to tell the child object about its
/// parent.
/// </summary>
/// <param name="parent">A reference to the parent collection object.</param>
void Core.IEditableCollection.SetParent(Core.IParent parent)
{
this.SetParent(parent);
}
#endregion
#region ToArray
/// <summary>
/// Get an array containing all items in the list.
/// </summary>
public C[] ToArray()
{
List<C> result = new List<C>();
foreach (C item in this)
result.Add(item);
return result.ToArray();
}
#endregion
#region ITrackStatus
bool Core.ITrackStatus.IsNew
{
get
{
return false;
}
}
bool Core.ITrackStatus.IsDeleted
{
get
{
return false;
}
}
/// <summary>
/// Gets the busy status for this object and its child objects.
/// </summary>
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
public override bool IsBusy
{
get
{
// any non-new deletions make us dirty
foreach (C item in DeletedList)
if (item.IsBusy)
return true;
// run through all the child objects
// and if any are dirty then then
// collection is dirty
foreach (C child in this)
if (child.IsBusy)
return true;
return false;
}
}
#endregion
#region IDataPortalTarget Members
void Csla.Server.IDataPortalTarget.CheckRules()
{ }
void Csla.Server.IDataPortalTarget.MarkAsChild()
{
this.MarkAsChild();
}
void Csla.Server.IDataPortalTarget.MarkNew()
{ }
void Csla.Server.IDataPortalTarget.MarkOld()
{ }
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.DataPortal_OnDataPortalException(e, ex);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.Child_OnDataPortalException(e, ex);
}
#endregion
#region Mobile object overrides
/// <summary>
/// Override this method to retrieve your field values
/// from the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info)
{
_isChild = info.GetValue<bool>("Csla.BusinessListBase._isChild");
_editLevel = info.GetValue<int>("Csla.BusinessListBase._editLevel");
_identity = info.GetValue<int>("Csla.Core.BusinessBase._identity");
base.OnSetState(info);
}
/// <summary>
/// Override this method to insert your field values
/// into the MobileFormatter serialzation stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info)
{
info.AddValue("Csla.BusinessListBase._isChild", _isChild);
info.AddValue("Csla.BusinessListBase._editLevel", _editLevel);
info.AddValue("Csla.Core.BusinessBase._identity", _identity);
base.OnGetState(info);
}
/// <summary>
/// Override this method to insert child objects
/// into the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the data to serialize.
/// </param>
/// <param name="formatter">
/// Reference to the current SerializationFormatterFactory.GetFormatter().
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnGetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter)
{
base.OnGetChildren(info, formatter);
if (_deletedList != null)
{
var fieldManagerInfo = formatter.SerializeObject(_deletedList);
info.AddChild("_deletedList", fieldManagerInfo.ReferenceId);
}
}
/// <summary>
/// Override this method to get child objects
/// from the MobileFormatter serialization stream.
/// </summary>
/// <param name="info">
/// Object containing the serialized data.
/// </param>
/// <param name="formatter">
/// Reference to the current SerializationFormatterFactory.GetFormatter().
/// </param>
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnSetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter)
{
if (info.Children.ContainsKey("_deletedList"))
{
var childData = info.Children["_deletedList"];
_deletedList = (MobileList<C>)formatter.GetObject(childData.ReferenceId);
}
base.OnSetChildren(info, formatter);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mono.Options;
namespace CppSharp
{
class CLI
{
private static OptionSet optionSet = new OptionSet();
private static Options options = new Options();
static bool ParseCommandLineArgs(string[] args, List<string> errorMessages, ref bool helpShown)
{
var showHelp = false;
optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, errorMessages); });
optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l) );
optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l) );
optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, errorMessages) );
optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, errorMessages) );
optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, errorMessages) );
optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on );
optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln );
optionSet.Add("d|debug", "enables debug mode which generates more verbose code to aid debugging", v => options.Debug = true);
optionSet.Add("c|compile", "enables automatic compilation of the generated code", v => options.Compile = true);
optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'csharp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, errorMessages); } );
optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, errorMessages); } );
optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, errorMessages); } );
optionSet.Add("exceptions", "enables support for C++ exceptions in the parser", v => { options.EnableExceptions = true; });
optionSet.Add("rtti", "enables support for C++ RTTI in the parser", v => { options.EnableRTTI = true; });
optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); } );
optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); } );
optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); } );
optionSet.Add("v|verbose", "enables verbose mode", v => { options.Verbose = true; });
optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); });
List<string> additionalArguments = null;
try
{
additionalArguments = optionSet.Parse(args);
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
return false;
}
if (showHelp || additionalArguments != null && additionalArguments.Count == 0)
{
helpShown = true;
ShowHelp();
return false;
}
foreach(string s in additionalArguments)
HandleAdditionalArgument(s, errorMessages);
return true;
}
static void ShowHelp()
{
string appName = Platform.IsWindows ? "CppSharp.CLI.exe" : "CppSharp.CLI";
Console.WriteLine();
Console.WriteLine("Usage: {0} [OPTIONS]+ [FILES]+", appName);
Console.WriteLine("Generates target language bindings to interop with unmanaged code.");
Console.WriteLine();
Console.WriteLine("Options:");
optionSet.WriteOptionDescriptions(Console.Out);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Useful informations:");
Console.WriteLine(" - to specify a file to generate bindings from you just have to add their path without any option flag, just like you");
Console.WriteLine(" would do with GCC compiler. You can specify a path to a single file (local or absolute) or a path to a folder with");
Console.WriteLine(" a search query.");
Console.WriteLine(" e.g.: '{0} [OPTIONS]+ my_header.h' will generate the bindings for the file my_header.h", appName);
Console.WriteLine(" e.g.: '{0} [OPTIONS]+ include/*.h' will generate the bindings for all the '.h' files inside the include folder", appName);
Console.WriteLine(" - the options 'iln' (same as 'inputlibraryname') and 'l' have a similar meaning. Both of them are used to tell");
Console.WriteLine(" the generator which library has to be used to P/Invoke the functions from your native code.");
Console.WriteLine(" The difference is that if you want to generate the bindings for more than one library within a single managed");
Console.WriteLine(" file you need to use the 'l' option to specify the names of all the libraries that contain the symbols to be loaded");
Console.WriteLine(" and you MUST set the 'cs' ('checksymbols') flag to let the generator automatically understand which library");
Console.WriteLine(" to use to P/Invoke. This can be also used if you plan to generate the bindings for only one library.");
Console.WriteLine(" If you specify the 'iln' (or 'inputlibraryname') options, this option's value will be used for all the P/Invokes");
Console.WriteLine(" that the generator will create.");
Console.WriteLine(" - If you specify the 'unitybuild' option then the generator will output a file for each given header file that will");
Console.WriteLine(" contain only the bindings for that header file.");
}
static void AddIncludeDirs(string dir, List<string> errorMessages)
{
if (Directory.Exists(dir))
options.IncludeDirs.Add(dir);
else
errorMessages.Add(string.Format("Directory '{0}' doesn't exist. Ignoring as include directory.", dir));
}
static void HandleOutputArg(string arg, List<string> errorMessages)
{
try
{
string file = Path.GetFileNameWithoutExtension(arg);
options.OutputFileName = file;
var dir = Path.HasExtension(arg) ? Path.GetDirectoryName(arg) : Path.GetFullPath(arg);
options.OutputDir = dir;
}
catch(Exception e)
{
errorMessages.Add(e.Message);
options.OutputDir = "";
options.OutputFileName = "";
}
}
static void AddArgument(string value, List<string> errorMessages)
{
if (value == null)
errorMessages.Add("Invalid compiler argument name for option -A.");
else
options.Arguments.Add(value);
}
static void AddDefine(string name, string value, List<string> errorMessages)
{
if (name == null)
errorMessages.Add("Invalid definition name for option -D.");
else
options.Defines.Add(name, value);
}
static void HandleAdditionalArgument(string args, List<string> errorMessages)
{
if (!Path.IsPathRooted(args))
args = Path.Combine(Directory.GetCurrentDirectory(), args);
try
{
bool searchQuery = args.IndexOf('*') >= 0 || args.IndexOf('?') >= 0;
if (searchQuery || Directory.Exists(args))
GetFilesFromPath(args, errorMessages);
else if (File.Exists(args))
options.HeaderFiles.Add(args);
else
{
errorMessages.Add($"File '{args}' could not be found.");
}
}
catch(Exception)
{
errorMessages.Add($"Error while looking for files inside path '{args}'. Ignoring.");
}
}
static void GetFilesFromPath(string path, List<string> errorMessages)
{
path = path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
string searchPattern = string.Empty;
int lastSeparatorPosition = path.LastIndexOf(Path.AltDirectorySeparatorChar);
if (lastSeparatorPosition >= 0)
{
if (path.IndexOf('*', lastSeparatorPosition) >= lastSeparatorPosition || path.IndexOf('?', lastSeparatorPosition) >= lastSeparatorPosition)
{
searchPattern = path.Substring(lastSeparatorPosition + 1);
path = path.Substring(0, lastSeparatorPosition);
}
}
try
{
if (!string.IsNullOrEmpty(searchPattern))
{
string[] files = Directory.GetFiles(path, searchPattern);
foreach (string s in files)
options.HeaderFiles.Add(s);
}
else
{
var files = Directory.GetFiles(path).Where(f =>
Path.GetExtension(f) == ".h" || Path.GetExtension(f) == ".hpp");
options.HeaderFiles.AddRange(files);
}
}
catch (Exception)
{
errorMessages.Add(string.Format("Error while looking for files inside path '{0}'. Ignoring.", path));
}
}
static void GetGeneratorKind(string generator, List<string> errorMessages)
{
switch (generator.ToLower())
{
case "csharp":
options.Kind = CppSharp.Generators.GeneratorKind.CSharp;
return;
case "cli":
options.Kind = CppSharp.Generators.GeneratorKind.CLI;
return;
}
errorMessages.Add(string.Format("Unknown generator kind: {0}. Defaulting to {1}", generator, options.Kind.ToString()));
}
static void GetDestinationPlatform(string platform, List<string> errorMessages)
{
switch (platform.ToLower())
{
case "win":
options.Platform = TargetPlatform.Windows;
return;
case "osx":
options.Platform = TargetPlatform.MacOS;
return;
case "linux":
options.Platform = TargetPlatform.Linux;
return;
}
errorMessages.Add(string.Format("Unknown target platform: {0}. Defaulting to {1}", platform, options.Platform.ToString()));
}
static void GetDestinationArchitecture(string architecture, List<string> errorMessages)
{
switch (architecture.ToLower())
{
case "x86":
options.Architecture = TargetArchitecture.x86;
return;
case "x64":
options.Architecture = TargetArchitecture.x64;
return;
}
errorMessages.Add(string.Format("Unknown target architecture: {0}. Defaulting to {1}", architecture, options.Architecture.ToString()));
}
static void PrintErrorMessages(List<string> errorMessages)
{
foreach (string m in errorMessages)
Console.Error.WriteLine(m);
}
static void Main(string[] args)
{
List<string> errorMessages = new List<string>();
bool helpShown = false;
try
{
if (!ParseCommandLineArgs(args, errorMessages, ref helpShown))
{
PrintErrorMessages(errorMessages);
// Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown
return;
}
Generator gen = new Generator(options);
bool validOptions = gen.ValidateOptions(errorMessages);
PrintErrorMessages(errorMessages);
if (validOptions)
gen.Run();
}
catch (Exception ex)
{
PrintErrorMessages(errorMessages);
Console.Error.WriteLine();
throw ex;
}
}
}
}
| |
/*
* ArrayQueue.cs - Generic queue class, implemented as an array.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Generics
{
using System;
public sealed class ArrayQueue<T> : IQueue<T>, ICapacity, ICloneable
{
// Internal state.
private T[] items;
private int add, remove, size;
// The default capacity for queues.
private const int DefaultCapacity = 32;
// Constructors.
public ArrayQueue()
{
items = new Object [DefaultCapacity];
add = 0;
remove = 0;
size = 0;
}
public ArrayQueue(int capacity)
{
if(capacity < 0)
{
throw new ArgumentOutOfRangeException
("capacity", S._("ArgRange_NonNegative"));
}
items = new T [capacity];
add = 0;
remove = 0;
size = 0;
}
// Implement the ICollection<T> interface.
public void CopyTo(T[] array, int index)
{
if(array == null)
{
throw new ArgumentNullException("array");
}
else if(index < 0)
{
throw new ArgumentOutOfRangeException
("index", S._("ArgRange_Array"));
}
else if((array.Length - index) < size)
{
throw new ArgumentException(S._("Arg_InvalidArrayRange"));
}
else if(size > 0)
{
if((remove + size) <= items.Length)
{
Array.Copy(items, remove, array, index, size);
}
else
{
Array.Copy(items, remove, array, index,
items.Length - remove);
Array.Copy(items, 0, array,
index + items.Length - remove, add);
}
}
}
public int Count
{
get
{
return size;
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public Object SyncRoot
{
get
{
return this;
}
}
// Implement the ICapacity interface.
public int Capacity
{
get
{
return items.Length;
}
set
{
if(value < 0)
{
throw new ArgumentOutOfRangeException
("value", S._("ArgRange_NonNegative"));
}
if(value < size)
{
throw new ArgumentOutOfRangeException
("value", S._("Arg_CannotReduceCapacity"));
}
if(value != size)
{
T[] newItems = new T [value];
if(remove < size)
{
Array.Copy(items, remove, newItems,
0, size - remove);
}
if(remove > 0)
{
Array.Copy(items, 0, newItems,
size - remove, remove);
}
items = newItems;
add = size;
remove = 0;
}
}
}
// Implement the ICloneable<T> interface.
public Object Clone()
{
ArrayQueue<T> queue = (ArrayQueue<T>)MemberwiseClone();
queue.items = (T[])items.Clone();
return queue;
}
// Implement the IIterable<T> interface.
public IIterable<T> GetIterator()
{
return new QueueIterator<T>(this);
}
// Implement the IQueue<T> interface.
public void Clear()
{
add = 0;
remove = 0;
size = 0;
}
public bool Contains(T obj)
{
int index = remove;
int capacity = items.Length;
int count = size;
if(typeof(T).IsValueType)
{
while(count > 0)
{
if(obj.Equals(items[index]))
{
return true;
}
index = (index + 1) % capacity;
--count;
}
}
else
{
while(count > 0)
{
if(items[index] != null && obj != null)
{
if(obj.Equals(items[index]))
{
return true;
}
}
else if(items[index] == null && obj == null)
{
return true;
}
index = (index + 1) % capacity;
--count;
}
}
return false;
}
public void Enqueue(T value)
{
if(size < items.Length)
{
// The queue is big enough to hold the new item.
items[add] = value;
add = (add + 1) % items.Length;
++size;
}
else
{
// We need to increase the size of the queue.
int newCapacity = (int)(items.Length * 2);
if(newCapacity <= items.Length)
{
newCapacity = items.Length + 1;
}
T[] newItems = new T [newCapacity];
if(remove < size)
{
Array.Copy(items, remove, newItems, 0, size - remove);
}
if(remove > 0)
{
Array.Copy(items, 0, newItems, size - remove, remove);
}
items = newItems;
add = size;
remove = 0;
items[add] = value;
add = (add + 1) % items.Length;
++size;
}
}
public T Dequeue()
{
if(size > 0)
{
T value = items[remove];
remove = (remove + 1) % items.Length;
--size;
return value;
}
else
{
throw new InvalidOperationException
(S._("Invalid_EmptyQueue"));
}
}
public T Peek()
{
if(size > 0)
{
return items[remove];
}
else
{
throw new InvalidOperationException
(S._("Invalid_EmptyQueue"));
}
}
public T[] ToArray()
{
T[] array = new T [size];
if(size > 0)
{
if((remove + size) <= items.Length)
{
Array.Copy(items, remove, array, 0, size);
}
else
{
Array.Copy(items, remove, array, 0,
items.Length - remove);
Array.Copy(items, 0, array,
items.Length - remove, add);
}
}
return array;
}
// Private class for implementing queue enumeration.
private class QueueIterator<T> : IIterator<T>
{
// Internal state.
private ArrayQueue<T> queue;
private int position;
// Constructor.
public QueueIterator(ArrayQueue<T> queue)
{
this.queue = queue;
position = -1;
}
// Implement the IIterator<T> interface.
public bool MoveNext()
{
++position;
if(position < queue.size)
{
return true;
}
position = queue.size;
return false;
}
public void Reset()
{
position = -1;
}
public void Remove()
{
throw new InvalidOperationException(S._("NotSupp_Remove"));
}
public T Current
{
get
{
if(position < 0 || position >= queue.size)
{
throw new InvalidOperationException
(S._("Invalid_BadIteratorPosition"));
}
return queue.items
[(queue.remove + position) % queue.size];
}
}
}; // class QueueIterator<T>
}; // class ArrayQueue<T>
}; // namespace Generics
| |
using System.Linq;
using System.Reflection;
using GetSocialSdk.Core;
using UnityEngine;
namespace GetSocialSdk.MiniJSON
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class GSJson
{
// interpret all numbers as if they are english US formatted numbers
private static NumberFormatInfo numberFormat = (new CultureInfo("en-US")).NumberFormat;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json)
{
// save the string for debug information
if (json == null)
{
return null;
}
if (json.Length == 0)
{
return null;
}
return Parser.Parse(json);
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj)
{
return Serializer.Serialize(obj);
}
public static string TextureToBase64(this Texture2D obj)
{
if (obj == null)
{
return null;
}
var bytes = obj.EncodeToPNG();
if (bytes == null)
{
return null;
}
return Convert.ToBase64String(bytes);
}
public static Texture2D FromBase64(this string base64Image)
{
if (string.IsNullOrEmpty(base64Image))
{
return null;
}
var b64_bytes = Convert.FromBase64String(base64Image);
var tex = new Texture2D(1,1);
tex.LoadImage(b64_bytes);
tex.Apply();
return tex;
}
public static string ByteArrayToBase64(this byte[] byteArray)
{
if (byteArray == null)
{
return "";
}
return Convert.ToBase64String(byteArray);
}
public static T ToObject<T>(object json)
{
var obj = ToObject(json, typeof(T));
return (T) obj;
}
private static object ToObject(object json, Type type)
{
if (json == null || type == typeof(string))
{
return json;
}
if (type.IsPrimitive)
{
if (type == typeof(bool))
{
return json;
}
return Convert.ChangeType(json, type);
}
if (type.IsEnum)
{
return Enum.ToObject(type, Convert.ChangeType(json, typeof(int)));
}
if (type.IsGenericList())
{
var listType = typeof(List<>);
var genericType = type.GetGenericArguments()[0];
var constructedListType = listType.MakeGenericType(genericType);
var instance = (IList) Activator.CreateInstance(constructedListType);
foreach (var item in (List<object>) json)
{
instance.Add(GSJson.ToObject(item, genericType));
}
return instance;
}
if (type.IsGenericDictionary())
{
var dictionaryType = typeof(Dictionary<,>);
var keyType = type.GetGenericArguments()[0];
var valueType = type.GetGenericArguments()[1];
var constructedDictionaryType = dictionaryType.MakeGenericType(keyType, valueType);
var instance = (IDictionary) Activator.CreateInstance(constructedDictionaryType);
foreach (var item in (Dictionary<string, object>) json)
{
var key = GSJson.ToObject(item.Key, keyType);
instance[key] = GSJson.ToObject(item.Value, valueType);
}
return instance;
}
var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] {}, null);
if (constructor == null)
{
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] {}, null);
}
var res = constructor.Invoke(new object[]{});
var dictionary = (Dictionary<string, object>) json;
Action<FieldInfo> attrField = field =>
{
var attrs = (JsonSerializationKey[]) field.GetCustomAttributes
(typeof(JsonSerializationKey), false);
if (attrs.Length != 0)
{
var value = GSJson.ToObject(
dictionary.ContainsKey(attrs[0].Name) ? dictionary[attrs[0].Name] : null, field.FieldType);
field.SetValue(res, value);
}
};
Action<PropertyInfo> attrProperty = property =>
{
var attrs = (JsonSerializationKey[]) property.GetCustomAttributes
(typeof(JsonSerializationKey), false);
if (attrs.Length != 0)
{
var value = GSJson.ToObject(
dictionary.ContainsKey(attrs[0].Name) ? dictionary[attrs[0].Name] : null, property.PropertyType);
property.SetValue(res, value);
}
};
type.GetFields().ToList().ForEach(attrField);
type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).ToList().ForEach(attrField);
type.GetProperties().ToList().ForEach(attrProperty);
type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).ToList().ForEach(attrProperty);
return res;
}
private sealed class Parser : IDisposable
{
private const string WhiteSpace = " \t\n\r";
private const string WordBreak = " \t\n\r{}[],:\"";
private StringReader json;
private Parser(string jsonString)
{
this.json = new StringReader(jsonString);
}
private enum TOKEN
{
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
}
private char PeekChar
{
get
{
return Convert.ToChar(this.json.Peek());
}
}
private char NextChar
{
get
{
return Convert.ToChar(this.json.Read());
}
}
private string NextWord
{
get
{
StringBuilder word = new StringBuilder();
while (WordBreak.IndexOf(this.PeekChar) == -1)
{
word.Append(this.NextChar);
if (this.json.Peek() == -1)
{
break;
}
}
return word.ToString();
}
}
private TOKEN NextToken
{
get
{
this.EatWhitespace();
if (this.json.Peek() == -1)
{
return TOKEN.NONE;
}
char c = this.PeekChar;
switch (c)
{
case '{':
return TOKEN.CURLY_OPEN;
case '}':
this.json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
this.json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
this.json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = this.NextWord;
switch (word)
{
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
public static object Parse(string jsonString)
{
using (var instance = new Parser(jsonString))
{
return instance.ParseValue();
}
}
public void Dispose()
{
this.json.Dispose();
this.json = null;
}
private Dictionary<string, object> ParseObject()
{
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
this.json.Read();
// {
while (true)
{
switch (this.NextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = this.ParseString();
if (name == null)
{
return null;
}
// :
if (this.NextToken != TOKEN.COLON)
{
return null;
}
// ditch the colon
this.json.Read();
// value
table[name] = this.ParseValue();
break;
}
}
}
private List<object> ParseArray()
{
List<object> array = new List<object>();
// ditch opening bracket
this.json.Read();
// [
var parsing = true;
while (parsing)
{
TOKEN nextToken = this.NextToken;
switch (nextToken)
{
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = this.ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
private object ParseValue()
{
TOKEN nextToken = this.NextToken;
return this.ParseByToken(nextToken);
}
private object ParseByToken(TOKEN token)
{
switch (token)
{
case TOKEN.STRING:
return this.ParseString();
case TOKEN.NUMBER:
return this.ParseNumber();
case TOKEN.CURLY_OPEN:
return this.ParseObject();
case TOKEN.SQUARED_OPEN:
return this.ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
private string ParseString()
{
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
this.json.Read();
bool parsing = true;
while (parsing)
{
if (this.json.Peek() == -1)
{
parsing = false;
break;
}
c = this.NextChar;
switch (c)
{
case '"':
parsing = false;
break;
case '\\':
if (this.json.Peek() == -1)
{
parsing = false;
break;
}
c = this.NextChar;
switch (c)
{
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i = 0; i < 4; i++)
{
hex.Append(this.NextChar);
}
s.Append((char)Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
private object ParseNumber()
{
string number = this.NextWord;
if (number.IndexOf('.') == -1)
{
return long.Parse(number, numberFormat);
}
return double.Parse(number, numberFormat);
}
private void EatWhitespace()
{
while (WhiteSpace.IndexOf(this.PeekChar) != -1)
{
this.json.Read();
if (this.json.Peek() == -1)
{
break;
}
}
}
}
private sealed class Serializer
{
private StringBuilder builder;
private Serializer()
{
this.builder = new StringBuilder();
}
public static string Serialize(object obj)
{
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
private void SerializeValue(object value)
{
IList asList;
IDictionary asDict;
string asStr;
if (value == null)
{
this.builder.Append("null");
}
else if ((asStr = value as string) != null)
{
this.SerializeString(asStr);
}
else if (value is bool)
{
this.builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null)
{
this.SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null)
{
this.SerializeObject(asDict);
}
else if (value is char)
{
this.SerializeString(value.ToString());
}
else
{
this.SerializeOther(value);
}
}
private void SerializeObject(IDictionary obj)
{
bool first = true;
this.builder.Append('{');
foreach (object e in obj.Keys)
{
if (!first)
{
this.builder.Append(',');
}
this.SerializeString(e.ToString());
this.builder.Append(':');
this.SerializeValue(obj[e]);
first = false;
}
this.builder.Append('}');
}
private void SerializeArray(IList array)
{
this.builder.Append('[');
bool first = true;
foreach (object obj in array)
{
if (!first)
{
this.builder.Append(',');
}
this.SerializeValue(obj);
first = false;
}
this.builder.Append(']');
}
private void SerializeString(string str)
{
this.builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray)
{
switch (c)
{
case '"':
this.builder.Append("\\\"");
break;
case '\\':
this.builder.Append("\\\\");
break;
case '\b':
this.builder.Append("\\b");
break;
case '\f':
this.builder.Append("\\f");
break;
case '\n':
this.builder.Append("\\n");
break;
case '\r':
this.builder.Append("\\r");
break;
case '\t':
this.builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126))
{
this.builder.Append(c);
}
else
{
this.builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
this.builder.Append('\"');
}
private void SerializeOther(object value)
{
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal)
{
this.builder.Append(value.ToString());
}
else if (value.GetType().IsEnum)
{
this.builder.Append((int) value);
}
else {
var toJson = value.GetType().GetMethod("ToJson", BindingFlags.NonPublic | BindingFlags.Instance);
if (toJson == null)
{
this.SerializeObject(ToDictionary(value));
}
else
{
this.SerializeOther(toJson.Invoke(value, new object[]{}));
}
}
}
private static IDictionary ToDictionary(object value)
{
var type = value.GetType();
var dictionary = new Dictionary<string, object>();
Action<FieldInfo> attrField = field =>
{
var attrs = (JsonSerializationKey[]) field.GetCustomAttributes
(typeof(JsonSerializationKey), false);
foreach (var attr in attrs)
{
dictionary[attr.Name] = field.GetValue(value);
}
};
Action<PropertyInfo> attrProperty = field =>
{
var attrs = (JsonSerializationKey[]) field.GetCustomAttributes
(typeof(JsonSerializationKey), false);
foreach (var attr in attrs)
{
dictionary[attr.Name] = field.GetValue(value);
}
};
type.GetFields().ToList().ForEach(attrField);
type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).ToList().ForEach(attrField);
type.GetProperties().ToList().ForEach(attrProperty);
type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).ToList().ForEach(attrProperty);
return dictionary;
}
}
public static bool IsGenericList(this Type oType)
{
return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>)));
}
public static bool IsGenericDictionary(this Type oType)
{
return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(Dictionary<,>)));
}
}
}
| |
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Mozu.Api.Contracts.AppDev;
using Mozu.Api.Logging;
using Mozu.Api.Urls.Platform.Applications;
using Mozu.Api.Utilities;
using Newtonsoft.Json;
namespace Mozu.Api.Security
{
/// <summary>
/// This class handles Mozu application authentication.
/// </summary>
public sealed class AppAuthenticator
{
private static AppAuthenticator _auth = null;
private static object _lockObj = new Object();
private AppAuthInfo _appAuthInfo;
private RefreshInterval _refreshInterval = null;
private static ILogger _log = LogManager.GetLogger(typeof(AppAuthenticator));
/// <summary>
/// The application auth ticket
/// </summary>
public AuthTicket AppAuthTicket { get; protected set; }
/// <summary>
/// The baseUrl for App Auth. Once an app auths with this base url, all subsequent MOZU API calls will go to this base url.
/// </summary>
public string BaseUrl { get; private set; }
public static AppAuthenticator Instance
{
get { return _auth; }
}
public static bool UseSSL { get; set; }
internal AppAuthInfo AppAuthInfo
{
get { return _appAuthInfo; }
}
public static AppAuthenticator Initialize(AppAuthInfo appAuthInfo, RefreshInterval refreshInterval = null)
{
var baseAppAuthUrl = MozuConfig.BaseAppAuthUrl;
if (appAuthInfo == null || string.IsNullOrEmpty(baseAppAuthUrl))
throw new Exception("AppAuthInfo or Base App auth Url cannot be null or empty");
if (String.IsNullOrEmpty(appAuthInfo.ApplicationId) || String.IsNullOrEmpty(appAuthInfo.SharedSecret))
throw new Exception("ApplicationId or Shared Secret is missing");
if (_auth == null || (_auth != null && _auth.AppAuthInfo.ApplicationId != appAuthInfo.ApplicationId))
{
lock (_lockObj)
{
try
{
_log.Info("Initializing App");
var uri = new Uri(baseAppAuthUrl);
HttpHelper.UrlScheme = uri.Scheme;
_auth = new AppAuthenticator(appAuthInfo, baseAppAuthUrl, refreshInterval);
_auth.AuthenticateApp();
_log.Info("Initializing App..Done");
}
catch (ApiException exc)
{
_log.Error(exc.Message, exc);
_auth = null;
throw exc;
}
}
}
return _auth;
}
public static async Task<AppAuthenticator> InitializeAsync(AppAuthInfo appAuthInfo, RefreshInterval refreshInterval = null)
{
var baseAppAuthUrl = MozuConfig.BaseAppAuthUrl;
if (appAuthInfo == null || string.IsNullOrEmpty(baseAppAuthUrl))
throw new Exception("AppAuthInfo or Base App auth Url cannot be null or empty");
if (String.IsNullOrEmpty(appAuthInfo.ApplicationId) || String.IsNullOrEmpty(appAuthInfo.SharedSecret))
throw new Exception("ApplicationId or Shared Secret is missing");
if (_auth != null && _auth.AppAuthInfo.ApplicationId == appAuthInfo.ApplicationId)
return _auth;
try
{
_log.Info("Initializing App");
var uri = new Uri(baseAppAuthUrl);
HttpHelper.UrlScheme = uri.Scheme;
var tmp = new AppAuthenticator(appAuthInfo, baseAppAuthUrl, refreshInterval);
await tmp.AuthenticateAppAsync();
lock (_lockObj)
{
_auth = tmp;
}
_log.Info("Initializing App..Done");
}
catch (ApiException exc)
{
_log.Error(exc.Message, exc);
lock (_lockObj)
{
_auth = null;
}
throw exc;
}
return _auth;
}
/// <summary>
/// This contructor does application authentication and setups up the necessary timers to keep the app auth ticket valid.
/// </summary>
/// <param name="appId">The application version's app id</param>
/// <param name="sharedSecret">The application version's shared secret</param>
/// <param name="baseAppAuthUrl">The base URL of the Mozu application authentication service</param>
private AppAuthenticator(AppAuthInfo appAuthInfo, string baseAppAuthUrl, RefreshInterval refreshInterval = null)
{
BaseUrl = baseAppAuthUrl;
_appAuthInfo = appAuthInfo;
_refreshInterval = refreshInterval;
MozuConfig.SharedSecret = appAuthInfo.SharedSecret;
MozuConfig.ApplicationId = appAuthInfo.ApplicationId;
}
public static void DeleteAuth()
{
if (_auth != null)
{
var resourceUrl = AuthTicketUrl.DeleteAppAuthTicketUrl(_auth.AppAuthTicket.RefreshToken);
var client = new HttpClient { BaseAddress = new Uri(_auth.BaseUrl) };
var response = client.DeleteAsync(resourceUrl.Url).Result;
ResponseHelper.EnsureSuccess(response);
}
}
public static async Task DeleteAuthAsync()
{
if (_auth != null)
{
var resourceUrl = AuthTicketUrl.DeleteAppAuthTicketUrl(_auth.AppAuthTicket.RefreshToken);
var client = new HttpClient { BaseAddress = new Uri(_auth.BaseUrl) };
var response = await client.DeleteAsync(resourceUrl.Url);
ResponseHelper.EnsureSuccess(response);
}
}
/// <summary>
/// Do application authentication
/// </summary>
private void AuthenticateApp()
{
var resourceUrl = AuthTicketUrl.AuthenticateAppUrl();
_log.Info(String.Format("App authentication Url : {0}{1}", BaseUrl, resourceUrl.Url) );
var client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var stringContent = JsonConvert.SerializeObject(_appAuthInfo);
var response = client.PostAsync(resourceUrl.Url, new StringContent(stringContent, Encoding.UTF8, "application/json")).Result;
ResponseHelper.EnsureSuccess(response);
AppAuthTicket = response.Content.ReadAsAsync<AuthTicket>().Result;
SetRefreshIntervals(true);
}
private async Task AuthenticateAppAsync()
{
var resourceUrl = AuthTicketUrl.AuthenticateAppUrl();
_log.Info(String.Format("App authentication Url : {0}{1}", BaseUrl, resourceUrl.Url));
var client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var stringContent = JsonConvert.SerializeObject(_appAuthInfo);
var response = await client.PostAsync(resourceUrl.Url, new StringContent(stringContent, Encoding.UTF8, "application/json"));
ResponseHelper.EnsureSuccess(response);
AppAuthTicket = await response.Content.ReadAsAsync<AuthTicket>();
SetRefreshIntervals(true);
}
/// <summary>
/// Refresh the application auth ticket using the refresh token
/// </summary>
private void RefreshAppAuthTicket()
{
var resourceUrl = AuthTicketUrl.RefreshAppAuthTicketUrl();
_log.Info(String.Format("App authentication refresh Url : {0}{1}", BaseUrl, resourceUrl.Url));
var client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var authTicketRequest = new AuthTicketRequest { RefreshToken = AppAuthTicket.RefreshToken };
var stringContent = JsonConvert.SerializeObject(authTicketRequest);
var response = client.PutAsync(resourceUrl.Url, new StringContent(stringContent, Encoding.UTF8, "application/json")).Result;
ResponseHelper.EnsureSuccess(response);
AppAuthTicket = response.Content.ReadAsAsync<AuthTicket>().Result;
SetRefreshIntervals(false);
}
private async Task RefreshAppAuthTicketAsync()
{
var resourceUrl = AuthTicketUrl.RefreshAppAuthTicketUrl();
_log.Info(String.Format("App authentication refresh Url : {0}{1}", BaseUrl, resourceUrl.Url));
var client = new HttpClient { BaseAddress = new Uri(BaseUrl) };
var authTicketRequest = new AuthTicketRequest { RefreshToken = AppAuthTicket.RefreshToken };
var stringContent = JsonConvert.SerializeObject(authTicketRequest);
var response = await client.PutAsync(resourceUrl.Url, new StringContent(stringContent, Encoding.UTF8, "application/json"));
ResponseHelper.EnsureSuccess(response);
AppAuthTicket = await response.Content.ReadAsAsync<AuthTicket>();
SetRefreshIntervals(false);
}
private void SetRefreshIntervals(bool updateRefreshTokenInterval)
{
if (_refreshInterval == null)
{
_log.Info(String.Format("Access token expires at : {0}", AppAuthTicket.AccessTokenExpiration ));
_log.Info(String.Format("Refresh token expires at : {0}", AppAuthTicket.RefreshTokenExpiration ));
_refreshInterval =
new RefreshInterval((long) (AppAuthTicket.AccessTokenExpiration - DateTime.Now).TotalSeconds - 180,
(long)(AppAuthTicket.RefreshTokenExpiration - DateTime.Now).TotalSeconds - 180);
}
_refreshInterval.UpdateExpirationDates(updateRefreshTokenInterval);
}
/// <summary>
/// Ensure that the auth ticket is valid. If not, then make it so. Will be used when not using timers to keep the auth ticket alive (i.e. "on demand" mode).
/// </summary>
public void EnsureAuthTicket()
{
lock (_lockObj)
{
if (AppAuthTicket == null || DateTime.UtcNow >= _refreshInterval.RefreshTokenExpiration)
{
_log.Info("Refresh token Expired");
AuthenticateApp();
}
else if (DateTime.UtcNow >= _refreshInterval.AccessTokenExpiration)
{
_log.Info("Access token expored");
RefreshAppAuthTicket();
}
}
}
public async Task EnsureAuthTicketAsync()
{
lock (_lockObj)
{}
if (AppAuthTicket == null || DateTime.UtcNow >= _refreshInterval.RefreshTokenExpiration)
{
_log.Info("Refresh token Expired");
await AuthenticateAppAsync();
}
else if (DateTime.UtcNow >= _refreshInterval.AccessTokenExpiration)
{
_log.Info("Access token expored");
await RefreshAppAuthTicketAsync();
}
lock (_lockObj)
{ }
}
/// <summary>
/// This method adds the necessary app claims header to a http client to allow authorized calls to Mozu services
/// </summary>
/// <param name="client">The http client for which to add the header</param>
public static void AddHeader(HttpClient client)
{
if (_auth == null)
{
_log.Error("App is not initialized");
throw new ApplicationException("AppAuthTicketKeepAlive Not Initialized");
}
_auth.EnsureAuthTicket();
client.DefaultRequestHeaders.Add(Headers.X_VOL_APP_CLAIMS, _auth.AppAuthTicket.AccessToken);
}
public static void AddHeader(HttpRequestMessage requestMsg)
{
if (_auth == null)
{
_log.Error("App is not initialized");
throw new ApplicationException("AppAuthTicketKeepAlive Not Initialized");
}
_auth.EnsureAuthTicket();
requestMsg.Headers.Add(Headers.X_VOL_APP_CLAIMS, _auth.AppAuthTicket.AccessToken);
}
}
}
| |
/*
* Copyright 2012 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;
using System.Collections.Generic;
using ZXing.Common;
using ZXing.PDF417.Internal;
namespace ZXing.PDF417
{
/// <summary>
/// <author>Jacob Haynes</author>
/// <author>[email protected] (Andrew Walbran)</author>
/// </summary>
public sealed class PDF417Writer : Writer
{
/// <summary>
/// </summary>
/// <param name="contents">The contents to encode in the barcode</param>
/// <param name="format">The barcode format to generate</param>
/// <param name="width">The preferred width in pixels</param>
/// <param name="height">The preferred height in pixels</param>
/// <param name="hints">Additional parameters to supply to the encoder</param>
/// <returns>
/// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white)
/// </returns>
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
IDictionary<EncodeHintType, object> hints)
{
if (format != BarcodeFormat.PDF_417)
{
throw new ArgumentException("Can only encode PDF_417, but got " + format);
}
var encoder = new Internal.PDF417();
if (hints != null)
{
if (hints.ContainsKey(EncodeHintType.PDF417_COMPACT))
{
encoder.setCompact((Boolean)hints[EncodeHintType.PDF417_COMPACT]);
}
if (hints.ContainsKey(EncodeHintType.PDF417_COMPACTION))
{
encoder.setCompaction((Compaction)hints[EncodeHintType.PDF417_COMPACTION]);
}
if (hints.ContainsKey(EncodeHintType.PDF417_DIMENSIONS))
{
Dimensions dimensions = (Dimensions)hints[EncodeHintType.PDF417_DIMENSIONS];
encoder.setDimensions(dimensions.MaxCols,
dimensions.MinCols,
dimensions.MaxRows,
dimensions.MinRows);
}
}
return bitMatrixFromEncoder(encoder, contents, width, height);
}
/// <summary>
/// Encode a barcode using the default settings.
/// </summary>
/// <param name="contents">The contents to encode in the barcode</param>
/// <param name="format">The barcode format to generate</param>
/// <param name="width">The preferred width in pixels</param>
/// <param name="height">The preferred height in pixels</param>
/// <returns>
/// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white)
/// </returns>
public BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height)
{
return encode(contents, format, width, height, null);
}
/// <summary>
/// Use <see cref="encode(String, BarcodeFormat, int, int, IDictionary{TKey, TValue})" /> instead, with hints to
/// specify the encoding options.
/// </summary>
/// <returns></returns>
[Obsolete]
public BitMatrix encode(String contents,
BarcodeFormat format,
bool compact,
int width,
int height,
int minCols,
int maxCols,
int minRows,
int maxRows,
Compaction compaction)
{
IDictionary<EncodeHintType, Object> hints = new Dictionary<EncodeHintType, Object>();
hints[EncodeHintType.PDF417_COMPACT] = compact;
hints[EncodeHintType.PDF417_COMPACTION] = compaction;
hints[EncodeHintType.PDF417_DIMENSIONS] = new Dimensions(minCols, maxCols, minRows, maxRows);
return encode(contents, format, width, height, hints);
}
/// <summary>
/// Takes encoder, accounts for width/height, and retrieves bit matrix
/// </summary>
private static BitMatrix bitMatrixFromEncoder(Internal.PDF417 encoder,
String contents,
int width,
int height)
{
const int errorCorrectionLevel = 2;
encoder.generateBarcodeLogic(contents, errorCorrectionLevel);
const int lineThickness = 2;
const int aspectRatio = 4;
sbyte[][] originalScale = encoder.BarcodeMatrix.getScaledMatrix(lineThickness, aspectRatio * lineThickness);
bool rotated = false;
if ((height > width) ^ (originalScale[0].Length < originalScale.Length))
{
originalScale = rotateArray(originalScale);
rotated = true;
}
int scaleX = width / originalScale[0].Length;
int scaleY = height / originalScale.Length;
int scale;
if (scaleX < scaleY)
{
scale = scaleX;
}
else
{
scale = scaleY;
}
if (scale > 1)
{
sbyte[][] scaledMatrix =
encoder.BarcodeMatrix.getScaledMatrix(scale * lineThickness, scale * aspectRatio * lineThickness);
if (rotated)
{
scaledMatrix = rotateArray(scaledMatrix);
}
return bitMatrixFrombitArray(scaledMatrix);
}
return bitMatrixFrombitArray(originalScale);
}
/// <summary>
/// This takes an array holding the values of the PDF 417
///
/// <param name="input">a byte array of information with 0 is black, and 1 is white</param>
/// <returns>BitMatrix of the input</returns>
/// </summary>
private static BitMatrix bitMatrixFrombitArray(sbyte[][] input)
{
// Creates a small whitespace border around the barcode
const int whiteSpace = 30;
// Creates the bitmatrix with extra space for whitespace
var output = new BitMatrix(input[0].Length + 2 * whiteSpace, input.Length + 2 * whiteSpace);
var yOutput = output.Height - whiteSpace;
for (int y = 0; y < input.Length; y++)
{
for (int x = 0; x < input[0].Length; x++)
{
// Zero is white in the bytematrix
if (input[y][x] == 1)
{
output[x + whiteSpace, yOutput] = true;
}
}
yOutput--;
}
return output;
}
/// <summary>
/// Takes and rotates the it 90 degrees
/// </summary>
private static sbyte[][] rotateArray(sbyte[][] bitarray)
{
sbyte[][] temp = new sbyte[bitarray[0].Length][];
for (int idx = 0; idx < bitarray[0].Length; idx++)
temp[idx] = new sbyte[bitarray.Length];
for (int ii = 0; ii < bitarray.Length; ii++)
{
// This makes the direction consistent on screen when rotating the
// screen;
int inverseii = bitarray.Length - ii - 1;
for (int jj = 0; jj < bitarray[0].Length; jj++)
{
temp[jj][inverseii] = bitarray[ii][jj];
}
}
return temp;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Staff Availability for Calendar Extras Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SFAVDataSet : EduHubDataSet<SFAV>
{
/// <inheritdoc />
public override string Name { get { return "SFAV"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SFAVDataSet(EduHubContext Context)
: base(Context)
{
Index_TEACH = new Lazy<Dictionary<string, IReadOnlyList<SFAV>>>(() => this.ToGroupedDictionary(i => i.TEACH));
Index_TID = new Lazy<Dictionary<int, SFAV>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SFAV" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SFAV" /> fields for each CSV column header</returns>
internal override Action<SFAV, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SFAV, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "TEACH":
mapper[i] = (e, v) => e.TEACH = v;
break;
case "DAY_NUMBER":
mapper[i] = (e, v) => e.DAY_NUMBER = v == null ? (short?)null : short.Parse(v);
break;
case "START_TIME":
mapper[i] = (e, v) => e.START_TIME = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "END_TIME":
mapper[i] = (e, v) => e.END_TIME = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "AVAILABLE_DATE":
mapper[i] = (e, v) => e.AVAILABLE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SFAV" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SFAV" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SFAV" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SFAV}"/> of entities</returns>
internal override IEnumerable<SFAV> ApplyDeltaEntities(IEnumerable<SFAV> Entities, List<SFAV> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TEACH;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TEACH.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, IReadOnlyList<SFAV>>> Index_TEACH;
private Lazy<Dictionary<int, SFAV>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find SFAV by TEACH field
/// </summary>
/// <param name="TEACH">TEACH value used to find SFAV</param>
/// <returns>List of related SFAV entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SFAV> FindByTEACH(string TEACH)
{
return Index_TEACH.Value[TEACH];
}
/// <summary>
/// Attempt to find SFAV by TEACH field
/// </summary>
/// <param name="TEACH">TEACH value used to find SFAV</param>
/// <param name="Value">List of related SFAV entities</param>
/// <returns>True if the list of related SFAV entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTEACH(string TEACH, out IReadOnlyList<SFAV> Value)
{
return Index_TEACH.Value.TryGetValue(TEACH, out Value);
}
/// <summary>
/// Attempt to find SFAV by TEACH field
/// </summary>
/// <param name="TEACH">TEACH value used to find SFAV</param>
/// <returns>List of related SFAV entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SFAV> TryFindByTEACH(string TEACH)
{
IReadOnlyList<SFAV> value;
if (Index_TEACH.Value.TryGetValue(TEACH, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SFAV by TID field
/// </summary>
/// <param name="TID">TID value used to find SFAV</param>
/// <returns>Related SFAV entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SFAV FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find SFAV by TID field
/// </summary>
/// <param name="TID">TID value used to find SFAV</param>
/// <param name="Value">Related SFAV entity</param>
/// <returns>True if the related SFAV entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out SFAV Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find SFAV by TID field
/// </summary>
/// <param name="TID">TID value used to find SFAV</param>
/// <returns>Related SFAV entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SFAV TryFindByTID(int TID)
{
SFAV value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SFAV table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SFAV]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SFAV](
[TID] int IDENTITY NOT NULL,
[TEACH] varchar(4) NOT NULL,
[DAY_NUMBER] smallint NULL,
[START_TIME] datetime NULL,
[END_TIME] datetime NULL,
[AVAILABLE_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_DATE] datetime NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SFAV_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE CLUSTERED INDEX [SFAV_Index_TEACH] ON [dbo].[SFAV]
(
[TEACH] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SFAV]') AND name = N'SFAV_Index_TID')
ALTER INDEX [SFAV_Index_TID] ON [dbo].[SFAV] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SFAV]') AND name = N'SFAV_Index_TID')
ALTER INDEX [SFAV_Index_TID] ON [dbo].[SFAV] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SFAV"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SFAV"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SFAV> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[SFAV] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SFAV data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SFAV data set</returns>
public override EduHubDataSetDataReader<SFAV> GetDataSetDataReader()
{
return new SFAVDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SFAV data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SFAV data set</returns>
public override EduHubDataSetDataReader<SFAV> GetDataSetDataReader(List<SFAV> Entities)
{
return new SFAVDataReader(new EduHubDataSetLoadedReader<SFAV>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SFAVDataReader : EduHubDataSetDataReader<SFAV>
{
public SFAVDataReader(IEduHubDataSetReader<SFAV> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 9; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // TEACH
return Current.TEACH;
case 2: // DAY_NUMBER
return Current.DAY_NUMBER;
case 3: // START_TIME
return Current.START_TIME;
case 4: // END_TIME
return Current.END_TIME;
case 5: // AVAILABLE_DATE
return Current.AVAILABLE_DATE;
case 6: // LW_TIME
return Current.LW_TIME;
case 7: // LW_DATE
return Current.LW_DATE;
case 8: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // DAY_NUMBER
return Current.DAY_NUMBER == null;
case 3: // START_TIME
return Current.START_TIME == null;
case 4: // END_TIME
return Current.END_TIME == null;
case 5: // AVAILABLE_DATE
return Current.AVAILABLE_DATE == null;
case 6: // LW_TIME
return Current.LW_TIME == null;
case 7: // LW_DATE
return Current.LW_DATE == null;
case 8: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // TEACH
return "TEACH";
case 2: // DAY_NUMBER
return "DAY_NUMBER";
case 3: // START_TIME
return "START_TIME";
case 4: // END_TIME
return "END_TIME";
case 5: // AVAILABLE_DATE
return "AVAILABLE_DATE";
case 6: // LW_TIME
return "LW_TIME";
case 7: // LW_DATE
return "LW_DATE";
case 8: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "TEACH":
return 1;
case "DAY_NUMBER":
return 2;
case "START_TIME":
return 3;
case "END_TIME":
return 4;
case "AVAILABLE_DATE":
return 5;
case "LW_TIME":
return 6;
case "LW_DATE":
return 7;
case "LW_USER":
return 8;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#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.IO;
using System.Linq;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static class RecipientInfoCollectionTests
{
[Fact]
public static void TestCount()
{
RecipientInfoCollection col = CreateTestCollection();
Assert.Equal(3, col.Count);
}
[Fact]
public static void TestGetEnumerator()
{
RecipientInfoCollection col = CreateTestCollection();
ValidateMembers(col.GetEnumerator());
}
[Fact]
public static void TestExplicitGetEnumerator()
{
IEnumerable col = CreateTestCollection();
ValidateMembers(col.GetEnumerator());
}
[Fact]
public static void TestIndex()
{
RecipientInfoCollection col = CreateTestCollection();
RecipientInfo[] recipients = { col[0], col[1], col[2] };
ValidateMembers(recipients);
}
[Fact]
public static void TestIndexExceptions()
{
RecipientInfoCollection col = CreateTestCollection();
RecipientInfo ignore = null;
Assert.Throws<ArgumentOutOfRangeException>(() => ignore = col[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => ignore = col[3]);
}
[Fact]
public static void TestCopyTo()
{
RecipientInfoCollection col = CreateTestCollection();
RecipientInfo[] recipients = new RecipientInfo[3];
col.CopyTo(recipients, 0);
ValidateMembers(recipients);
}
[Fact]
public static void TestExplicitCopyTo()
{
ICollection col = CreateTestCollection();
RecipientInfo[] recipients = new RecipientInfo[3];
col.CopyTo(recipients, 0);
ValidateMembers(recipients);
}
[Fact]
public static void TestCopyToOffset()
{
RecipientInfoCollection col = CreateTestCollection();
RecipientInfo[] recipients = new RecipientInfo[6];
col.CopyTo(recipients, 2);
Assert.Null(recipients[0]);
Assert.Null(recipients[1]);
Assert.Null(recipients[5]);
ValidateMembers(recipients.Skip(2).Take(3));
}
[Fact]
public static void TestExplicitCopyToOffset()
{
ICollection col = CreateTestCollection();
RecipientInfo[] recipients = new RecipientInfo[6];
col.CopyTo(recipients, 2);
Assert.Null(recipients[0]);
Assert.Null(recipients[1]);
Assert.Null(recipients[5]);
ValidateMembers(recipients.Skip(2).Take(3));
}
[Fact]
public static void TestCopyToExceptions()
{
RecipientInfoCollection col = CreateTestCollection();
Assert.Throws<ArgumentNullException>(() => col.CopyTo(null, 0));
RecipientInfo[] recipients = new RecipientInfo[6];
col.CopyTo(recipients, 3);
AssertExtensions.Throws<ArgumentException>("destinationArray", null, () => col.CopyTo(recipients, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => col.CopyTo(recipients, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => col.CopyTo(recipients, 6));
ICollection ic = col;
AssertExtensions.Throws<ArgumentException>(null, () => ic.CopyTo(recipients, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(recipients, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(recipients, 6));
Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(recipients, 6));
AssertExtensions.Throws<ArgumentException>(null, () => ic.CopyTo(new RecipientInfo[2, 2], 0));
}
[Fact]
public static void TestExplicitCopyToExceptions()
{
ICollection col = CreateTestCollection();
Assert.Throws<ArgumentNullException>(() => col.CopyTo(null, 0));
RecipientInfo[] recipients = new RecipientInfo[6];
col.CopyTo(recipients, 3);
AssertExtensions.Throws<ArgumentException>(null, () => col.CopyTo(recipients, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => col.CopyTo(recipients, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => col.CopyTo(recipients, 6));
if (PlatformDetection.IsNonZeroLowerBoundArraySupported)
{
// Array has non-zero lower bound
Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 });
Assert.Throws<IndexOutOfRangeException>(() => col.CopyTo(array, 0));
}
}
private static void ValidateMembers(IEnumerable e)
{
ValidateMembers(e.GetEnumerator());
}
private static void ValidateMembers(IEnumerator e)
{
RecipientInfo[] recipients = new RecipientInfo[3];
Assert.True(e.MoveNext());
recipients[0] = (RecipientInfo)(e.Current);
Assert.True(e.MoveNext());
recipients[1] = (RecipientInfo)(e.Current);
Assert.True(e.MoveNext());
recipients[2] = (RecipientInfo)(e.Current);
Assert.False(e.MoveNext());
X509IssuerSerial[] si = recipients.Select(r => (X509IssuerSerial)(r.RecipientIdentifier.Value)).OrderBy(x => x.IssuerName).ToArray();
Assert.Equal("CN=RSAKeyTransfer1", si[0].IssuerName);
Assert.Equal("CN=RSAKeyTransfer2", si[1].IssuerName);
Assert.Equal("CN=RSAKeyTransfer3", si[2].IssuerName);
}
private static RecipientInfoCollection CreateTestCollection()
{
// Creates a RecipientInfoCollection with three items.
//
// Because RecipientInfoCollection can only be created by the framework, we have to do this the hard way...
//
byte[] encodedMessage =
("3082029f06092a864886f70d010703a08202903082028c020100318202583081c5020100302e301a31183016060355040313"
+ "0f5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004"
+ "818061b4161da3daff2c6c304b8decb021b09ee2523f5162124a6893b077b22a71327c8ab12a82f80472845e274643bfee33"
+ "d34caca6b59fffc66f7fdb2279726f58615258bc3787b479fdfeb4856279e85106d5c271b2f5cadcc8b5622f69cb7e7efd90"
+ "38727c1cb717cb867d2f3e87c3f653cb77837706abb01d40bb22136dac753081c5020100302e301a31183016060355040313"
+ "0f5253414b65795472616e736665723202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d010101050004"
+ "818077293ebfd59a4cef9161ef60f082eca1fd7b2e52804992ea5421527bbea35d7abf810d4316e07dfe766f90b221ae34aa"
+ "192e200c26105aba5511c5e168e4cb0bb2996dce730648d5bc8a0005fbb112a80f9a525e266654d4f3de8318abb8f769c387"
+ "e402889354965f05814dcc4a787de1d5442107ab1bf8dcdbeb432d4d70a73081c5020100302e301a31183016060355040313"
+ "0f5253414b65795472616e736665723302104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d010101050004"
+ "81807f2d1e0c34b9c4d8e07cf50107114e10f8c3759eca4bb6385451cf7d3619548b217670e4d9eea0c7a09c513c0e4fc1b1"
+ "978ee2b2aab4c7b04183031d2685bf5ea32b8b48d8eef34743bdf14ba71cde56c97618d48692e59f529cd5a7922caff4ac02"
+ "e5a856a5b28db681b0b508b9761b6fa05a5634742c3542986e4073e7932a302b06092a864886f70d010701301406082a8648"
+ "86f70d030704081ddc958302db22518008d0f4f5bb03b69819").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
return ecms.RecipientInfos;
}
}
}
| |
// <copyright file="ObservableCollectionUndoRedoSpecialFeaturesUnitTests.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using IX.Observable;
using Xunit;
namespace IX.UnitTests.Observable;
/// <summary>
/// Special undo/redo features test for observable collections.
/// </summary>
public class ObservableCollectionUndoRedoSpecialFeaturesUnitTests
{
/// <summary>
/// Generates the test data.
/// </summary>
/// <returns>The test data.</returns>
public static object[][] GeneratePredefinedData() => new[]
{
new object[]
{
new ObservableList<int>(
new[]
{
1,
7,
19,
23,
4,
}),
},
new object[]
{
new ConcurrentObservableList<int>(
new[]
{
1,
7,
19,
23,
4,
}),
},
};
/// <summary>
/// Generates the test data.
/// </summary>
/// <returns>The test data.</returns>
public static object[][] GenerateSupressedUndoContextData() => new[]
{
new object[]
{
new ObservableList<int>(true)
{
1,
7,
19,
23,
4,
},
},
new object[]
{
new ConcurrentObservableList<int>(true)
{
1,
7,
19,
23,
4,
},
},
};
/// <summary>
/// When a list has predefined data (straight from the constructor), it should not be able to undo or redo.
/// </summary>
/// <param name="list">The list.</param>
[Theory(DisplayName = "ObservableList with predefined data, undo/redo does nothing")]
[MemberData(nameof(GeneratePredefinedData))]
public void UnitTest1(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT 1
list.Undo();
// ASSERT 1
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT 2
list.Redo();
// ASSERT 2
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
/// <summary>
/// When a list has its undo context suppressed, it should not be able to undo or redo.
/// </summary>
/// <param name="list">The list.</param>
[Theory(DisplayName = "ObservableList with suppressed context, undo/redo does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest2(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT 1
list.Undo();
// ASSERT 1
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT 2
list.Redo();
// ASSERT 2
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
/// <summary>
/// When a list has its undo context suppressed, then activated, it should not be able to undo or redo.
/// </summary>
/// <param name="list">The list.</param>
[Theory(DisplayName = "ObservableList with suppressed then activated context, undo/redo does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest3(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT
list.StartUndo();
// ASSERT
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
/// <summary>
/// When a list has its undo context suppressed, then activated, it should not be able to undo or redo in either part
/// of the test.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName =
"ObservableList with suppressed context, undo/redo does nothing, then activated and also does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest4(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT
list.StartUndo();
// ASSERT
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
/// <summary>
/// When a list has its undo context suppressed, then activated, it should not be able to undo or redo in either part
/// of the test if there is action before starting.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName =
"ObservableList with suppressed context and acted on, undo/redo does nothing, then activated and also does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest5(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT
list.RemoveAt(0);
// ASSERT
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.StartUndo();
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
/// <summary>
/// When a list has its undo context suppressed, then activated, it should not be able to undo or redo in either part
/// of the test if there is action before starting, but should do something if htere is action after starting.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName =
"ObservableList with suppressed context and acted on, undo/redo does nothing, then activated and acted on, does only undo the last act")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest6(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT
list.RemoveAt(0);
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.StartUndo();
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.RemoveAt(0);
// ASSERT
Assert.Equal(
3,
list.Count);
Assert.True(list.CanUndo);
Assert.False(list.CanRedo);
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.True(list.CanRedo);
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.True(list.CanRedo);
list.Redo();
Assert.Equal(
3,
list.Count);
Assert.True(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
3,
list.Count);
Assert.True(list.CanUndo);
Assert.False(list.CanRedo);
}
/// <summary>
/// When a list (captured) has predefined data (straight from the constructor), it should not be able to undo or redo.
/// </summary>
/// <param name="list">The list.</param>
[Theory(DisplayName = "ObservableList (captured) with predefined data, undo/redo does nothing")]
[MemberData(nameof(GeneratePredefinedData))]
public void UnitTest11(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// Capture into a parent context
using (var capturingList = new ObservableList<ObservableList<int>> { AutomaticallyCaptureSubItems = true })
{
Assert.Null(list.ParentUndoContext);
capturingList.Add(list);
Assert.Equal(
capturingList,
list.ParentUndoContext);
// ACT 1
list.Undo();
// ASSERT 1
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT 2
list.Redo();
// ASSERT 2
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
}
/// <summary>
/// When a list (captured) has its undo context suppressed, it should not be able to undo or redo.
/// </summary>
/// <param name="list">The list.</param>
[Theory(DisplayName = "ObservableList (captured) with suppressed context, undo/redo does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest12(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// Capture into a parent context
using (var capturingList = new ObservableList<ObservableList<int>> { AutomaticallyCaptureSubItems = true })
{
Assert.Null(list.ParentUndoContext);
capturingList.Add(list);
Assert.Equal(
capturingList,
list.ParentUndoContext);
// ACT 1
list.Undo();
// ASSERT 1
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// ACT 2
list.Redo();
// ASSERT 2
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
}
/// <summary>
/// When a list (captured) has its undo context suppressed, then activated, it should not be able to undo or redo.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName = "ObservableList (captured) with suppressed then activated context, undo/redo does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest13(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// Capture into a parent context
using (var capturingList = new ObservableList<ObservableList<int>> { AutomaticallyCaptureSubItems = true })
{
Assert.Null(list.ParentUndoContext);
capturingList.Add(list);
Assert.Equal(
capturingList,
list.ParentUndoContext);
// ACT
list.StartUndo();
// ASSERT
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
}
/// <summary>
/// When a list (captured) has its undo context suppressed, then activated, it should not be able to undo or redo in
/// either part of the test.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName =
"ObservableList (captured) with suppressed context, undo/redo does nothing, then activated and also does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest14(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// Capture into a parent context
using (var capturingList = new ObservableList<ObservableList<int>> { AutomaticallyCaptureSubItems = true })
{
Assert.Null(list.ParentUndoContext);
capturingList.Add(list);
Assert.Equal(
capturingList,
list.ParentUndoContext);
// ACT
list.StartUndo();
// ASSERT
list.Undo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
}
/// <summary>
/// When a list (captured) has its undo context suppressed, then activated, it should not be able to undo or redo in
/// either part of the test if there is action before starting.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName =
"ObservableList (captured) with suppressed context and acted on, undo/redo does nothing, then activated and also does nothing")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest15(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// Capture into a parent context
using (var capturingList = new ObservableList<ObservableList<int>> { AutomaticallyCaptureSubItems = true })
{
Assert.Null(list.ParentUndoContext);
capturingList.Add(list);
Assert.Equal(
capturingList,
list.ParentUndoContext);
// ACT
list.RemoveAt(0);
// ASSERT
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.StartUndo();
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
}
}
/// <summary>
/// When a list (captured) has its undo context suppressed, then activated, it should not be able to undo or redo in
/// either part of the test if there is action before starting, but should do something if htere is action after
/// starting.
/// </summary>
/// <param name="list">The list.</param>
[Theory(
DisplayName =
"ObservableList (captured) with suppressed context and acted on, undo/redo does nothing, then activated and acted on, does only undo the last act")]
[MemberData(nameof(GenerateSupressedUndoContextData))]
public void UnitTest16(ObservableList<int> list)
{
// ARRANGE
// =======
// Initial assertions
Assert.Equal(
5,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
// Capture into a parent context
using (var capturingList = new ObservableList<ObservableList<int>> { AutomaticallyCaptureSubItems = true })
{
Assert.Null(list.ParentUndoContext);
capturingList.Add(list);
Assert.Equal(
capturingList,
list.ParentUndoContext);
// ACT
list.RemoveAt(0);
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.StartUndo();
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.False(list.CanRedo);
list.RemoveAt(0);
// ASSERT
Assert.Equal(
3,
list.Count);
Assert.True(list.CanUndo);
Assert.False(list.CanRedo);
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.True(list.CanRedo);
list.Undo();
Assert.Equal(
4,
list.Count);
Assert.False(list.CanUndo);
Assert.True(list.CanRedo);
list.Redo();
Assert.Equal(
3,
list.Count);
Assert.True(list.CanUndo);
Assert.False(list.CanRedo);
list.Redo();
Assert.Equal(
3,
list.Count);
Assert.True(list.CanUndo);
Assert.False(list.CanRedo);
}
}
/// <summary>
/// When a list (captured) that has items from within the constructor sets its AutomaticallyCaptureItems property to
/// true, it should change existing items to capture them as well.
/// </summary>
[Fact(DisplayName = "ObservableList (captured) activating its captures from constructor")]
public void UnitTest17()
{
// ARRANGE
using (var capturingList = new ObservableList<CapturedItem>(new[] { new CapturedItem() }))
{
// Capture into a parent context
using (var upperCapturingList = new ObservableList<ObservableList<CapturedItem>>
{
AutomaticallyCaptureSubItems = true,
})
{
Assert.Null(capturingList.ParentUndoContext);
upperCapturingList.Add(capturingList);
Assert.Equal(
upperCapturingList,
capturingList.ParentUndoContext);
Assert.Null(capturingList[0].ParentUndoContext);
// ACT
capturingList.AutomaticallyCaptureSubItems = true;
// ASSERT
Assert.Equal(
capturingList,
capturingList[0].ParentUndoContext);
}
}
}
/// <summary>
/// When a list (captured) that has items from adding sets its AutomaticallyCaptureItems property to true, it should
/// change existing items to capture them as well.
/// </summary>
[Fact(DisplayName = "ObservableList (captured) activating its captures from adding")]
public void UnitTest18()
{
// ARRANGE
using (var capturingList = new ObservableList<CapturedItem>
{
new CapturedItem(),
})
{
// Capture into a parent context
using (var upperCapturingList = new ObservableList<ObservableList<CapturedItem>>
{ AutomaticallyCaptureSubItems = true })
{
Assert.Null(capturingList.ParentUndoContext);
upperCapturingList.Add(capturingList);
Assert.Equal(
upperCapturingList,
capturingList.ParentUndoContext);
Assert.Null(capturingList[0].ParentUndoContext);
// ACT
capturingList.AutomaticallyCaptureSubItems = true;
// ASSERT
Assert.Equal(
capturingList,
capturingList[0].ParentUndoContext);
}
}
}
/// <summary>
/// When a list that has items from within the constructor sets its AutomaticallyCaptureItems property to true, it
/// should change existing items to capture them as well.
/// </summary>
[Fact(DisplayName = "ObservableList activating its captures from constructor")]
public void UnitTest7()
{
// ARRANGE
using (var capturingList = new ObservableList<CapturedItem>(new[] { new CapturedItem() }))
{
Assert.Null(capturingList[0].ParentUndoContext);
// ACT
capturingList.AutomaticallyCaptureSubItems = true;
// ASSERT
Assert.Equal(
capturingList,
capturingList[0].ParentUndoContext);
}
}
/// <summary>
/// When a list that has items from adding sets its AutomaticallyCaptureItems property to true, it should change
/// existing items to capture them as well.
/// </summary>
[Fact(DisplayName = "ObservableList activating its captures from adding")]
public void UnitTest8()
{
// ARRANGE
using (var capturingList = new ObservableList<CapturedItem>
{
new CapturedItem(),
})
{
Assert.Null(capturingList[0].ParentUndoContext);
// ACT
capturingList.AutomaticallyCaptureSubItems = true;
// ASSERT
Assert.Equal(
capturingList,
capturingList[0].ParentUndoContext);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Network;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Network Management API includes operations for managing the Virtual
/// IPs for your deployment.
/// </summary>
internal partial class VirtualIPOperations : IServiceOperations<NetworkManagementClient>, IVirtualIPOperations
{
/// <summary>
/// Initializes a new instance of the VirtualIPOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualIPOperations(NetworkManagementClient client)
{
this._client = client;
}
private NetworkManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient.
/// </summary>
public NetworkManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The Add Virtual IP operation adds a logical Virtual IP to the
/// deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the hosted service that contains the given
/// deployment.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment where the logical Virtual IP
/// is to be added.
/// </param>
/// <param name='virtualIPName'>
/// Required. The name of the logical Virtual IP to be added.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> AddAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("virtualIPName", virtualIPName);
TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.VirtualIPs.BeginAddingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Begin Adding Virtual IP operation adds a logical Virtual IP to
/// the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the hosted service that contains the given
/// deployment.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment where the logical Virtual IP
/// is to be added.
/// </param>
/// <param name='virtualIPName'>
/// Required. The name of the logical Virtual IP to be added.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginAddingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (virtualIPName == null)
{
throw new ArgumentNullException("virtualIPName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("virtualIPName", virtualIPName);
TracingAdapter.Enter(invocationId, this, "BeginAddingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/";
url = url + Uri.EscapeDataString(virtualIPName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Begin Removing Virtual IP operation removes a logical Virtual
/// IP from the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the hosted service that contains the given
/// deployment.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment whose logical Virtual IP is to
/// be removed.
/// </param>
/// <param name='virtualIPName'>
/// Required. The name of the logical Virtual IP to be added.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> BeginRemovingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken)
{
// Validate
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (deploymentName == null)
{
throw new ArgumentNullException("deploymentName");
}
if (virtualIPName == null)
{
throw new ArgumentNullException("virtualIPName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("virtualIPName", virtualIPName);
TracingAdapter.Enter(invocationId, this, "BeginRemovingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/hostedservices/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/deployments/";
url = url + Uri.EscapeDataString(deploymentName);
url = url + "/virtualIPs/";
url = url + Uri.EscapeDataString(virtualIPName);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
result = new OperationStatusResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Remove Virtual IP operation removes a logical Virtual IP from
/// the deployment.
/// </summary>
/// <param name='serviceName'>
/// Required. The name of the hosted service that contains the given
/// deployment.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment whose logical Virtual IP is to
/// be removed.
/// </param>
/// <param name='virtualIPName'>
/// Required. The name of the logical Virtual IP to be removed.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<OperationStatusResponse> RemoveAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken)
{
NetworkManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("deploymentName", deploymentName);
tracingParameters.Add("virtualIPName", virtualIPName);
TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse response = await client.VirtualIPs.BeginRemovingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != OperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using Microsoft.Extensions.DependencyModel;
namespace Microsoft.DotNet.CommandFactory
{
public class DepsJsonCommandResolver : ICommandResolver
{
private static readonly string[] s_extensionPreferenceOrder = new[]
{
"",
".exe",
".dll"
};
private string _nugetPackageRoot;
private Muxer _muxer;
public DepsJsonCommandResolver(string nugetPackageRoot)
: this(new Muxer(), nugetPackageRoot) { }
public DepsJsonCommandResolver(Muxer muxer, string nugetPackageRoot)
{
_muxer = muxer;
_nugetPackageRoot = nugetPackageRoot;
}
public CommandSpec Resolve(CommandResolverArguments commandResolverArguments)
{
if (commandResolverArguments.CommandName == null
|| commandResolverArguments.DepsJsonFile == null)
{
return null;
}
return ResolveFromDepsJsonFile(
commandResolverArguments.CommandName,
commandResolverArguments.CommandArguments.OrEmptyIfNull(),
commandResolverArguments.DepsJsonFile);
}
private CommandSpec ResolveFromDepsJsonFile(
string commandName,
IEnumerable<string> commandArgs,
string depsJsonFile)
{
var dependencyContext = LoadDependencyContextFromFile(depsJsonFile);
var commandPath = GetCommandPathFromDependencyContext(commandName, dependencyContext);
if (commandPath == null)
{
return null;
}
return CreateCommandSpecUsingMuxerIfPortable(
commandPath,
commandArgs,
depsJsonFile,
_nugetPackageRoot,
IsPortableApp(commandPath));
}
public DependencyContext LoadDependencyContextFromFile(string depsJsonFile)
{
DependencyContext dependencyContext = null;
DependencyContextJsonReader contextReader = new DependencyContextJsonReader();
using (var contextStream = File.OpenRead(depsJsonFile))
{
dependencyContext = contextReader.Read(contextStream);
}
return dependencyContext;
}
public string GetCommandPathFromDependencyContext(string commandName, DependencyContext dependencyContext)
{
var commandCandidates = new List<CommandCandidate>();
var assemblyCommandCandidates = GetCommandCandidates(
commandName,
dependencyContext,
CommandCandidateType.RuntimeCommandCandidate);
var nativeCommandCandidates = GetCommandCandidates(
commandName,
dependencyContext,
CommandCandidateType.NativeCommandCandidate);
commandCandidates.AddRange(assemblyCommandCandidates);
commandCandidates.AddRange(nativeCommandCandidates);
var command = ChooseCommandCandidate(commandCandidates);
return command?.GetAbsoluteCommandPath(_nugetPackageRoot);
}
private IEnumerable<CommandCandidate> GetCommandCandidates(
string commandName,
DependencyContext dependencyContext,
CommandCandidateType commandCandidateType)
{
var commandCandidates = new List<CommandCandidate>();
foreach (var runtimeLibrary in dependencyContext.RuntimeLibraries)
{
IEnumerable<RuntimeAssetGroup> runtimeAssetGroups = null;
if (commandCandidateType == CommandCandidateType.NativeCommandCandidate)
{
runtimeAssetGroups = runtimeLibrary.NativeLibraryGroups;
}
else if (commandCandidateType == CommandCandidateType.RuntimeCommandCandidate)
{
runtimeAssetGroups = runtimeLibrary.RuntimeAssemblyGroups;
}
commandCandidates.AddRange(GetCommandCandidatesFromRuntimeAssetGroups(
commandName,
runtimeAssetGroups,
runtimeLibrary.Name,
runtimeLibrary.Version));
}
return commandCandidates;
}
private IEnumerable<CommandCandidate> GetCommandCandidatesFromRuntimeAssetGroups(
string commandName,
IEnumerable<RuntimeAssetGroup> runtimeAssetGroups,
string PackageName,
string PackageVersion)
{
var candidateAssetGroups = runtimeAssetGroups
.Where(r => r.Runtime == string.Empty)
.Where(a =>
a.AssetPaths.Any(p =>
Path.GetFileNameWithoutExtension(p).Equals(commandName, StringComparison.OrdinalIgnoreCase)));
var commandCandidates = new List<CommandCandidate>();
foreach (var candidateAssetGroup in candidateAssetGroups)
{
var candidateAssetPaths = candidateAssetGroup.AssetPaths.Where(
p => Path.GetFileNameWithoutExtension(p)
.Equals(commandName, StringComparison.OrdinalIgnoreCase));
foreach (var candidateAssetPath in candidateAssetPaths)
{
commandCandidates.Add(new CommandCandidate
{
PackageName = PackageName,
PackageVersion = PackageVersion,
RelativeCommandPath = candidateAssetPath
});
}
}
return commandCandidates;
}
private CommandCandidate ChooseCommandCandidate(IEnumerable<CommandCandidate> commandCandidates)
{
foreach (var extension in s_extensionPreferenceOrder)
{
var candidate = commandCandidates
.FirstOrDefault(p => Path.GetExtension(p.RelativeCommandPath)
.Equals(extension, StringComparison.OrdinalIgnoreCase));
if (candidate != null)
{
return candidate;
}
}
return null;
}
private CommandSpec CreateCommandSpecUsingMuxerIfPortable(
string commandPath,
IEnumerable<string> commandArgs,
string depsJsonFile,
string nugetPackagesRoot,
bool isPortable)
{
var depsFileArguments = GetDepsFileArguments(depsJsonFile);
var additionalProbingPathArguments = GetAdditionalProbingPathArguments();
var muxerArgs = new List<string>();
muxerArgs.Add("exec");
muxerArgs.AddRange(depsFileArguments);
muxerArgs.AddRange(additionalProbingPathArguments);
muxerArgs.Add(commandPath);
muxerArgs.AddRange(commandArgs);
var escapedArgString = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(muxerArgs);
return new CommandSpec(_muxer.MuxerPath, escapedArgString);
}
private bool IsPortableApp(string commandPath)
{
var commandDir = Path.GetDirectoryName(commandPath);
var runtimeConfigPath = Directory.EnumerateFiles(commandDir)
.FirstOrDefault(x => x.EndsWith("runtimeconfig.json"));
if (runtimeConfigPath == null)
{
return false;
}
var runtimeConfig = new RuntimeConfig(runtimeConfigPath);
return runtimeConfig.IsPortable;
}
private IEnumerable<string> GetDepsFileArguments(string depsJsonFile)
{
return new[] { "--depsfile", depsJsonFile };
}
private IEnumerable<string> GetAdditionalProbingPathArguments()
{
return new[] { "--additionalProbingPath", _nugetPackageRoot };
}
private class CommandCandidate
{
public string PackageName { get; set; }
public string PackageVersion { get; set; }
public string RelativeCommandPath { get; set; }
public string GetAbsoluteCommandPath(string nugetPackageRoot)
{
return Path.Combine(
nugetPackageRoot.Replace('/', Path.DirectorySeparatorChar),
PackageName.Replace('/', Path.DirectorySeparatorChar),
PackageVersion.Replace('/', Path.DirectorySeparatorChar),
RelativeCommandPath.Replace('/', Path.DirectorySeparatorChar));
}
}
private enum CommandCandidateType
{
NativeCommandCandidate,
RuntimeCommandCandidate
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if !PORTABLE && !NETSTANDARD1_6
using System;
using System.Collections;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Summary description for PlatformHelperTests.
/// </summary>
[TestFixture]
public class PlatformDetectionTests
{
private static readonly PlatformHelper win95Helper = new PlatformHelper(
new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private static readonly PlatformHelper winXPHelper = new PlatformHelper(
new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ),
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );
private void CheckOSPlatforms( OSPlatform os,
string expectedPlatforms )
{
Assert.That(expectedPlatforms, Is.SubsetOf(PlatformHelper.OSPlatforms).IgnoreCase,
"Error in test: one or more expected platforms is not a valid OSPlatform.");
CheckPlatforms(
new PlatformHelper( os, RuntimeFramework.CurrentFramework ),
expectedPlatforms,
PlatformHelper.OSPlatforms );
}
private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework,
string expectedPlatforms )
{
CheckPlatforms(
new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ),
expectedPlatforms,
PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,NET-4.5,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH" );
}
private void CheckPlatforms( PlatformHelper helper,
string expectedPlatforms, string checkPlatforms )
{
string[] expected = expectedPlatforms.Split( new char[] { ',' } );
string[] check = checkPlatforms.Split( new char[] { ',' } );
foreach( string testPlatform in check )
{
bool shouldPass = false;
foreach( string platform in expected )
if ( shouldPass = platform.ToLower() == testPlatform.ToLower() )
break;
bool didPass = helper.IsPlatformSupported( testPlatform );
if ( shouldPass && !didPass )
Assert.Fail( "Failed to detect {0}", testPlatform );
else if ( didPass && !shouldPass )
Assert.Fail( "False positive on {0}", testPlatform );
else if ( !shouldPass && !didPass )
Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason );
}
}
[Test]
public void DetectWin95()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ),
"Win95,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWin98()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ),
"Win98,Win32Windows,Win32,Win" );
}
[Test]
public void DetectWinMe()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ),
"WinMe,Win32Windows,Win32,Win" );
}
[Test]
public void DetectNT3()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ),
"NT3,Win32NT,Win32,Win" );
}
[Test]
public void DetectNT4()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ),
"NT4,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2K()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ),
"Win2K,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXP()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWinXPProfessionalX64()
{
CheckOSPlatforms(
new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ),
"WinXP,NT5,Win32NT,Win32,Win" );
}
[Test]
public void DetectWin2003Server()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server),
"Win2003Server,NT5,Win32NT,Win32,Win");
}
[Test]
public void DetectVista()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation),
"Vista,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server),
"Win2008Server,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWin2008ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server),
"Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows7()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation),
"Win7,Windows7,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerOriginal()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows2012ServerR2()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.Server),
"Win2012Server,Win2012ServerR2,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows8()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.WorkStation),
"Win8,Windows8,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows81()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.WorkStation),
"Win8.1,Windows8.1,NT6,Win32NT,Win32,Win");
}
[Test]
public void DetectWindows10()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.WorkStation),
"Win10,Windows10,Win32NT,Win32,Win");
}
[Test]
public void DetectWindowsServer()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.Server),
"WindowsServer10,Win32NT,Win32,Win");
}
[Test]
public void DetectUnixUnderMicrosoftDotNet()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)),
"UNIX,Linux");
}
[Test]
public void DetectUnixUnderMono()
{
CheckOSPlatforms(
new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)),
"UNIX,Linux");
}
[Test]
public void DetectXbox()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.Xbox, new Version(0, 0)),
"Xbox");
}
[Test]
public void DetectMacOSX()
{
CheckOSPlatforms(
new OSPlatform(PlatformID.MacOSX, new Version(0, 0)),
"MacOSX");
}
[Test]
public void DetectNet10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ),
"NET,NET-1.0" );
}
[Test]
public void DetectNet11()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ),
"NET,NET-1.1" );
}
[Test]
public void DetectNet20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 50727, 0 ) ),
"Net,Net-2.0" );
}
[Test]
public void DetectNet30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(3, 0)),
"Net,Net-2.0,Net-3.0");
}
[Test]
public void DetectNet35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(3, 5)),
"Net,Net-2.0,Net-3.0,Net-3.5");
}
[Test]
public void DetectNet40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)),
"Net,Net-4.0");
}
[Test]
public void DetectSSCLI()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ),
"SSCLI,Rotor" );
}
[Test]
public void DetectMono10()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ),
"Mono,Mono-1.0" );
}
[Test]
public void DetectMono20()
{
CheckRuntimePlatforms(
new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ),
"Mono,Mono-2.0" );
}
[Test]
public void DetectMono30()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)),
"Mono,Mono-2.0,Mono-3.0");
}
[Test]
public void DetectMono35()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)),
"Mono,Mono-2.0,Mono-3.0,Mono-3.5");
}
[Test]
public void DetectMono40()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)),
"Mono,Mono-4.0");
}
[Test]
public void DetectMonoTouch()
{
CheckRuntimePlatforms(
new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)),
"MonoTouch");
}
[Test]
public void DetectExactVersion()
{
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) );
Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) );
Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) );
}
[Test]
public void ArrayOfPlatforms()
{
string[] platforms = new string[] { "NT4", "Win2K", "WinXP" };
Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) );
}
[Test]
public void PlatformAttribute_Include()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason);
}
[Test]
public void PlatformAttribute_Exclude()
{
PlatformAttribute attr = new PlatformAttribute();
attr.Exclude = "Win2K,WinXP,NT4";
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason );
Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) );
}
[Test]
public void PlatformAttribute_IncludeAndExclude()
{
PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
attr.Exclude = "Mono";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
attr.Exclude = "Net";
Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.AreEqual( "Not supported on Net", winXPHelper.Reason );
}
[Test]
public void PlatformAttribute_InvalidPlatform()
{
PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" );
Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
Assert.That( winXPHelper.Reason, Does.StartWith("Invalid platform name"));
Assert.That( winXPHelper.Reason, Does.Contain("Net11"));
}
[Test]
public void PlatformAttribute_ProcessBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit");
PlatformHelper helper = new PlatformHelper();
// This test verifies that the two labels are known,
// do not cause an error and return consistent results.
bool is32BitProcess = helper.IsPlatformSupported(attr32);
bool is64BitProcess = helper.IsPlatformSupported(attr64);
Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit");
#if ASYNC
// For .NET 4.0 and 4.5, we can check further
Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess));
#endif
}
#if ASYNC
[Test]
public void PlatformAttribute_OperatingSystemBitNess()
{
PlatformAttribute attr32 = new PlatformAttribute("32-Bit-OS");
PlatformAttribute attr64 = new PlatformAttribute("64-Bit-OS");
PlatformHelper helper = new PlatformHelper();
bool is64BitOS = Environment.Is64BitOperatingSystem;
Assert.That(helper.IsPlatformSupported(attr32), Is.Not.EqualTo(is64BitOS));
Assert.That(helper.IsPlatformSupported(attr64), Is.EqualTo(is64BitOS));
}
#endif
}
}
#endif
| |
//
// Encog(tm) Core v3.2 - .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.Generic;
using Encog.Engine.Network.Activation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Encog.ML.Data.Temporal
{
[TestClass]
public class TestTemporal
{
[TestMethod]
public void BasicTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.Generate();
Assert.AreEqual(10, temporal.InputNeuronCount);
Assert.AreEqual(1, temporal.OutputNeuronCount);
Assert.AreEqual(10, temporal.CalculateActualSetSize());
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
itr.MoveNext();
// set 0
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(1.0, pair.Input[0]);
Assert.AreEqual(2.0, pair.Input[1]);
Assert.AreEqual(4.0, pair.Input[2]);
Assert.AreEqual(5.0, pair.Input[3]);
Assert.AreEqual(7.0, pair.Input[4]);
Assert.AreEqual(8.0, pair.Input[5]);
Assert.AreEqual(10.0, pair.Input[6]);
Assert.AreEqual(11.0, pair.Input[7]);
Assert.AreEqual(13.0, pair.Input[8]);
Assert.AreEqual(14.0, pair.Input[9]);
Assert.AreEqual(18.0, pair.Ideal[0]);
// set 1
itr.MoveNext();
pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(4.0, pair.Input[0]);
Assert.AreEqual(5.0, pair.Input[1]);
Assert.AreEqual(7.0, pair.Input[2]);
Assert.AreEqual(8.0, pair.Input[3]);
Assert.AreEqual(10.0, pair.Input[4]);
Assert.AreEqual(11.0, pair.Input[5]);
Assert.AreEqual(13.0, pair.Input[6]);
Assert.AreEqual(14.0, pair.Input[7]);
Assert.AreEqual(16.0, pair.Input[8]);
Assert.AreEqual(17.0, pair.Input[9]);
Assert.AreEqual(21.0, pair.Ideal[0]);
// set 2
itr.MoveNext();
pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(7.0, pair.Input[0]);
Assert.AreEqual(8.0, pair.Input[1]);
Assert.AreEqual(10.0, pair.Input[2]);
Assert.AreEqual(11.0, pair.Input[3]);
Assert.AreEqual(13.0, pair.Input[4]);
Assert.AreEqual(14.0, pair.Input[5]);
Assert.AreEqual(16.0, pair.Input[6]);
Assert.AreEqual(17.0, pair.Input[7]);
Assert.AreEqual(19.0, pair.Input[8]);
Assert.AreEqual(20.0, pair.Input[9]);
Assert.AreEqual(24.0, pair.Ideal[0]);
// set 3
itr.MoveNext();
pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(10.0, pair.Input[0]);
Assert.AreEqual(11.0, pair.Input[1]);
Assert.AreEqual(13.0, pair.Input[2]);
Assert.AreEqual(14.0, pair.Input[3]);
Assert.AreEqual(16.0, pair.Input[4]);
Assert.AreEqual(17.0, pair.Input[5]);
Assert.AreEqual(19.0, pair.Input[6]);
Assert.AreEqual(20.0, pair.Input[7]);
Assert.AreEqual(22.0, pair.Input[8]);
Assert.AreEqual(23.0, pair.Input[9]);
Assert.AreEqual(27.0, pair.Ideal[0]);
}
[TestMethod]
public void HiLowTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.HighSequence = 8;
temporal.LowSequence = 2;
temporal.Generate();
Assert.AreEqual(10, temporal.InputNeuronCount);
Assert.AreEqual(1, temporal.OutputNeuronCount);
Assert.AreEqual(7, temporal.CalculateActualSetSize());
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
itr.MoveNext();
// set 0
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(7.0, pair.Input[0]);
Assert.AreEqual(8.0, pair.Input[1]);
Assert.AreEqual(10.0, pair.Input[2]);
Assert.AreEqual(11.0, pair.Input[3]);
Assert.AreEqual(13.0, pair.Input[4]);
Assert.AreEqual(14.0, pair.Input[5]);
Assert.AreEqual(16.0, pair.Input[6]);
Assert.AreEqual(17.0, pair.Input[7]);
Assert.AreEqual(19.0, pair.Input[8]);
Assert.AreEqual(20.0, pair.Input[9]);
Assert.AreEqual(24.0, pair.Ideal[0]);
}
[TestMethod]
public void FormatTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.DeltaChange, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.PercentChange, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.Generate();
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
itr.MoveNext();
// set 0
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(3.0, pair.Input[0]);
Assert.AreEqual(1.5, pair.Input[1]);
Assert.AreEqual(3.0, pair.Input[2]);
Assert.AreEqual(0.6, pair.Input[3]);
Assert.AreEqual(3.0, pair.Input[4]);
Assert.AreEqual(0.375, pair.Input[5]);
Assert.AreEqual(3.0, pair.Input[6]);
Assert.AreEqual(0.25, Math.Round(pair.Input[7]*4.0)/4.0);
Assert.AreEqual(3.0, pair.Input[8]);
Assert.AreEqual(0.25, Math.Round(pair.Input[9]*4.0)/4.0);
Assert.AreEqual(18.0, pair.Ideal[0]);
}
[TestMethod]
public void ActivationTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.Raw,
true, false));
temporal.AddDescription(new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.Raw,
true, false));
temporal.AddDescription(new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.Raw,
false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.Generate();
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
// set 0
itr.MoveNext();
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(0.75, Math.Round(pair.Input[0]*4.0)/4.0);
Assert.AreEqual(1.0, Math.Round(pair.Input[1]*4.0)/4.0);
Assert.AreEqual(1.0, Math.Round(pair.Input[2]*4.0)/4.0);
Assert.AreEqual(1.0, Math.Round(pair.Input[3]*4.0)/4.0);
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Diagnostics;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Threading;
using System.Security;
using System.ServiceModel.Configuration;
using System.ServiceModel.Activation;
using System.Xml;
using System.ServiceModel.Diagnostics.Application;
using System.Globalization;
using System.Collections.Generic;
static class TraceUtility
{
const string ActivityIdKey = "ActivityId";
const string AsyncOperationActivityKey = "AsyncOperationActivity";
const string AsyncOperationStartTimeKey = "AsyncOperationStartTime";
static bool shouldPropagateActivity;
static bool shouldPropagateActivityGlobal;
static bool activityTracing;
static bool messageFlowTracing;
static bool messageFlowTracingOnly;
static long messageNumber = 0;
static Func<Action<AsyncCallback, IAsyncResult>> asyncCallbackGenerator;
static SortedList<int, string> traceCodes = new SortedList<int, string>(382)
{
// Administration trace codes (TraceCode.Administration)
{ TraceCode.WmiPut, "WmiPut" },
// Diagnostic trace codes (TraceCode.Diagnostics)
{ TraceCode.AppDomainUnload, "AppDomainUnload" },
{ TraceCode.EventLog, "EventLog" },
{ TraceCode.ThrowingException, "ThrowingException" },
{ TraceCode.TraceHandledException, "TraceHandledException" },
{ TraceCode.UnhandledException, "UnhandledException" },
{ TraceCode.FailedToAddAnActivityIdHeader, "FailedToAddAnActivityIdHeader" },
{ TraceCode.FailedToReadAnActivityIdHeader, "FailedToReadAnActivityIdHeader" },
{ TraceCode.FilterNotMatchedNodeQuotaExceeded, "FilterNotMatchedNodeQuotaExceeded" },
{ TraceCode.MessageCountLimitExceeded, "MessageCountLimitExceeded" },
{ TraceCode.DiagnosticsFailedMessageTrace, "DiagnosticsFailedMessageTrace" },
{ TraceCode.MessageNotLoggedQuotaExceeded, "MessageNotLoggedQuotaExceeded" },
{ TraceCode.TraceTruncatedQuotaExceeded, "TraceTruncatedQuotaExceeded" },
{ TraceCode.ActivityBoundary, "ActivityBoundary" },
// Serialization trace codes (TraceCode.Serialization)
{ TraceCode.ElementIgnored, "" }, // shared by ServiceModel, need to investigate if should put this one in the SM section
// Channels trace codes (TraceCode.Channels)
{ TraceCode.ConnectionAbandoned, "ConnectionAbandoned" },
{ TraceCode.ConnectionPoolCloseException, "ConnectionPoolCloseException" },
{ TraceCode.ConnectionPoolIdleTimeoutReached, "ConnectionPoolIdleTimeoutReached" },
{ TraceCode.ConnectionPoolLeaseTimeoutReached, "ConnectionPoolLeaseTimeoutReached" },
{ TraceCode.ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, "ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached" },
{ TraceCode.ServerMaxPooledConnectionsQuotaReached, "ServerMaxPooledConnectionsQuotaReached" },
{ TraceCode.EndpointListenerClose, "EndpointListenerClose" },
{ TraceCode.EndpointListenerOpen, "EndpointListenerOpen" },
{ TraceCode.HttpResponseReceived, "HttpResponseReceived" },
{ TraceCode.HttpChannelConcurrentReceiveQuotaReached, "HttpChannelConcurrentReceiveQuotaReached" },
{ TraceCode.HttpChannelMessageReceiveFailed, "HttpChannelMessageReceiveFailed" },
{ TraceCode.HttpChannelUnexpectedResponse, "HttpChannelUnexpectedResponse" },
{ TraceCode.HttpChannelRequestAborted, "HttpChannelRequestAborted" },
{ TraceCode.HttpChannelResponseAborted, "HttpChannelResponseAborted" },
{ TraceCode.HttpsClientCertificateInvalid, "HttpsClientCertificateInvalid" },
{ TraceCode.HttpsClientCertificateNotPresent, "HttpsClientCertificateNotPresent" },
{ TraceCode.NamedPipeChannelMessageReceiveFailed, "NamedPipeChannelMessageReceiveFailed" },
{ TraceCode.NamedPipeChannelMessageReceived, "NamedPipeChannelMessageReceived" },
{ TraceCode.MessageReceived, "MessageReceived" },
{ TraceCode.MessageSent, "MessageSent" },
{ TraceCode.RequestChannelReplyReceived, "RequestChannelReplyReceived" },
{ TraceCode.TcpChannelMessageReceiveFailed, "TcpChannelMessageReceiveFailed" },
{ TraceCode.TcpChannelMessageReceived, "TcpChannelMessageReceived" },
{ TraceCode.ConnectToIPEndpoint, "ConnectToIPEndpoint" },
{ TraceCode.SocketConnectionCreate, "SocketConnectionCreate" },
{ TraceCode.SocketConnectionClose, "SocketConnectionClose" },
{ TraceCode.SocketConnectionAbort, "SocketConnectionAbort" },
{ TraceCode.SocketConnectionAbortClose, "SocketConnectionAbortClose" },
{ TraceCode.PipeConnectionAbort, "PipeConnectionAbort" },
{ TraceCode.RequestContextAbort, "RequestContextAbort" },
{ TraceCode.ChannelCreated, "ChannelCreated" },
{ TraceCode.ChannelDisposed, "ChannelDisposed" },
{ TraceCode.ListenerCreated, "ListenerCreated" },
{ TraceCode.ListenerDisposed, "ListenerDisposed" },
{ TraceCode.PrematureDatagramEof, "PrematureDatagramEof" },
{ TraceCode.MaxPendingConnectionsReached, "MaxPendingConnectionsReached" },
{ TraceCode.MaxAcceptedChannelsReached, "MaxAcceptedChannelsReached" },
{ TraceCode.ChannelConnectionDropped, "ChannelConnectionDropped" },
{ TraceCode.HttpAuthFailed, "HttpAuthFailed" },
{ TraceCode.NoExistingTransportManager, "NoExistingTransportManager" },
{ TraceCode.IncompatibleExistingTransportManager, "IncompatibleExistingTransportManager" },
{ TraceCode.InitiatingNamedPipeConnection, "InitiatingNamedPipeConnection" },
{ TraceCode.InitiatingTcpConnection, "InitiatingTcpConnection" },
{ TraceCode.OpenedListener, "OpenedListener" },
{ TraceCode.SslClientCertMissing, "SslClientCertMissing" },
{ TraceCode.StreamSecurityUpgradeAccepted, "StreamSecurityUpgradeAccepted" },
{ TraceCode.TcpConnectError, "TcpConnectError" },
{ TraceCode.FailedAcceptFromPool, "FailedAcceptFromPool" },
{ TraceCode.FailedPipeConnect, "FailedPipeConnect" },
{ TraceCode.SystemTimeResolution, "SystemTimeResolution" },
{ TraceCode.PeerNeighborCloseFailed, "PeerNeighborCloseFailed" },
{ TraceCode.PeerNeighborClosingFailed, "PeerNeighborClosingFailed" },
{ TraceCode.PeerNeighborNotAccepted, "PeerNeighborNotAccepted" },
{ TraceCode.PeerNeighborNotFound, "PeerNeighborNotFound" },
{ TraceCode.PeerNeighborOpenFailed, "PeerNeighborOpenFailed" },
{ TraceCode.PeerNeighborStateChanged, "PeerNeighborStateChanged" },
{ TraceCode.PeerNeighborStateChangeFailed, "PeerNeighborStateChangeFailed" },
{ TraceCode.PeerNeighborMessageReceived, "PeerNeighborMessageReceived" },
{ TraceCode.PeerNeighborManagerOffline, "PeerNeighborManagerOffline" },
{ TraceCode.PeerNeighborManagerOnline, "PeerNeighborManagerOnline" },
{ TraceCode.PeerChannelMessageReceived, "PeerChannelMessageReceived" },
{ TraceCode.PeerChannelMessageSent, "PeerChannelMessageSent" },
{ TraceCode.PeerNodeAddressChanged, "PeerNodeAddressChanged" },
{ TraceCode.PeerNodeOpening, "PeerNodeOpening" },
{ TraceCode.PeerNodeOpened, "PeerNodeOpened" },
{ TraceCode.PeerNodeOpenFailed, "PeerNodeOpenFailed" },
{ TraceCode.PeerNodeClosing, "PeerNodeClosing" },
{ TraceCode.PeerNodeClosed, "PeerNodeClosed" },
{ TraceCode.PeerFloodedMessageReceived, "PeerFloodedMessageReceived" },
{ TraceCode.PeerFloodedMessageNotPropagated, "PeerFloodedMessageNotPropagated" },
{ TraceCode.PeerFloodedMessageNotMatched, "PeerFloodedMessageNotMatched" },
{ TraceCode.PnrpRegisteredAddresses, "PnrpRegisteredAddresses" },
{ TraceCode.PnrpUnregisteredAddresses, "PnrpUnregisteredAddresses" },
{ TraceCode.PnrpResolvedAddresses, "PnrpResolvedAddresses" },
{ TraceCode.PnrpResolveException, "PnrpResolveException" },
{ TraceCode.PeerReceiveMessageAuthenticationFailure, "PeerReceiveMessageAuthenticationFailure" },
{ TraceCode.PeerNodeAuthenticationFailure, "PeerNodeAuthenticationFailure" },
{ TraceCode.PeerNodeAuthenticationTimeout, "PeerNodeAuthenticationTimeout" },
{ TraceCode.PeerFlooderReceiveMessageQuotaExceeded, "PeerFlooderReceiveMessageQuotaExceeded" },
{ TraceCode.PeerServiceOpened, "PeerServiceOpened" },
{ TraceCode.PeerMaintainerActivity, "PeerMaintainerActivity" },
{ TraceCode.MsmqCannotPeekOnQueue, "MsmqCannotPeekOnQueue" },
{ TraceCode.MsmqCannotReadQueues, "MsmqCannotReadQueues" },
{ TraceCode.MsmqDatagramSent, "MsmqDatagramSent" },
{ TraceCode.MsmqDatagramReceived, "MsmqDatagramReceived" },
{ TraceCode.MsmqDetected, "MsmqDetected" },
{ TraceCode.MsmqEnteredBatch, "MsmqEnteredBatch" },
{ TraceCode.MsmqExpectedException, "MsmqExpectedException" },
{ TraceCode.MsmqFoundBaseAddress, "MsmqFoundBaseAddress" },
{ TraceCode.MsmqLeftBatch, "MsmqLeftBatch" },
{ TraceCode.MsmqMatchedApplicationFound, "MsmqMatchedApplicationFound" },
{ TraceCode.MsmqMessageDropped, "MsmqMessageDropped" },
{ TraceCode.MsmqMessageLockedUnderTheTransaction, "MsmqMessageLockedUnderTheTransaction" },
{ TraceCode.MsmqMessageRejected, "MsmqMessageRejected" },
{ TraceCode.MsmqMoveOrDeleteAttemptFailed, "MsmqMoveOrDeleteAttemptFailed" },
{ TraceCode.MsmqPoisonMessageMovedPoison, "MsmqPoisonMessageMovedPoison" },
{ TraceCode.MsmqPoisonMessageMovedRetry, "MsmqPoisonMessageMovedRetry" },
{ TraceCode.MsmqPoisonMessageRejected, "MsmqPoisonMessageRejected" },
{ TraceCode.MsmqPoolFull, "MsmqPoolFull" },
{ TraceCode.MsmqPotentiallyPoisonMessageDetected, "MsmqPotentiallyPoisonMessageDetected" },
{ TraceCode.MsmqQueueClosed, "MsmqQueueClosed" },
{ TraceCode.MsmqQueueOpened, "MsmqQueueOpened" },
{ TraceCode.MsmqQueueTransactionalStatusUnknown, "MsmqQueueTransactionalStatusUnknown" },
{ TraceCode.MsmqScanStarted, "MsmqScanStarted" },
{ TraceCode.MsmqSessiongramReceived, "MsmqSessiongramReceived" },
{ TraceCode.MsmqSessiongramSent, "MsmqSessiongramSent" },
{ TraceCode.MsmqStartingApplication, "MsmqStartingApplication" },
{ TraceCode.MsmqStartingService, "MsmqStartingService" },
{ TraceCode.MsmqUnexpectedAcknowledgment, "MsmqUnexpectedAcknowledgment" },
{ TraceCode.WsrmNegativeElapsedTimeDetected, "WsrmNegativeElapsedTimeDetected" },
{ TraceCode.TcpTransferError, "TcpTransferError" },
{ TraceCode.TcpConnectionResetError, "TcpConnectionResetError" },
{ TraceCode.TcpConnectionTimedOut, "TcpConnectionTimedOut" },
// ComIntegration trace codes (TraceCode.ComIntegration)
{ TraceCode.ComIntegrationServiceHostStartingService, "ComIntegrationServiceHostStartingService" },
{ TraceCode.ComIntegrationServiceHostStartedService, "ComIntegrationServiceHostStartedService" },
{ TraceCode.ComIntegrationServiceHostCreatedServiceContract, "ComIntegrationServiceHostCreatedServiceContract" },
{ TraceCode.ComIntegrationServiceHostStartedServiceDetails, "ComIntegrationServiceHostStartedServiceDetails" },
{ TraceCode.ComIntegrationServiceHostCreatedServiceEndpoint, "ComIntegrationServiceHostCreatedServiceEndpoint" },
{ TraceCode.ComIntegrationServiceHostStoppingService, "ComIntegrationServiceHostStoppingService" },
{ TraceCode.ComIntegrationServiceHostStoppedService, "ComIntegrationServiceHostStoppedService" },
{ TraceCode.ComIntegrationDllHostInitializerStarting, "ComIntegrationDllHostInitializerStarting" },
{ TraceCode.ComIntegrationDllHostInitializerAddingHost, "ComIntegrationDllHostInitializerAddingHost" },
{ TraceCode.ComIntegrationDllHostInitializerStarted, "ComIntegrationDllHostInitializerStarted" },
{ TraceCode.ComIntegrationDllHostInitializerStopping, "ComIntegrationDllHostInitializerStopping" },
{ TraceCode.ComIntegrationDllHostInitializerStopped, "ComIntegrationDllHostInitializerStopped" },
{ TraceCode.ComIntegrationTLBImportStarting, "ComIntegrationTLBImportStarting" },
{ TraceCode.ComIntegrationTLBImportFromAssembly, "ComIntegrationTLBImportFromAssembly" },
{ TraceCode.ComIntegrationTLBImportFromTypelib, "ComIntegrationTLBImportFromTypelib" },
{ TraceCode.ComIntegrationTLBImportConverterEvent, "ComIntegrationTLBImportConverterEvent" },
{ TraceCode.ComIntegrationTLBImportFinished, "ComIntegrationTLBImportFinished" },
{ TraceCode.ComIntegrationInstanceCreationRequest, "ComIntegrationInstanceCreationRequest" },
{ TraceCode.ComIntegrationInstanceCreationSuccess, "ComIntegrationInstanceCreationSuccess" },
{ TraceCode.ComIntegrationInstanceReleased, "ComIntegrationInstanceReleased" },
{ TraceCode.ComIntegrationEnteringActivity, "ComIntegrationEnteringActivity" },
{ TraceCode.ComIntegrationExecutingCall, "ComIntegrationExecutingCall" },
{ TraceCode.ComIntegrationLeftActivity, "ComIntegrationLeftActivity" },
{ TraceCode.ComIntegrationInvokingMethod, "ComIntegrationInvokingMethod" },
{ TraceCode.ComIntegrationInvokedMethod, "ComIntegrationInvokedMethod" },
{ TraceCode.ComIntegrationInvokingMethodNewTransaction, "ComIntegrationInvokingMethodNewTransaction" },
{ TraceCode.ComIntegrationInvokingMethodContextTransaction, "ComIntegrationInvokingMethodContextTransaction" },
{ TraceCode.ComIntegrationServiceMonikerParsed, "ComIntegrationServiceMonikerParsed" },
{ TraceCode.ComIntegrationWsdlChannelBuilderLoaded, "ComIntegrationWsdlChannelBuilderLoaded" },
{ TraceCode.ComIntegrationTypedChannelBuilderLoaded, "ComIntegrationTypedChannelBuilderLoaded" },
{ TraceCode.ComIntegrationChannelCreated, "ComIntegrationChannelCreated" },
{ TraceCode.ComIntegrationDispatchMethod, "ComIntegrationDispatchMethod" },
{ TraceCode.ComIntegrationTxProxyTxCommitted, "ComIntegrationTxProxyTxCommitted" },
{ TraceCode.ComIntegrationTxProxyTxAbortedByContext, "ComIntegrationTxProxyTxAbortedByContext" },
{ TraceCode.ComIntegrationTxProxyTxAbortedByTM, "ComIntegrationTxProxyTxAbortedByTM" },
{ TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, "ComIntegrationMexMonikerMetadataExchangeComplete" },
{ TraceCode.ComIntegrationMexChannelBuilderLoaded, "ComIntegrationMexChannelBuilderLoaded" },
// Security trace codes (TraceCode.Security)
{ TraceCode.Security, "Security" },
{ TraceCode.SecurityIdentityVerificationSuccess, "SecurityIdentityVerificationSuccess" },
{ TraceCode.SecurityIdentityVerificationFailure, "SecurityIdentityVerificationFailure" },
{ TraceCode.SecurityIdentityDeterminationSuccess, "SecurityIdentityDeterminationSuccess" },
{ TraceCode.SecurityIdentityDeterminationFailure, "SecurityIdentityDeterminationFailure" },
{ TraceCode.SecurityIdentityHostNameNormalizationFailure, "SecurityIdentityHostNameNormalizationFailure" },
{ TraceCode.SecurityImpersonationSuccess, "SecurityImpersonationSuccess" },
{ TraceCode.SecurityImpersonationFailure, "SecurityImpersonationFailure" },
{ TraceCode.SecurityNegotiationProcessingFailure, "SecurityNegotiationProcessingFailure" },
{ TraceCode.IssuanceTokenProviderRemovedCachedToken, "IssuanceTokenProviderRemovedCachedToken" },
{ TraceCode.IssuanceTokenProviderUsingCachedToken, "IssuanceTokenProviderUsingCachedToken" },
{ TraceCode.IssuanceTokenProviderBeginSecurityNegotiation, "IssuanceTokenProviderBeginSecurityNegotiation" },
{ TraceCode.IssuanceTokenProviderEndSecurityNegotiation, "IssuanceTokenProviderEndSecurityNegotiation" },
{ TraceCode.IssuanceTokenProviderRedirectApplied, "IssuanceTokenProviderRedirectApplied" },
{ TraceCode.IssuanceTokenProviderServiceTokenCacheFull, "IssuanceTokenProviderServiceTokenCacheFull" },
{ TraceCode.NegotiationTokenProviderAttached, "NegotiationTokenProviderAttached" },
{ TraceCode.SpnegoClientNegotiationCompleted, "SpnegoClientNegotiationCompleted" },
{ TraceCode.SpnegoServiceNegotiationCompleted, "SpnegoServiceNegotiationCompleted" },
{ TraceCode.SpnegoClientNegotiation, "SpnegoClientNegotiation" },
{ TraceCode.SpnegoServiceNegotiation, "SpnegoServiceNegotiation" },
{ TraceCode.NegotiationAuthenticatorAttached, "NegotiationAuthenticatorAttached" },
{ TraceCode.ServiceSecurityNegotiationCompleted, "ServiceSecurityNegotiationCompleted" },
{ TraceCode.SecurityContextTokenCacheFull, "SecurityContextTokenCacheFull" },
{ TraceCode.ExportSecurityChannelBindingEntry, "ExportSecurityChannelBindingEntry" },
{ TraceCode.ExportSecurityChannelBindingExit, "ExportSecurityChannelBindingExit" },
{ TraceCode.ImportSecurityChannelBindingEntry, "ImportSecurityChannelBindingEntry" },
{ TraceCode.ImportSecurityChannelBindingExit, "ImportSecurityChannelBindingExit" },
{ TraceCode.SecurityTokenProviderOpened, "SecurityTokenProviderOpened" },
{ TraceCode.SecurityTokenProviderClosed, "SecurityTokenProviderClosed" },
{ TraceCode.SecurityTokenAuthenticatorOpened, "SecurityTokenAuthenticatorOpened" },
{ TraceCode.SecurityTokenAuthenticatorClosed, "SecurityTokenAuthenticatorClosed" },
{ TraceCode.SecurityBindingOutgoingMessageSecured, "SecurityBindingOutgoingMessageSecured" },
{ TraceCode.SecurityBindingIncomingMessageVerified, "SecurityBindingIncomingMessageVerified" },
{ TraceCode.SecurityBindingSecureOutgoingMessageFailure, "SecurityBindingSecureOutgoingMessageFailure" },
{ TraceCode.SecurityBindingVerifyIncomingMessageFailure, "SecurityBindingVerifyIncomingMessageFailure" },
{ TraceCode.SecuritySpnToSidMappingFailure, "SecuritySpnToSidMappingFailure" },
{ TraceCode.SecuritySessionRedirectApplied, "SecuritySessionRedirectApplied" },
{ TraceCode.SecurityClientSessionCloseSent, "SecurityClientSessionCloseSent" },
{ TraceCode.SecurityClientSessionCloseResponseSent, "SecurityClientSessionCloseResponseSent" },
{ TraceCode.SecurityClientSessionCloseMessageReceived, "SecurityClientSessionCloseMessageReceived" },
{ TraceCode.SecuritySessionKeyRenewalFaultReceived, "SecuritySessionKeyRenewalFaultReceived" },
{ TraceCode.SecuritySessionAbortedFaultReceived, "SecuritySessionAbortedFaultReceived" },
{ TraceCode.SecuritySessionClosedResponseReceived, "SecuritySessionClosedResponseReceived" },
{ TraceCode.SecurityClientSessionPreviousKeyDiscarded, "SecurityClientSessionPreviousKeyDiscarded" },
{ TraceCode.SecurityClientSessionKeyRenewed, "SecurityClientSessionKeyRenewed" },
{ TraceCode.SecurityPendingServerSessionAdded, "SecurityPendingServerSessionAdded" },
{ TraceCode.SecurityPendingServerSessionClosed, "SecurityPendingServerSessionClosed" },
{ TraceCode.SecurityPendingServerSessionActivated, "SecurityPendingServerSessionActivated" },
{ TraceCode.SecurityActiveServerSessionRemoved, "SecurityActiveServerSessionRemoved" },
{ TraceCode.SecurityNewServerSessionKeyIssued, "SecurityNewServerSessionKeyIssued" },
{ TraceCode.SecurityInactiveSessionFaulted, "SecurityInactiveSessionFaulted" },
{ TraceCode.SecurityServerSessionKeyUpdated, "SecurityServerSessionKeyUpdated" },
{ TraceCode.SecurityServerSessionCloseReceived, "SecurityServerSessionCloseReceived" },
{ TraceCode.SecurityServerSessionRenewalFaultSent, "SecurityServerSessionRenewalFaultSent" },
{ TraceCode.SecurityServerSessionAbortedFaultSent, "SecurityServerSessionAbortedFaultSent" },
{ TraceCode.SecuritySessionCloseResponseSent, "SecuritySessionCloseResponseSent" },
{ TraceCode.SecuritySessionServerCloseSent, "SecuritySessionServerCloseSent" },
{ TraceCode.SecurityServerSessionCloseResponseReceived, "SecurityServerSessionCloseResponseReceived" },
{ TraceCode.SecuritySessionRenewFaultSendFailure, "SecuritySessionRenewFaultSendFailure" },
{ TraceCode.SecuritySessionAbortedFaultSendFailure, "SecuritySessionAbortedFaultSendFailure" },
{ TraceCode.SecuritySessionClosedResponseSendFailure, "SecuritySessionClosedResponseSendFailure" },
{ TraceCode.SecuritySessionServerCloseSendFailure, "SecuritySessionServerCloseSendFailure" },
{ TraceCode.SecuritySessionRequestorStartOperation, "SecuritySessionRequestorStartOperation" },
{ TraceCode.SecuritySessionRequestorOperationSuccess, "SecuritySessionRequestorOperationSuccess" },
{ TraceCode.SecuritySessionRequestorOperationFailure, "SecuritySessionRequestorOperationFailure" },
{ TraceCode.SecuritySessionResponderOperationFailure, "SecuritySessionResponderOperationFailure" },
{ TraceCode.SecuritySessionDemuxFailure, "SecuritySessionDemuxFailure" },
{ TraceCode.SecurityAuditWrittenSuccess, "SecurityAuditWrittenSuccess" },
{ TraceCode.SecurityAuditWrittenFailure, "SecurityAuditWrittenFailure" },
// ServiceModel trace codes (TraceCode.ServiceModel)
{ TraceCode.AsyncCallbackThrewException, "AsyncCallbackThrewException" },
{ TraceCode.CommunicationObjectAborted, "CommunicationObjectAborted" },
{ TraceCode.CommunicationObjectAbortFailed, "CommunicationObjectAbortFailed" },
{ TraceCode.CommunicationObjectCloseFailed, "CommunicationObjectCloseFailed" },
{ TraceCode.CommunicationObjectOpenFailed, "CommunicationObjectOpenFailed" },
{ TraceCode.CommunicationObjectClosing, "CommunicationObjectClosing" },
{ TraceCode.CommunicationObjectClosed, "CommunicationObjectClosed" },
{ TraceCode.CommunicationObjectCreated, "CommunicationObjectCreated" },
{ TraceCode.CommunicationObjectDisposing, "CommunicationObjectDisposing" },
{ TraceCode.CommunicationObjectFaultReason, "CommunicationObjectFaultReason" },
{ TraceCode.CommunicationObjectFaulted, "CommunicationObjectFaulted" },
{ TraceCode.CommunicationObjectOpening, "CommunicationObjectOpening" },
{ TraceCode.CommunicationObjectOpened, "CommunicationObjectOpened" },
{ TraceCode.DidNotUnderstandMessageHeader, "DidNotUnderstandMessageHeader" },
{ TraceCode.UnderstoodMessageHeader, "UnderstoodMessageHeader" },
{ TraceCode.MessageClosed, "MessageClosed" },
{ TraceCode.MessageClosedAgain, "MessageClosedAgain" },
{ TraceCode.MessageCopied, "MessageCopied" },
{ TraceCode.MessageRead, "MessageRead" },
{ TraceCode.MessageWritten, "MessageWritten" },
{ TraceCode.BeginExecuteMethod, "BeginExecuteMethod" },
{ TraceCode.ConfigurationIsReadOnly, "ConfigurationIsReadOnly" },
{ TraceCode.ConfiguredExtensionTypeNotFound, "ConfiguredExtensionTypeNotFound" },
{ TraceCode.EvaluationContextNotFound, "EvaluationContextNotFound" },
{ TraceCode.EndExecuteMethod, "EndExecuteMethod" },
{ TraceCode.ExtensionCollectionDoesNotExist, "ExtensionCollectionDoesNotExist" },
{ TraceCode.ExtensionCollectionNameNotFound, "ExtensionCollectionNameNotFound" },
{ TraceCode.ExtensionCollectionIsEmpty, "ExtensionCollectionIsEmpty" },
{ TraceCode.ExtensionElementAlreadyExistsInCollection, "ExtensionElementAlreadyExistsInCollection" },
{ TraceCode.ElementTypeDoesntMatchConfiguredType, "ElementTypeDoesntMatchConfiguredType" },
{ TraceCode.ErrorInvokingUserCode, "ErrorInvokingUserCode" },
{ TraceCode.GetBehaviorElement, "GetBehaviorElement" },
{ TraceCode.GetCommonBehaviors, "GetCommonBehaviors" },
{ TraceCode.GetConfiguredBinding, "GetConfiguredBinding" },
{ TraceCode.GetChannelEndpointElement, "GetChannelEndpointElement" },
{ TraceCode.GetConfigurationSection, "GetConfigurationSection" },
{ TraceCode.GetDefaultConfiguredBinding, "GetDefaultConfiguredBinding" },
{ TraceCode.GetServiceElement, "GetServiceElement" },
{ TraceCode.MessageProcessingPaused, "MessageProcessingPaused" },
{ TraceCode.ManualFlowThrottleLimitReached, "ManualFlowThrottleLimitReached" },
{ TraceCode.OverridingDuplicateConfigurationKey, "OverridingDuplicateConfigurationKey" },
{ TraceCode.RemoveBehavior, "RemoveBehavior" },
{ TraceCode.ServiceChannelLifetime, "ServiceChannelLifetime" },
{ TraceCode.ServiceHostCreation, "ServiceHostCreation" },
{ TraceCode.ServiceHostBaseAddresses, "ServiceHostBaseAddresses" },
{ TraceCode.ServiceHostTimeoutOnClose, "ServiceHostTimeoutOnClose" },
{ TraceCode.ServiceHostFaulted, "ServiceHostFaulted" },
{ TraceCode.ServiceHostErrorOnReleasePerformanceCounter, "ServiceHostErrorOnReleasePerformanceCounter" },
{ TraceCode.ServiceThrottleLimitReached, "ServiceThrottleLimitReached" },
{ TraceCode.ServiceOperationMissingReply, "ServiceOperationMissingReply" },
{ TraceCode.ServiceOperationMissingReplyContext, "ServiceOperationMissingReplyContext" },
{ TraceCode.ServiceOperationExceptionOnReply, "ServiceOperationExceptionOnReply" },
{ TraceCode.SkipBehavior, "SkipBehavior" },
{ TraceCode.TransportListen, "TransportListen" },
{ TraceCode.UnhandledAction, "UnhandledAction" },
{ TraceCode.PerformanceCounterFailedToLoad, "PerformanceCounterFailedToLoad" },
{ TraceCode.PerformanceCountersFailed, "PerformanceCountersFailed" },
{ TraceCode.PerformanceCountersFailedDuringUpdate, "PerformanceCountersFailedDuringUpdate" },
{ TraceCode.PerformanceCountersFailedForService, "PerformanceCountersFailedForService" },
{ TraceCode.PerformanceCountersFailedOnRelease, "PerformanceCountersFailedOnRelease" },
{ TraceCode.WsmexNonCriticalWsdlExportError, "WsmexNonCriticalWsdlExportError" },
{ TraceCode.WsmexNonCriticalWsdlImportError, "WsmexNonCriticalWsdlImportError" },
{ TraceCode.FailedToOpenIncomingChannel, "FailedToOpenIncomingChannel" },
{ TraceCode.UnhandledExceptionInUserOperation, "UnhandledExceptionInUserOperation" },
{ TraceCode.DroppedAMessage, "DroppedAMessage" },
{ TraceCode.CannotBeImportedInCurrentFormat, "CannotBeImportedInCurrentFormat" },
{ TraceCode.GetConfiguredEndpoint, "GetConfiguredEndpoint" },
{ TraceCode.GetDefaultConfiguredEndpoint, "GetDefaultConfiguredEndpoint" },
{ TraceCode.ExtensionTypeNotFound, "ExtensionTypeNotFound" },
{ TraceCode.DefaultEndpointsAdded, "DefaultEndpointsAdded" },
//ServiceModel Metadata codes
{ TraceCode.MetadataExchangeClientSendRequest, "MetadataExchangeClientSendRequest" },
{ TraceCode.MetadataExchangeClientReceiveReply, "MetadataExchangeClientReceiveReply" },
{ TraceCode.WarnHelpPageEnabledNoBaseAddress, "WarnHelpPageEnabledNoBaseAddress" },
// PortSharingtrace codes (TraceCode.PortSharing)
{ TraceCode.PortSharingClosed, "PortSharingClosed" },
{ TraceCode.PortSharingDuplicatedPipe, "PortSharingDuplicatedPipe" },
{ TraceCode.PortSharingDupHandleGranted, "PortSharingDupHandleGranted" },
{ TraceCode.PortSharingDuplicatedSocket, "PortSharingDuplicatedSocket" },
{ TraceCode.PortSharingListening, "PortSharingListening" },
{ TraceCode.SharedManagerServiceEndpointNotExist, "SharedManagerServiceEndpointNotExist" },
//Indigo Tx trace codes (TraceCode.ServiceModelTransaction)
{ TraceCode.TxSourceTxScopeRequiredIsTransactedTransport, "TxSourceTxScopeRequiredIsTransactedTransport" },
{ TraceCode.TxSourceTxScopeRequiredIsTransactionFlow, "TxSourceTxScopeRequiredIsTransactionFlow" },
{ TraceCode.TxSourceTxScopeRequiredIsAttachedTransaction, "TxSourceTxScopeRequiredIsAttachedTransaction" },
{ TraceCode.TxSourceTxScopeRequiredIsCreateNewTransaction, "TxSourceTxScopeRequiredIsCreateNewTransaction" },
{ TraceCode.TxCompletionStatusCompletedForAutocomplete, "TxCompletionStatusCompletedForAutocomplete" },
{ TraceCode.TxCompletionStatusCompletedForError, "TxCompletionStatusCompletedForError" },
{ TraceCode.TxCompletionStatusCompletedForSetComplete, "TxCompletionStatusCompletedForSetComplete" },
{ TraceCode.TxCompletionStatusCompletedForTACOSC, "TxCompletionStatusCompletedForTACOSC" },
{ TraceCode.TxCompletionStatusCompletedForAsyncAbort, "TxCompletionStatusCompletedForAsyncAbort" },
{ TraceCode.TxCompletionStatusRemainsAttached, "TxCompletionStatusRemainsAttached" },
{ TraceCode.TxCompletionStatusAbortedOnSessionClose, "TxCompletionStatusAbortedOnSessionClose" },
{ TraceCode.TxReleaseServiceInstanceOnCompletion, "TxReleaseServiceInstanceOnCompletion" },
{ TraceCode.TxAsyncAbort, "TxAsyncAbort" },
{ TraceCode.TxFailedToNegotiateOleTx, "TxFailedToNegotiateOleTx" },
{ TraceCode.TxSourceTxScopeRequiredUsingExistingTransaction, "TxSourceTxScopeRequiredUsingExistingTransaction" },
//CfxGreen trace codes (TraceCode.NetFx35)
{ TraceCode.ActivatingMessageReceived, "ActivatingMessageReceived" },
{ TraceCode.InstanceContextBoundToDurableInstance, "InstanceContextBoundToDurableInstance" },
{ TraceCode.InstanceContextDetachedFromDurableInstance, "InstanceContextDetachedFromDurableInstance" },
{ TraceCode.ContextChannelFactoryChannelCreated, "ContextChannelFactoryChannelCreated" },
{ TraceCode.ContextChannelListenerChannelAccepted, "ContextChannelListenerChannelAccepted" },
{ TraceCode.ContextProtocolContextAddedToMessage, "ContextProtocolContextAddedToMessage" },
{ TraceCode.ContextProtocolContextRetrievedFromMessage, "ContextProtocolContextRetrievedFromMessage" },
{ TraceCode.DICPInstanceContextCached, "DICPInstanceContextCached" },
{ TraceCode.DICPInstanceContextRemovedFromCache, "DICPInstanceContextRemovedFromCache" },
{ TraceCode.ServiceDurableInstanceDeleted, "ServiceDurableInstanceDeleted" },
{ TraceCode.ServiceDurableInstanceDisposed, "ServiceDurableInstanceDisposed" },
{ TraceCode.ServiceDurableInstanceLoaded, "ServiceDurableInstanceLoaded" },
{ TraceCode.ServiceDurableInstanceSaved, "ServiceDurableInstanceSaved" },
{ TraceCode.SqlPersistenceProviderSQLCallStart, "SqlPersistenceProviderSQLCallStart" },
{ TraceCode.SqlPersistenceProviderSQLCallEnd, "SqlPersistenceProviderSQLCallEnd" },
{ TraceCode.SqlPersistenceProviderOpenParameters, "SqlPersistenceProviderOpenParameters" },
{ TraceCode.SyncContextSchedulerServiceTimerCancelled, "SyncContextSchedulerServiceTimerCancelled" },
{ TraceCode.SyncContextSchedulerServiceTimerCreated, "SyncContextSchedulerServiceTimerCreated" },
{ TraceCode.WorkflowDurableInstanceLoaded, "WorkflowDurableInstanceLoaded" },
{ TraceCode.WorkflowDurableInstanceAborted, "WorkflowDurableInstanceAborted" },
{ TraceCode.WorkflowDurableInstanceActivated, "WorkflowDurableInstanceActivated" },
{ TraceCode.WorkflowOperationInvokerItemQueued, "WorkflowOperationInvokerItemQueued" },
{ TraceCode.WorkflowRequestContextReplySent, "WorkflowRequestContextReplySent" },
{ TraceCode.WorkflowRequestContextFaultSent, "WorkflowRequestContextFaultSent" },
{ TraceCode.WorkflowServiceHostCreated, "WorkflowServiceHostCreated" },
{ TraceCode.SyndicationReadFeedBegin, "SyndicationReadFeedBegin" },
{ TraceCode.SyndicationReadFeedEnd, "SyndicationReadFeedEnd" },
{ TraceCode.SyndicationReadItemBegin, "SyndicationReadItemBegin" },
{ TraceCode.SyndicationReadItemEnd, "SyndicationReadItemEnd" },
{ TraceCode.SyndicationWriteFeedBegin, "SyndicationWriteFeedBegin" },
{ TraceCode.SyndicationWriteFeedEnd, "SyndicationWriteFeedEnd" },
{ TraceCode.SyndicationWriteItemBegin, "SyndicationWriteItemBegin" },
{ TraceCode.SyndicationWriteItemEnd, "SyndicationWriteItemEnd" },
{ TraceCode.SyndicationProtocolElementIgnoredOnRead, "SyndicationProtocolElementIgnoredOnRead" },
{ TraceCode.SyndicationProtocolElementIgnoredOnWrite, "SyndicationProtocolElementIgnoredOnWrite" },
{ TraceCode.SyndicationProtocolElementInvalid, "SyndicationProtocolElementInvalid" },
{ TraceCode.WebUnknownQueryParameterIgnored, "WebUnknownQueryParameterIgnored" },
{ TraceCode.WebRequestMatchesOperation, "WebRequestMatchesOperation" },
{ TraceCode.WebRequestDoesNotMatchOperations, "WebRequestDoesNotMatchOperations" },
{ TraceCode.WebRequestRedirect, "WebRequestRedirect" },
{ TraceCode.SyndicationReadServiceDocumentBegin, "SyndicationReadServiceDocumentBegin" },
{ TraceCode.SyndicationReadServiceDocumentEnd, "SyndicationReadServiceDocumentEnd" },
{ TraceCode.SyndicationReadCategoriesDocumentBegin, "SyndicationReadCategoriesDocumentBegin" },
{ TraceCode.SyndicationReadCategoriesDocumentEnd, "SyndicationReadCategoriesDocumentEnd" },
{ TraceCode.SyndicationWriteServiceDocumentBegin, "SyndicationWriteServiceDocumentBegin" },
{ TraceCode.SyndicationWriteServiceDocumentEnd, "SyndicationWriteServiceDocumentEnd" },
{ TraceCode.SyndicationWriteCategoriesDocumentBegin, "SyndicationWriteCategoriesDocumentBegin" },
{ TraceCode.SyndicationWriteCategoriesDocumentEnd, "SyndicationWriteCategoriesDocumentEnd" },
{ TraceCode.AutomaticFormatSelectedOperationDefault, "AutomaticFormatSelectedOperationDefault" },
{ TraceCode.AutomaticFormatSelectedRequestBased, "AutomaticFormatSelectedRequestBased" },
{ TraceCode.RequestFormatSelectedFromContentTypeMapper, "RequestFormatSelectedFromContentTypeMapper" },
{ TraceCode.RequestFormatSelectedByEncoderDefaults, "RequestFormatSelectedByEncoderDefaults" },
{ TraceCode.AddingResponseToOutputCache, "AddingResponseToOutputCache" },
{ TraceCode.AddingAuthenticatedResponseToOutputCache, "AddingAuthenticatedResponseToOutputCache" },
{ TraceCode.JsonpCallbackNameSet, "JsonpCallbackNameSet" },
};
public const string E2EActivityId = "E2EActivityId";
public const string TraceApplicationReference = "TraceApplicationReference";
public static InputQueue<T> CreateInputQueue<T>() where T : class
{
if (asyncCallbackGenerator == null)
{
asyncCallbackGenerator = new Func<Action<AsyncCallback, IAsyncResult>>(CallbackGenerator);
}
return new InputQueue<T>(asyncCallbackGenerator)
{
DisposeItemCallback = value =>
{
if (value is ICommunicationObject)
{
((ICommunicationObject)value).Abort();
}
}
};
}
static Action<AsyncCallback, IAsyncResult> CallbackGenerator()
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity callbackActivity = ServiceModelActivity.Current;
if (callbackActivity != null)
{
return delegate(AsyncCallback callback, IAsyncResult result)
{
using (ServiceModelActivity.BoundOperation(callbackActivity))
{
callback(result);
}
};
}
}
return null;
}
static internal void AddActivityHeader(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message));
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToAddAnActivityIdHeader,
SR.GetString(SR.TraceCodeFailedToAddAnActivityIdHeader), e, message);
}
}
static internal void AddAmbientActivityToMessage(Message message)
{
try
{
ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTraceBase.ActivityId);
activityIdHeader.AddTo(message);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToAddAnActivityIdHeader,
SR.GetString(SR.TraceCodeFailedToAddAnActivityIdHeader), e, message);
}
}
static internal void CopyActivity(Message source, Message destination)
{
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source));
}
}
internal static long GetUtcBasedDurationForTrace(long startTicks)
{
if (startTicks > 0)
{
TimeSpan elapsedTime = new TimeSpan(DateTime.UtcNow.Ticks - startTicks);
return (long)elapsedTime.TotalMilliseconds;
}
return 0;
}
internal static ServiceModelActivity ExtractActivity(Message message)
{
ServiceModelActivity retval = null;
if ((DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivityGlobal) &&
(message != null) &&
(message.State != MessageState.Closed))
{
object property;
if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property))
{
retval = property as ServiceModelActivity;
}
}
return retval;
}
internal static ServiceModelActivity ExtractActivity(RequestContext request)
{
try
{
return TraceUtility.ExtractActivity(request.RequestMessage);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
return null;
}
internal static Guid ExtractActivityId(Message message)
{
if (TraceUtility.MessageFlowTracingOnly)
{
return ActivityIdHeader.ExtractActivityId(message);
}
ServiceModelActivity activity = ExtractActivity(message);
return activity == null ? Guid.Empty : activity.Id;
}
internal static Guid GetReceivedActivityId(OperationContext operationContext)
{
object activityIdFromProprties;
if (!operationContext.IncomingMessageProperties.TryGetValue(E2EActivityId, out activityIdFromProprties))
{
return TraceUtility.ExtractActivityId(operationContext.IncomingMessage);
}
else
{
return (Guid)activityIdFromProprties;
}
}
internal static ServiceModelActivity ExtractAndRemoveActivity(Message message)
{
ServiceModelActivity retval = TraceUtility.ExtractActivity(message);
if (retval != null)
{
// If the property is just removed, the item is disposed and we don't want the thing
// to be disposed of.
message.Properties[TraceUtility.ActivityIdKey] = false;
}
return retval;
}
internal static void ProcessIncomingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (activity != null && DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message);
if (null != incomingActivity && incomingActivity.Id != activity.Id)
{
using (ServiceModelActivity.BoundOperation(incomingActivity))
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(activity.Id);
}
}
}
TraceUtility.SetActivity(message, activity);
}
TraceUtility.MessageFlowAtMessageReceived(message, null, eventTraceActivity, true);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance);
}
}
internal static void ProcessOutgoingMessage(Message message, EventTraceActivity eventTraceActivity)
{
ServiceModelActivity activity = ServiceModelActivity.Current;
if (DiagnosticUtility.ShouldUseActivity)
{
TraceUtility.SetActivity(message, activity);
}
if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
{
TraceUtility.AddAmbientActivityToMessage(message);
}
TraceUtility.MessageFlowAtMessageSent(message, eventTraceActivity);
if (MessageLogger.LogMessagesAtServiceLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance);
}
}
internal static void SetActivity(Message message, ServiceModelActivity activity)
{
if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed)
{
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
EndpointAddress endpointAddress = null;
if (dispatcher != null)
{
endpointAddress = dispatcher.EndpointAddress;
}
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.DroppedAMessage,
SR.GetString(SR.TraceCodeDroppedAMessage), new MessageDroppedTraceRecord(message, endpointAddress));
}
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription)
{
TraceEvent(severity, traceCode, traceDescription, null, traceDescription, (Exception)null);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData)
{
TraceEvent(severity, traceCode, traceDescription, extendedData, null, (Exception)null);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source)
{
TraceEvent(severity, traceCode, traceDescription, null, source, (Exception)null);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source, Exception exception)
{
TraceEvent(severity, traceCode, traceDescription, null, source, exception);
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, Message message)
{
if (message == null)
{
TraceEvent(severity, traceCode, traceDescription, null, (Exception)null);
}
else
{
TraceEvent(severity, traceCode, traceDescription, message, message);
}
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source, Message message)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, new MessageTraceRecord(message), null, activityId, message);
}
}
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, Exception exception, Message message)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, new MessageTraceRecord(message), exception, activityId, null);
}
}
internal static void TraceEventNoCheck(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, source);
}
// These methods require a TraceRecord to be allocated, so we want them to show up on profiles if the caller didn't avoid
// allocating the TraceRecord by using ShouldTrace.
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception)
{
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, source);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Message message)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode),
traceDescription, extendedData, exception, activityId, source);
}
}
internal static void TraceEventNoCheck(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Guid activityId)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode),
traceDescription, extendedData, exception, activityId, source);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Guid activityId)
{
if (DiagnosticUtility.ShouldTrace(severity))
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode),
traceDescription, extendedData, exception, activityId, source);
}
}
static string GenerateMsdnTraceCode(int traceCode)
{
int group = (int)(traceCode & 0xFFFF0000);
string terminatorUri = null;
switch (group)
{
case TraceCode.Administration:
terminatorUri = "System.ServiceModel.Administration";
break;
case TraceCode.Channels:
terminatorUri = "System.ServiceModel.Channels";
break;
case TraceCode.ComIntegration:
terminatorUri = "System.ServiceModel.ComIntegration";
break;
case TraceCode.Diagnostics:
terminatorUri = "System.ServiceModel.Diagnostics";
break;
case TraceCode.PortSharing:
terminatorUri = "System.ServiceModel.PortSharing";
break;
case TraceCode.Security:
terminatorUri = "System.ServiceModel.Security";
break;
case TraceCode.Serialization:
terminatorUri = "System.Runtime.Serialization";
break;
case TraceCode.ServiceModel:
case TraceCode.ServiceModelTransaction:
terminatorUri = "System.ServiceModel";
break;
default:
terminatorUri = string.Empty;
break;
}
Fx.Assert(traceCodes.ContainsKey(traceCode),
string.Format(CultureInfo.InvariantCulture, "Unsupported trace code: Please add trace code 0x{0} to the SortedList TraceUtility.traceCodes in {1}",
traceCode.ToString("X", CultureInfo.InvariantCulture), typeof(TraceUtility)));
#if !MONO
return LegacyDiagnosticTrace.GenerateMsdnTraceCode(terminatorUri, traceCodes[traceCode]);
#else
return "";
#endif
}
internal static Exception ThrowHelperError(Exception exception, Message message)
{
// If the message is closed, we won't get an activity
Guid activityId = TraceUtility.ExtractActivityId(message);
if (DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException),
TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null);
}
return exception;
}
internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source)
{
if (DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException),
TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, source);
}
return exception;
}
internal static Exception ThrowHelperWarning(Exception exception, Message message)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
Guid activityId = TraceUtility.ExtractActivityId(message);
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException),
TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null);
}
return exception;
}
internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg)
{
return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg);
}
internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message)
{
return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message);
}
internal static string CreateSourceString(object source)
{
return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture);
}
internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
Dictionary<string, string> values = new Dictionary<string, string>(2)
{
{ "LocalEndpoint", localEndpoint },
{ "RemoteEndpoint", remoteEndpoint }
};
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ConnectToIPEndpoint,
SR.GetString(SR.TraceCodeConnectToIPEndpoint), new DictionaryTraceRecord(values), source, null);
}
}
internal static void TraceUserCodeException(Exception e, MethodInfo method)
{
if (DiagnosticUtility.ShouldTraceWarning)
{
StringTraceRecord record = new StringTraceRecord("Comment",
SR.GetString(SR.SFxUserCodeThrewException, method.DeclaringType.FullName, method.Name));
DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning,
TraceCode.UnhandledExceptionInUserOperation, GenerateMsdnTraceCode(TraceCode.UnhandledExceptionInUserOperation),
SR.GetString(SR.TraceCodeUnhandledExceptionInUserOperation, method.DeclaringType.FullName, method.Name),
record,
e, null);
}
}
static TraceUtility()
{
//Maintain the order of calls
TraceUtility.SetEtwProviderId();
TraceUtility.SetEndToEndTracingFlags();
if (DiagnosticUtility.DiagnosticTrace != null)
{
DiagnosticTraceSource ts = (DiagnosticTraceSource)DiagnosticUtility.DiagnosticTrace.TraceSource;
TraceUtility.shouldPropagateActivity = (ts.PropagateActivity || TraceUtility.shouldPropagateActivityGlobal);
}
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores bool values.")]
[SecuritySafeCritical]
static void SetEndToEndTracingFlags()
{
EndToEndTracingElement element = DiagnosticSection.UnsafeGetSection().EndToEndTracing;
TraceUtility.shouldPropagateActivityGlobal = element.PropagateActivity;
// if Sys.Diag trace is not enabled then the value is true if shouldPropagateActivityGlobal is true
TraceUtility.shouldPropagateActivity = TraceUtility.shouldPropagateActivityGlobal || TraceUtility.shouldPropagateActivity;
//Activity tracing is enabled by either of the flags (Sys.Diag trace source or E2E config element)
DiagnosticUtility.ShouldUseActivity = (DiagnosticUtility.ShouldUseActivity || element.ActivityTracing);
TraceUtility.activityTracing = DiagnosticUtility.ShouldUseActivity;
TraceUtility.messageFlowTracing = element.MessageFlowTracing || TraceUtility.activityTracing;
TraceUtility.messageFlowTracingOnly = element.MessageFlowTracing && !element.ActivityTracing;
//Set the flag if activity tracing is enabled through the E2E config element as well
DiagnosticUtility.TracingEnabled = (DiagnosticUtility.TracingEnabled || TraceUtility.activityTracing);
}
static public long RetrieveMessageNumber()
{
return Interlocked.Increment(ref TraceUtility.messageNumber);
}
static public bool PropagateUserActivity
{
get
{
return TraceUtility.ShouldPropagateActivity &&
TraceUtility.PropagateUserActivityCore;
}
}
// Most of the time, shouldPropagateActivity will be false.
// This property will rarely be executed as a result.
static bool PropagateUserActivityCore
{
[MethodImpl(MethodImplOptions.NoInlining)]
get
{
return !(DiagnosticUtility.TracingEnabled) &&
DiagnosticTraceBase.ActivityId != Guid.Empty;
}
}
static internal string GetCallerInfo(OperationContext context)
{
if (context != null && context.IncomingMessageProperties != null)
{
object endpointMessageProperty;
if (context.IncomingMessageProperties.TryGetValue(RemoteEndpointMessageProperty.Name, out endpointMessageProperty))
{
RemoteEndpointMessageProperty endpoint = endpointMessageProperty as RemoteEndpointMessageProperty;
if (endpoint != null)
{
return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", endpoint.Address, endpoint.Port);
}
}
}
return "null";
}
[Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.",
Safe = "Doesn't leak config section instance, just reads and stores string values for Guid")]
[SecuritySafeCritical]
static internal void SetEtwProviderId()
{
// Get section should not trace as the ETW provider id is not set yet
DiagnosticSection diagnostics = DiagnosticSection.UnsafeGetSectionNoTrace();
Guid etwProviderId = Guid.Empty;
//set the Id in PT if specified in the config file. If not, ETW tracing is off.
if (PartialTrustHelpers.HasEtwPermissions() || diagnostics.IsEtwProviderIdFromConfigFile())
{
etwProviderId = Fx.CreateGuid(diagnostics.EtwProviderId);
}
System.Runtime.Diagnostics.EtwDiagnosticTrace.DefaultEtwProviderId = etwProviderId;
}
static internal void SetActivityId(MessageProperties properties)
{
Guid activityId;
if ((null != properties) && properties.TryGetValue(TraceUtility.E2EActivityId, out activityId))
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
static internal bool ShouldPropagateActivity
{
get { return TraceUtility.shouldPropagateActivity; }
}
static internal bool ShouldPropagateActivityGlobal
{
get { return TraceUtility.shouldPropagateActivityGlobal; }
}
static internal bool ActivityTracing
{
get { return TraceUtility.activityTracing; }
}
static internal bool MessageFlowTracing
{
get { return TraceUtility.messageFlowTracing; }
}
static internal bool MessageFlowTracingOnly
{
get { return TraceUtility.messageFlowTracingOnly; }
}
static internal void MessageFlowAtMessageSent(Message message, EventTraceActivity eventTraceActivity)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (activityIdFound && activityId != DiagnosticTraceBase.ActivityId)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
if (TD.MessageSentToTransportIsEnabled())
{
TD.MessageSentToTransport(eventTraceActivity, correlationId);
}
}
}
static internal void MessageFlowAtMessageReceived(Message message, OperationContext context, EventTraceActivity eventTraceActivity, bool createNewActivityId)
{
if (TraceUtility.MessageFlowTracing)
{
Guid activityId;
Guid correlationId;
bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId);
if (TraceUtility.MessageFlowTracingOnly)
{
if (createNewActivityId)
{
if (!activityIdFound)
{
activityId = Guid.NewGuid();
activityIdFound = true;
}
//message flow tracing only - start fresh
DiagnosticTraceBase.ActivityId = Guid.Empty;
}
if (activityIdFound)
{
FxTrace.Trace.SetAndTraceTransfer(activityId, !createNewActivityId);
message.Properties[TraceUtility.E2EActivityId] = Trace.CorrelationManager.ActivityId;
}
}
if (TD.MessageReceivedFromTransportIsEnabled())
{
if (context == null)
{
context = OperationContext.Current;
}
TD.MessageReceivedFromTransport(eventTraceActivity, correlationId, TraceUtility.GetAnnotation(context));
}
}
}
internal static string GetAnnotation(OperationContext context)
{
object hostReference;
if (context != null && null != context.IncomingMessage && (MessageState.Closed != context.IncomingMessage.State))
{
if (!context.IncomingMessageProperties.TryGetValue(TraceApplicationReference, out hostReference))
{
hostReference = AspNetEnvironment.Current.GetAnnotationFromHost(context.Host);
context.IncomingMessageProperties.Add(TraceApplicationReference, hostReference);
}
}
else
{
hostReference = AspNetEnvironment.Current.GetAnnotationFromHost(null);
}
return (string)hostReference;
}
internal static void TransferFromTransport(Message message)
{
if (message != null && DiagnosticUtility.ShouldUseActivity)
{
Guid guid = Guid.Empty;
// Only look if we are allowing user propagation
if (TraceUtility.ShouldPropagateActivity)
{
guid = ActivityIdHeader.ExtractActivityId(message);
}
if (guid == Guid.Empty)
{
guid = Guid.NewGuid();
}
ServiceModelActivity activity = null;
bool emitStart = true;
if (ServiceModelActivity.Current != null)
{
if ((ServiceModelActivity.Current.Id == guid) ||
(ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction))
{
activity = ServiceModelActivity.Current;
emitStart = false;
}
else if (ServiceModelActivity.Current.PreviousActivity != null &&
ServiceModelActivity.Current.PreviousActivity.Id == guid)
{
activity = ServiceModelActivity.Current.PreviousActivity;
emitStart = false;
}
}
if (activity == null)
{
activity = ServiceModelActivity.CreateActivity(guid);
}
if (DiagnosticUtility.ShouldUseActivity)
{
if (emitStart)
{
if (null != FxTrace.Trace)
{
FxTrace.Trace.TraceTransfer(guid);
}
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction);
}
}
message.Properties[TraceUtility.ActivityIdKey] = activity;
}
}
static internal void UpdateAsyncOperationContextWithActivity(object activity)
{
if (OperationContext.Current != null && activity != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity;
}
}
static internal object ExtractAsyncOperationContextActivity()
{
object data = null;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey);
}
return data;
}
static internal void UpdateAsyncOperationContextWithStartTime(EventTraceActivity eventTraceActivity, long startTime)
{
if (OperationContext.Current != null)
{
OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationStartTimeKey] = new EventTraceActivityTimeProperty(eventTraceActivity, startTime);
}
}
static internal void ExtractAsyncOperationStartTime(out EventTraceActivity eventTraceActivity, out long startTime)
{
EventTraceActivityTimeProperty data = null;
eventTraceActivity = null;
startTime = 0;
if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue<EventTraceActivityTimeProperty>(TraceUtility.AsyncOperationStartTimeKey, out data))
{
OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationStartTimeKey);
eventTraceActivity = data.EventTraceActivity;
startTime = data.StartTime;
}
}
internal class TracingAsyncCallbackState
{
object innerState;
Guid activityId;
internal TracingAsyncCallbackState(object innerState)
{
this.innerState = innerState;
this.activityId = DiagnosticTraceBase.ActivityId;
}
internal object InnerState
{
get { return this.innerState; }
}
internal Guid ActivityId
{
get { return this.activityId; }
}
}
internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback)
{
return (DiagnosticUtility.ShouldUseActivity && callback != null) ?
(new ExecuteUserCodeAsync(callback)).Callback
: callback;
}
sealed class ExecuteUserCodeAsync
{
AsyncCallback callback;
public ExecuteUserCodeAsync(AsyncCallback callback)
{
this.callback = callback;
}
public AsyncCallback Callback
{
get
{
return Fx.ThunkCallback(new AsyncCallback(this.ExecuteUserCode));
}
}
void ExecuteUserCode(IAsyncResult result)
{
using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity())
{
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityCallback), ActivityType.ExecuteUserCode);
this.callback(result);
}
}
}
class EventTraceActivityTimeProperty
{
long startTime;
EventTraceActivity eventTraceActivity;
public EventTraceActivityTimeProperty(EventTraceActivity eventTraceActivity, long startTime)
{
this.eventTraceActivity = eventTraceActivity;
this.startTime = startTime;
}
internal long StartTime
{
get { return this.startTime; }
}
internal EventTraceActivity EventTraceActivity
{
get { return this.eventTraceActivity; }
}
}
internal static string GetRemoteEndpointAddressPort(Net.IPEndPoint iPEndPoint)
{
//We really don't want any exceptions out of TraceUtility.
if (iPEndPoint != null)
{
try
{
return iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
//ignore and continue with all non-fatal exceptions.
}
}
return string.Empty;
}
internal static string GetRemoteEndpointAddressPort(RemoteEndpointMessageProperty remoteEndpointMessageProperty)
{
try
{
if (remoteEndpointMessageProperty != null)
{
return remoteEndpointMessageProperty.Address + ":" + remoteEndpointMessageProperty.Port;
}
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
//ignore and continue with all non-fatal exceptions.
}
return string.Empty;
}
}
}
| |
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using MLAPI.Messaging;
namespace MLAPI.Prototyping
{
/// <summary>
/// A prototype component for syncing transforms
/// </summary>
[AddComponentMenu("MLAPI/NetworkTransform")]
public class NetworkTransform : NetworkBehaviour
{
internal class ClientSendInfo
{
public float LastSent;
public Vector3? LastMissedPosition;
public Quaternion? LastMissedRotation;
}
/// <summary>
/// The base amount of sends per seconds to use when range is disabled
/// </summary>
[Range(0, 120)]
public float FixedSendsPerSecond = 20f;
/// <summary>
/// Is the sends per second assumed to be the same across all instances
/// </summary>
[Tooltip("This assumes that the SendsPerSecond is synced across clients")]
public bool AssumeSyncedSends = true;
/// <summary>
/// Enable interpolation
/// </summary>
[Tooltip("This requires AssumeSyncedSends to be true")]
public bool InterpolatePosition = true;
/// <summary>
/// The distance before snaping to the position
/// </summary>
[Tooltip("The transform will snap if the distance is greater than this distance")]
public float SnapDistance = 10f;
/// <summary>
/// Should the server interpolate
/// </summary>
public bool InterpolateServer = true;
/// <summary>
/// The min meters to move before a send is sent
/// </summary>
public float MinMeters = 0.15f;
/// <summary>
/// The min degrees to rotate before a send it sent
/// </summary>
public float MinDegrees = 1.5f;
/// <summary>
/// Enables extrapolation
/// </summary>
public bool ExtrapolatePosition = false;
/// <summary>
/// The maximum amount of expected send rates to extrapolate over when awaiting new packets.
/// A higher value will result in continued extrapolation after an object has stopped moving
/// </summary>
public float MaxSendsToExtrapolate = 5;
/// <summary>
/// The channel to send the data on
/// </summary>
[Tooltip("The channel to send the data on. Uses the default channel if left unspecified")]
public string Channel = null;
private float m_LerpTime;
private Vector3 m_LerpStartPos;
private Quaternion m_LerpStartRot;
private Vector3 m_LerpEndPos;
private Quaternion m_LerpEndRot;
private float m_LastSendTime;
private Vector3 m_LastSentPos;
private Quaternion m_LastSentRot;
private float m_LastReceiveTime;
/// <summary>
/// Enables range based send rate
/// </summary>
public bool EnableRange;
/// <summary>
/// Checks for missed sends without provocation. Provocation being a client inside it's normal SendRate
/// </summary>
public bool EnableNonProvokedResendChecks;
/// <summary>
/// The curve to use to calculate the send rate
/// </summary>
public AnimationCurve DistanceSendrate = AnimationCurve.Constant(0, 500, 20);
private readonly Dictionary<ulong, ClientSendInfo> m_ClientSendInfo = new Dictionary<ulong, ClientSendInfo>();
/// <summary>
/// The delegate used to check if a move is valid
/// </summary>
/// <param name="clientId">The client id the move is being validated for</param>
/// <param name="oldPos">The previous position</param>
/// <param name="newPos">The new requested position</param>
/// <returns>Returns Whether or not the move is valid</returns>
public delegate bool MoveValidationDelegate(ulong clientId, Vector3 oldPos, Vector3 newPos);
/// <summary>
/// If set, moves will only be accepted if the custom delegate returns true
/// </summary>
public MoveValidationDelegate IsMoveValidDelegate = null;
private void OnValidate()
{
if (!AssumeSyncedSends && InterpolatePosition)
InterpolatePosition = false;
if (InterpolateServer && !InterpolatePosition)
InterpolateServer = false;
if (MinDegrees < 0)
MinDegrees = 0;
if (MinMeters < 0)
MinMeters = 0;
if (EnableNonProvokedResendChecks && !EnableRange)
EnableNonProvokedResendChecks = false;
}
private float GetTimeForLerp(Vector3 pos1, Vector3 pos2)
{
return 1f / DistanceSendrate.Evaluate(Vector3.Distance(pos1, pos2));
}
/// <summary>
/// Registers message handlers
/// </summary>
public override void NetworkStart()
{
m_LastSentRot = transform.rotation;
m_LastSentPos = transform.position;
m_LerpStartPos = transform.position;
m_LerpStartRot = transform.rotation;
m_LerpEndPos = transform.position;
m_LerpEndRot = transform.rotation;
}
private void Update()
{
if (IsOwner)
{
if (NetworkManager.Singleton.NetworkTime - m_LastSendTime >= (1f / FixedSendsPerSecond) && (Vector3.Distance(transform.position, m_LastSentPos) > MinMeters || Quaternion.Angle(transform.rotation, m_LastSentRot) > MinDegrees))
{
m_LastSendTime = NetworkManager.Singleton.NetworkTime;
m_LastSentPos = transform.position;
m_LastSentRot = transform.rotation;
if (IsServer)
{
ApplyTransformClientRpc(transform.position, transform.rotation.eulerAngles,
new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = NetworkManager.Singleton.ConnectedClientsList.Where(c => c.ClientId != OwnerClientId).Select(c => c.ClientId).ToArray() } });
}
else
{
SubmitTransformServerRpc(transform.position, transform.rotation.eulerAngles);
}
}
}
else
{
//If we are server and interpolation is turned on for server OR we are not server and interpolation is turned on
if ((IsServer && InterpolateServer && InterpolatePosition) || (!IsServer && InterpolatePosition))
{
if (Vector3.Distance(transform.position, m_LerpEndPos) > SnapDistance)
{
//Snap, set T to 1 (100% of the lerp)
m_LerpTime = 1f;
}
float sendDelay = (IsServer || !EnableRange || !AssumeSyncedSends || NetworkManager.Singleton.ConnectedClients[NetworkManager.Singleton.LocalClientId].PlayerObject == null) ? (1f / FixedSendsPerSecond) : GetTimeForLerp(transform.position, NetworkManager.Singleton.ConnectedClients[NetworkManager.Singleton.LocalClientId].PlayerObject.transform.position);
m_LerpTime += Time.unscaledDeltaTime / sendDelay;
if (ExtrapolatePosition && Time.unscaledTime - m_LastReceiveTime < sendDelay * MaxSendsToExtrapolate)
transform.position = Vector3.LerpUnclamped(m_LerpStartPos, m_LerpEndPos, m_LerpTime);
else
transform.position = Vector3.Lerp(m_LerpStartPos, m_LerpEndPos, m_LerpTime);
if (ExtrapolatePosition && Time.unscaledTime - m_LastReceiveTime < sendDelay * MaxSendsToExtrapolate)
transform.rotation = Quaternion.SlerpUnclamped(m_LerpStartRot, m_LerpEndRot, m_LerpTime);
else
transform.rotation = Quaternion.Slerp(m_LerpStartRot, m_LerpEndRot, m_LerpTime);
}
}
if (IsServer && EnableRange && EnableNonProvokedResendChecks)
CheckForMissedSends();
}
[ClientRpc]
private void ApplyTransformClientRpc(Vector3 position, Vector3 eulerAngles, ClientRpcParams rpcParams = default)
{
if (enabled)
{
ApplyTransformInternal(position, Quaternion.Euler(eulerAngles));
}
}
private void ApplyTransformInternal(Vector3 position, Quaternion rotation)
{
if (!enabled)
return;
if (InterpolatePosition && (!IsServer || InterpolateServer))
{
m_LastReceiveTime = Time.unscaledTime;
m_LerpStartPos = transform.position;
m_LerpStartRot = transform.rotation;
m_LerpEndPos = position;
m_LerpEndRot = rotation;
m_LerpTime = 0;
}
else
{
transform.position = position;
transform.rotation = rotation;
}
}
[ServerRpc]
private void SubmitTransformServerRpc(Vector3 position, Vector3 eulerAngles, ServerRpcParams rpcParams = default)
{
if (!enabled)
return;
if (IsMoveValidDelegate != null && !IsMoveValidDelegate(rpcParams.Receive.SenderClientId, m_LerpEndPos, position))
{
//Invalid move!
//TODO: Add rubber band (just a message telling them to go back)
return;
}
if (!IsClient)
{
// Dedicated server
ApplyTransformInternal(position, Quaternion.Euler(eulerAngles));
}
if (EnableRange)
{
for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++)
{
if (!m_ClientSendInfo.ContainsKey(NetworkManager.Singleton.ConnectedClientsList[i].ClientId))
{
m_ClientSendInfo.Add(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, new ClientSendInfo()
{
LastMissedPosition = null,
LastMissedRotation = null,
LastSent = 0
});
}
ClientSendInfo info = m_ClientSendInfo[NetworkManager.Singleton.ConnectedClientsList[i].ClientId];
Vector3? receiverPosition = NetworkManager.Singleton.ConnectedClientsList[i].PlayerObject == null ? null : new Vector3?(NetworkManager.Singleton.ConnectedClientsList[i].PlayerObject.transform.position);
Vector3? senderPosition = NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject == null ? null : new Vector3?(NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject.transform.position);
if ((receiverPosition == null || senderPosition == null && NetworkManager.Singleton.NetworkTime - info.LastSent >= (1f / FixedSendsPerSecond)) || NetworkManager.Singleton.NetworkTime - info.LastSent >= GetTimeForLerp(receiverPosition.Value, senderPosition.Value))
{
info.LastSent = NetworkManager.Singleton.NetworkTime;
info.LastMissedPosition = null;
info.LastMissedRotation = null;
ApplyTransformClientRpc(position, eulerAngles,
new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = new[] { NetworkManager.Singleton.ConnectedClientsList[i].ClientId } } });
}
else
{
info.LastMissedPosition = position;
info.LastMissedRotation = Quaternion.Euler(eulerAngles);
}
}
}
else
{
ApplyTransformClientRpc(position, eulerAngles,
new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = NetworkManager.Singleton.ConnectedClientsList.Where(c => c.ClientId != OwnerClientId).Select(c => c.ClientId).ToArray() } });
}
}
private void CheckForMissedSends()
{
for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsList.Count; i++)
{
if (!m_ClientSendInfo.ContainsKey(NetworkManager.Singleton.ConnectedClientsList[i].ClientId))
{
m_ClientSendInfo.Add(NetworkManager.Singleton.ConnectedClientsList[i].ClientId, new ClientSendInfo()
{
LastMissedPosition = null,
LastMissedRotation = null,
LastSent = 0
});
}
ClientSendInfo info = m_ClientSendInfo[NetworkManager.Singleton.ConnectedClientsList[i].ClientId];
Vector3? receiverPosition = NetworkManager.Singleton.ConnectedClientsList[i].PlayerObject == null ? null : new Vector3?(NetworkManager.Singleton.ConnectedClientsList[i].PlayerObject.transform.position);
Vector3? senderPosition = NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject == null ? null : new Vector3?(NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject.transform.position);
if ((receiverPosition == null || senderPosition == null && NetworkManager.Singleton.NetworkTime - info.LastSent >= (1f / FixedSendsPerSecond)) || NetworkManager.Singleton.NetworkTime - info.LastSent >= GetTimeForLerp(receiverPosition.Value, senderPosition.Value))
{
/* why is this??? ->*/
Vector3? pos = NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject == null ? null : new Vector3?(NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject.transform.position);
/* why is this??? ->*/
Vector3? rot = NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject == null ? null : new Vector3?(NetworkManager.Singleton.ConnectedClients[OwnerClientId].PlayerObject.transform.rotation.eulerAngles);
if (info.LastMissedPosition != null && info.LastMissedRotation != null)
{
info.LastSent = NetworkManager.Singleton.NetworkTime;
ApplyTransformClientRpc(info.LastMissedPosition.Value, info.LastMissedRotation.Value.eulerAngles,
new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = new[] { NetworkManager.Singleton.ConnectedClientsList[i].ClientId } } });
info.LastMissedPosition = null;
info.LastMissedRotation = null;
}
}
}
}
/// <summary>
/// Teleports the transform to the given position and rotation
/// </summary>
/// <param name="position">The position to teleport to</param>
/// <param name="rotation">The rotation to teleport to</param>
public void Teleport(Vector3 position, Quaternion rotation)
{
if (InterpolateServer && IsServer || IsClient)
{
m_LerpStartPos = position;
m_LerpStartRot = rotation;
m_LerpEndPos = position;
m_LerpEndRot = rotation;
m_LerpTime = 0;
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Net;
using Newtonsoft.Json;
namespace SteamTrade
{
/// <summary>
/// This class handles the web-based interaction for Steam trades.
/// </summary>
public partial class Trade
{
static string SteamCommunityDomain = "steamcommunity.com";
static string SteamTradeUrl = "http://steamcommunity.com/trade/{0}/";
string sessionId;
string sessionIdEsc;
string baseTradeURL;
string steamLogin;
CookieContainer cookies;
internal int LogPos { get; set; }
internal int Version { get; set; }
StatusObj GetStatus ()
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
data.Add ("logpos", "" + LogPos);
data.Add ("version", "" + Version);
string response = Fetch (baseTradeURL + "tradestatus", "POST", data);
return JsonConvert.DeserializeObject<StatusObj> (response);
}
#region Trade Web command methods
/// <summary>
/// Sends a message to the user over the trade chat.
/// </summary>
bool SendMessageWebCmd (string msg)
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
data.Add ("message", msg);
data.Add ("logpos", "" + LogPos);
data.Add ("version", "" + Version);
string result = Fetch (baseTradeURL + "chat", "POST", data);
dynamic json = JsonConvert.DeserializeObject(result);
if (json == null || json.success != "true")
{
return false;
}
return true;
}
/// <summary>
/// Adds a specified itom by its itemid. Since each itemid is
/// unique to each item, you'd first have to find the item, or
/// use AddItemByDefindex instead.
/// </summary>
/// <returns>
/// Returns false if the item doesn't exist in the Bot's inventory,
/// and returns true if it appears the item was added.
/// </returns>
bool AddItemWebCmd (ulong itemid, int slot)
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
data.Add ("appid", "440");
data.Add ("contextid", "2");
data.Add ("itemid", "" + itemid);
data.Add ("slot", "" + slot);
string result = Fetch(baseTradeURL + "additem", "POST", data);
dynamic json = JsonConvert.DeserializeObject(result);
if (json == null || json.success != "true")
{
return false;
}
return true;
}
/// <summary>
/// Removes an item by its itemid. Read AddItem about itemids.
/// Returns false if the item isn't in the offered items, or
/// true if it appears it succeeded.
/// </summary>
bool RemoveItemWebCmd (ulong itemid, int slot)
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
data.Add ("appid", "440");
data.Add ("contextid", "2");
data.Add ("itemid", "" + itemid);
data.Add ("slot", "" + slot);
string result = Fetch (baseTradeURL + "removeitem", "POST", data);
dynamic json = JsonConvert.DeserializeObject(result);
if (json == null || json.success != "true")
{
return false;
}
return true;
}
/// <summary>
/// Sets the bot to a ready status.
/// </summary>
bool SetReadyWebCmd (bool ready)
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
data.Add ("ready", ready ? "true" : "false");
data.Add ("version", "" + Version);
string result = Fetch (baseTradeURL + "toggleready", "POST", data);
dynamic json = JsonConvert.DeserializeObject(result);
if (json == null || json.success != "true")
{
return false;
}
return true;
}
/// <summary>
/// Accepts the trade from the user. Returns a deserialized
/// JSON object.
/// </summary>
bool AcceptTradeWebCmd ()
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
data.Add ("version", "" + Version);
string response = Fetch (baseTradeURL + "confirm", "POST", data);
dynamic json = JsonConvert.DeserializeObject(response);
if (json == null || json.success != "true")
{
return false;
}
return true;
}
/// <summary>
/// Cancel the trade. This calls the OnClose handler, as well.
/// </summary>
bool CancelTradeWebCmd ()
{
var data = new NameValueCollection ();
data.Add ("sessionid", sessionIdEsc);
string result = Fetch (baseTradeURL + "cancel", "POST", data);
dynamic json = JsonConvert.DeserializeObject(result);
if (json == null || json.success != "true")
{
return false;
}
return true;
}
#endregion Trade Web command methods
string Fetch (string url, string method, NameValueCollection data = null)
{
return SteamWeb.Fetch (url, method, data, cookies);
}
void Init()
{
sessionIdEsc = Uri.UnescapeDataString(sessionId);
Version = 1;
cookies = new CookieContainer();
cookies.Add (new Cookie ("sessionid", sessionId, String.Empty, SteamCommunityDomain));
cookies.Add (new Cookie ("steamLogin", steamLogin, String.Empty, SteamCommunityDomain));
baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64 ());
}
public class StatusObj
{
public string error { get; set; }
public bool newversion { get; set; }
public bool success { get; set; }
public long trade_status { get; set; }
public int version { get; set; }
public int logpos { get; set; }
public TradeUserObj me { get; set; }
public TradeUserObj them { get; set; }
public TradeEvent[] events { get; set; }
}
public class TradeEvent
{
public string steamid { get; set; }
public int action { get; set; }
public ulong timestamp { get; set; }
public int appid { get; set; }
public string text { get; set; }
public int contextid { get; set; }
public ulong assetid { get; set; }
}
public class TradeUserObj
{
public int ready { get; set; }
public int confirmed { get; set; }
public int sec_since_touch { get; set; }
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <[email protected]>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
public class OptionValueCollection : IList, IList<string>
{
List<string> values = new List<string>();
OptionContext c;
internal OptionValueCollection(OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); }
bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } }
object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } }
#endregion
#region ICollection<T>
public void Add(string item) { values.Add(item); }
public void Clear() { values.Clear(); }
public bool Contains(string item) { return values.Contains(item); }
public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); }
public bool Remove(string item) { return values.Remove(item); }
public int Count { get { return values.Count; } }
public bool IsReadOnly { get { return false; } }
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); }
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); }
#endregion
#region IList
int IList.Add(object value) { return (values as IList).Add(value); }
bool IList.Contains(object value) { return (values as IList).Contains(value); }
int IList.IndexOf(object value) { return (values as IList).IndexOf(value); }
void IList.Insert(int index, object value) { (values as IList).Insert(index, value); }
void IList.Remove(object value) { (values as IList).Remove(value); }
void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); }
bool IList.IsFixedSize { get { return false; } }
object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } }
#endregion
#region IList<T>
public int IndexOf(string item) { return values.IndexOf(item); }
public void Insert(int index, string item) { values.Insert(index, item); }
public void RemoveAt(int index) { values.RemoveAt(index); }
private void AssertValid(int index)
{
if (c.Option == null)
throw new InvalidOperationException("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException(string.Format(
c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this[int index]
{
get
{
AssertValid(index);
return index >= values.Count ? null : values[index];
}
set
{
values[index] = value;
}
}
#endregion
public List<string> ToList()
{
return new List<string>(values);
}
public string[] ToArray()
{
return values.ToArray();
}
public override string ToString()
{
return string.Join(", ", values.ToArray());
}
}
public class OptionContext
{
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext(OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection(this);
}
public Option Option
{
get { return option; }
set { option = value; }
}
public string OptionName
{
get { return name; }
set { name = value; }
}
public int OptionIndex
{
get { return index; }
set { index = value; }
}
public OptionSet OptionSet
{
get { return set; }
}
public OptionValueCollection OptionValues
{
get { return c; }
}
}
public enum OptionValueType
{
None,
Optional,
Required,
}
public abstract class Option
{
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option(string prototype, string description)
: this(prototype, description, 1)
{
}
protected Option(string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException("prototype");
if (prototype.Length == 0)
throw new ArgumentException("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException(
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException(
string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf(names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException(
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype { get { return prototype; } }
public string Description { get { return description; } }
public OptionValueType OptionValueType { get { return type; } }
public int MaxValueCount { get { return count; } }
public string[] GetNames()
{
return (string[])names.Clone();
}
public string[] GetValueSeparators()
{
if (separators == null)
return new string[0];
return (string[])separators.Clone();
}
protected static T Parse<T>(string value, OptionContext c)
{
Type tt = typeof(T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition() == typeof(Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments()[0] : typeof(T);
TypeConverter conv = TypeDescriptor.GetConverter(targetType);
T t = default(T);
try
{
if (value != null)
t = (T)conv.ConvertFromString(value);
}
catch (Exception e)
{
throw new OptionException(
string.Format(
c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names { get { return names; } }
internal string[] ValueSeparators { get { return separators; } }
static readonly char[] NameTerminator = new char[] { '=', ':' };
private OptionValueType ParsePrototype()
{
char type = '\0';
List<string> seps = new List<string>();
for (int i = 0; i < names.Length; ++i)
{
string name = names[i];
if (name.Length == 0)
throw new ArgumentException("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny(NameTerminator);
if (end == -1)
continue;
names[i] = name.Substring(0, end);
if (type == '\0' || type == name[end])
type = name[end];
else
throw new ArgumentException(
string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]),
"prototype");
AddSeparators(name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException(
string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1)
{
if (seps.Count == 0)
this.separators = new string[] { ":", "=" };
else if (seps.Count == 1 && seps[0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators(string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end + 1; i < name.Length; ++i)
{
switch (name[i])
{
case '{':
if (start != -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i + 1;
break;
case '}':
if (start == -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add(name.Substring(start, i - start));
start = -1;
break;
default:
if (start == -1)
seps.Add(name[i].ToString());
break;
}
}
if (start != -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke(OptionContext c)
{
OnParseComplete(c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear();
}
protected abstract void OnParseComplete(OptionContext c);
public override string ToString()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception
{
private string option;
public OptionException()
{
}
public OptionException(string message, string optionName)
: base(message)
{
this.option = optionName;
}
public OptionException(string message, string optionName, Exception innerException)
: base(message, innerException)
{
this.option = optionName;
}
protected OptionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.option = info.GetString("OptionName");
}
public string OptionName
{
get { return this.option; }
}
[SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet()
: this(delegate(string f) { return f; })
{
}
public OptionSet(Converter<string, string> localizer)
{
this.localizer = localizer;
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer
{
get { return localizer; }
}
protected override string GetKeyForItem(Option item)
{
if (item == null)
throw new ArgumentNullException("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names[0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException("Option has no names!");
}
[Obsolete("Use KeyedCollection.this[string]")]
protected Option GetOptionForName(string option)
{
if (option == null)
throw new ArgumentNullException("option");
try
{
return base[option];
}
catch (KeyNotFoundException)
{
return null;
}
}
protected override void InsertItem(int index, Option item)
{
base.InsertItem(index, item);
AddImpl(item);
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
Option p = Items[index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i)
{
Dictionary.Remove(p.Names[i]);
}
}
protected override void SetItem(int index, Option item)
{
base.SetItem(index, item);
RemoveItem(index);
AddImpl(item);
}
private void AddImpl(Option option)
{
if (option == null)
throw new ArgumentNullException("option");
List<string> added = new List<string>(option.Names.Length);
try
{
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i)
{
Dictionary.Add(option.Names[i], option);
added.Add(option.Names[i]);
}
}
catch (Exception)
{
foreach (string name in added)
Dictionary.Remove(name);
throw;
}
}
public new OptionSet Add(Option option)
{
base.Add(option);
return this;
}
sealed class ActionOption : Option
{
Action<OptionValueCollection> action;
public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action)
: base(prototype, description, count)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(c.OptionValues);
}
}
public OptionSet Add(string prototype, Action<string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 1,
delegate(OptionValueCollection v) { action(v[0]); });
base.Add(p);
return this;
}
public OptionSet Add(string prototype, OptionAction<string, string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 2,
delegate(OptionValueCollection v) { action(v[0], v[1]); });
base.Add(p);
return this;
}
sealed class ActionOption<T> : Option
{
Action<T> action;
public ActionOption(string prototype, string description, Action<T> action)
: base(prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(Parse<T>(c.OptionValues[0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option
{
OptionAction<TKey, TValue> action;
public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action)
: base(prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(
Parse<TKey>(c.OptionValues[0], c),
Parse<TValue>(c.OptionValues[1], c));
}
}
public OptionSet Add<T>(string prototype, Action<T> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<T>(string prototype, string description, Action<T> action)
{
return Add(new ActionOption<T>(prototype, description, action));
}
public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add(new ActionOption<TKey, TValue>(prototype, description, action));
}
protected virtual OptionContext CreateOptionContext()
{
return new OptionContext(this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
var def = GetOptionForName ("<>");
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse(IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string>();
Option def = Contains("<>") ? this["<>"] : null;
foreach (string argument in arguments)
{
++c.OptionIndex;
if (argument == "--")
{
process = false;
continue;
}
if (!process)
{
Unprocessed(unprocessed, def, c, argument);
continue;
}
if (!Parse(argument, c))
Unprocessed(unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke(c);
return unprocessed;
}
#endif
private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null)
{
extra.Add(argument);
return false;
}
c.OptionValues.Add(argument);
c.Option = def;
c.Option.Invoke(c);
return false;
}
private readonly Regex ValueOption = new Regex(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match(argument);
if (!m.Success)
{
return false;
}
flag = m.Groups["flag"].Value;
name = m.Groups["name"].Value;
if (m.Groups["sep"].Success && m.Groups["value"].Success)
{
sep = m.Groups["sep"].Value;
value = m.Groups["value"].Value;
}
return true;
}
protected virtual bool Parse(string argument, OptionContext c)
{
if (c.Option != null)
{
ParseValue(argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts(argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains(n))
{
p = this[n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType)
{
case OptionValueType.None:
c.OptionValues.Add(n);
c.Option.Invoke(c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue(v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool(argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue(f, string.Concat(n + s + v), c))
return true;
return false;
}
private void ParseValue(string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split(c.Option.ValueSeparators, StringSplitOptions.None)
: new string[] { option })
{
c.OptionValues.Add(o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke(c);
else if (c.OptionValues.Count > c.Option.MaxValueCount)
{
throw new OptionException(localizer(string.Format(
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool(string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') &&
Contains((rn = n.Substring(0, n.Length - 1))))
{
p = this[rn];
string v = n[n.Length - 1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add(v);
p.Invoke(c);
return true;
}
return false;
}
private bool ParseBundledValue(string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i)
{
Option p;
string opt = f + n[i].ToString();
string rn = n[i].ToString();
if (!Contains(rn))
{
if (i == 0)
return false;
throw new OptionException(string.Format(localizer(
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this[rn];
switch (p.OptionValueType)
{
case OptionValueType.None:
Invoke(c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
{
string v = n.Substring(i + 1);
c.Option = p;
c.OptionName = opt;
ParseValue(v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke(OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add(value);
option.Invoke(c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions(TextWriter o)
{
foreach (Option p in this)
{
int written = 0;
if (!WriteOptionPrototype(o, p, ref written))
continue;
if (written < OptionWidth)
o.Write(new string(' ', OptionWidth - written));
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
bool indent = false;
string prefix = new string(' ', OptionWidth + 2);
foreach (string line in GetLines(localizer(GetDescription(p.Description))))
{
if (indent)
o.Write(prefix);
o.WriteLine(line);
indent = true;
}
}
}
bool WriteOptionPrototype(TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex(names, 0);
if (i == names.Length)
return false;
if (names[i].Length == 1)
{
Write(o, ref written, " -");
Write(o, ref written, names[0]);
}
else
{
Write(o, ref written, " --");
Write(o, ref written, names[0]);
}
for (i = GetNextOptionIndex(names, i + 1);
i < names.Length; i = GetNextOptionIndex(names, i + 1))
{
Write(o, ref written, ", ");
Write(o, ref written, names[i].Length == 1 ? "-" : "--");
Write(o, ref written, names[i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required)
{
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("["));
}
Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators[0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c)
{
Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("]"));
}
}
return true;
}
static int GetNextOptionIndex(string[] names, int i)
{
while (i < names.Length && names[i] == "<>")
{
++i;
}
return i;
}
static void Write(TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write(s);
}
private static string GetArgumentName(int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[] { "{0:", "{" };
else
nameStart = new string[] { "{" + index + ":" };
for (int i = 0; i < nameStart.Length; ++i)
{
int start, j = 0;
do
{
start = description.IndexOf(nameStart[i], j);
} while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf("}", start);
if (end == -1)
continue;
return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription(string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder(description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i)
{
switch (description[i])
{
case '{':
if (i == start)
{
sb.Append('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0)
{
if ((i + 1) == description.Length || description[i + 1] != '}')
throw new InvalidOperationException("Invalid option description: " + description);
++i;
sb.Append("}");
}
else
{
sb.Append(description.Substring(start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append(description[i]);
break;
}
}
return sb.ToString();
}
private static IEnumerable<string> GetLines(string description)
{
if (string.IsNullOrEmpty(description))
{
yield return string.Empty;
yield break;
}
int length = 80 - OptionWidth - 1;
int start = 0, end;
do
{
end = GetLineEnd(start, length, description);
char c = description[end - 1];
if (char.IsWhiteSpace(c))
--end;
bool writeContinuation = end != description.Length && !IsEolChar(c);
string line = description.Substring(start, end - start) +
(writeContinuation ? "-" : "");
yield return line;
start = end;
if (char.IsWhiteSpace(c))
++start;
length = 80 - OptionWidth - 2 - 1;
} while (end < description.Length);
}
private static bool IsEolChar(char c)
{
return !char.IsLetterOrDigit(c);
}
private static int GetLineEnd(int start, int length, string description)
{
int end = System.Math.Min(start + length, description.Length);
int sep = -1;
for (int i = start + 1; i < end; ++i)
{
if (description[i] == '\n')
return i + 1;
if (IsEolChar(description[i]))
sep = i + 1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2016 CoreTweet Development Team
//
// 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 System.Linq;
using System.Net;
using System.Text;
using CoreTweet.Core;
using Newtonsoft.Json.Linq;
namespace CoreTweet
{
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for OAuth authentication.
/// </summary>
public static partial class OAuth
{
/// <summary>
/// Represents an OAuth session.
/// </summary>
public class OAuthSession
{
/// <summary>
/// Gets or sets the consumer key.
/// </summary>
public string ConsumerKey { get; set; }
/// <summary>
/// Gets or sets the consumer secret.
/// </summary>
public string ConsumerSecret { get; set; }
/// <summary>
/// Gets or sets the request token.
/// </summary>
public string RequestToken { get; set; }
/// <summary>
/// Gets or sets the request token secret.
/// </summary>
public string RequestTokenSecret { get; set; }
/// <summary>
/// Gets or sets the options of the connection.
/// </summary>
public ConnectionOptions ConnectionOptions { get; set; }
/// <summary>
/// Gets the authorize URL.
/// </summary>
public Uri AuthorizeUri
{
get
{
var options = this.ConnectionOptions ?? new ConnectionOptions();
return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth/authorize") + "?oauth_token=" + RequestToken);
}
}
}
private static Uri GetRequestTokenUrl(ConnectionOptions options)
{
if (options == null) options = new ConnectionOptions();
return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth/request_token"));
}
private static Uri GetAccessTokenUrl(ConnectionOptions options)
{
if (options == null) options = new ConnectionOptions();
return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth/access_token"));
}
#if !ASYNC_ONLY
/// <summary>
/// <para>Generates the authorize URI.</para>
/// <para>Then call <see cref="GetTokens"/> after get the pin code.</para>
/// </summary>
/// <param name="consumerKey">The Consumer key.</param>
/// <param name="consumerSecret">The Consumer secret.</param>
/// <param name="oauthCallback">
/// <para>For OAuth 1.0a compliance this parameter is required.</para>
/// <para>The value you specify here will be used as the URL a user is redirected to should they approve your application's access to their account.</para>
/// <para>Set this to oob for out-of-band pin mode.</para>
/// <para>This is also how you specify custom callbacks for use in desktop/mobile applications.</para>
/// <para>Always send an oauth_callback on this step, regardless of a pre-registered callback.</para>
/// </param>
/// <param name="options">The connection options for the request.</param>
/// <returns>The authorize URI.</returns>
public static OAuthSession Authorize(string consumerKey, string consumerSecret, string oauthCallback = "oob", ConnectionOptions options = null)
{
var reqUrl = GetRequestTokenUrl(options);
// Note: Twitter says,
// "If you're using HTTP-header based OAuth, you shouldn't include oauth_* parameters in the POST body or querystring."
var prm = new Dictionary<string,object>();
if(!string.IsNullOrEmpty(oauthCallback))
prm.Add("oauth_callback", oauthCallback);
var header = Tokens.Create(consumerKey, consumerSecret, null, null)
.CreateAuthorizationHeader(MethodType.Post, reqUrl, prm);
try
{
var dic = from x in Request.HttpPost(reqUrl, prm, header, options).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select y.ReadToEnd()
.Split('&')
.Where(z => z.Contains('='))
.Select(z => z.Split('='))
.ToDictionary(z => z[0], z => z[1]);
return new OAuthSession()
{
RequestToken = dic["oauth_token"],
RequestTokenSecret = dic["oauth_token_secret"],
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
ConnectionOptions = options
};
}
catch(WebException ex)
{
var tex = TwitterException.Create(ex);
if(tex != null)
throw tex;
throw;
}
}
/// <summary>
/// <para>Gets the OAuth tokens.</para>
/// <para>Be sure to call <see cref="Authorize"/> before call this method.</para>
/// </summary>
/// <param name="session">The OAuth session.</param>
/// <param name="pin">The pin code.</param>
/// <returns>The tokens.</returns>
public static Tokens GetTokens(this OAuthSession session, string pin)
{
var reqUrl = GetAccessTokenUrl(session.ConnectionOptions);
var prm = new Dictionary<string,object>() { { "oauth_verifier", pin } };
var header = Tokens.Create(session.ConsumerKey, session.ConsumerSecret, session.RequestToken, session.RequestTokenSecret)
.CreateAuthorizationHeader(MethodType.Post, reqUrl, prm);
try
{
var dic = from x in Request.HttpPost(reqUrl, prm, header, session.ConnectionOptions).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select y.ReadToEnd()
.Split('&')
.Where(z => z.Contains('='))
.Select(z => z.Split('='))
.ToDictionary(z => z[0], z => z[1]);
var t = Tokens.Create(session.ConsumerKey, session.ConsumerSecret,
dic["oauth_token"], dic["oauth_token_secret"], long.Parse(dic["user_id"]), dic["screen_name"]);
t.ConnectionOptions = session.ConnectionOptions;
return t;
}
catch(WebException ex)
{
var tex = TwitterException.Create(ex);
if(tex != null)
throw tex;
throw;
}
}
#endif
}
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for OAuth 2 Authentication.
/// </summary>
public static partial class OAuth2
{
private static Uri GetAccessTokenUrl(ConnectionOptions options)
{
if (options == null) options = new ConnectionOptions();
return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth2/token"));
}
private static Uri GetInvalidateTokenUrl(ConnectionOptions options)
{
if (options == null) options = new ConnectionOptions();
return new Uri(InternalUtils.GetUrl(options, options.ApiUrl, false, "oauth2/invalidate_token"));
}
private static string CreateCredentials(string consumerKey, string consumerSecret)
{
return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret));
}
#if !ASYNC_ONLY
/// <summary>
/// Gets the OAuth 2 Bearer Token.
/// </summary>
/// <param name="consumerKey">The consumer key.</param>
/// <param name="consumerSecret">The consumer secret.</param>
/// <param name="options">The connection options for the request.</param>
/// <returns>The tokens.</returns>
public static OAuth2Token GetToken(string consumerKey, string consumerSecret, ConnectionOptions options = null)
{
try
{
var token = from x in Request.HttpPost(
GetAccessTokenUrl(options),
new Dictionary<string, object>() { { "grant_type", "client_credentials" } }, // At this time, only client_credentials is allowed.
CreateCredentials(consumerKey, consumerSecret),
options).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select (string)JObject.Parse(y.ReadToEnd())["access_token"];
var t = OAuth2Token.Create(consumerKey, consumerSecret, token);
t.ConnectionOptions = options;
return t;
}
catch(WebException ex)
{
var tex = TwitterException.Create(ex);
if(tex != null)
throw tex;
throw;
}
}
/// <summary>
/// Invalidates the OAuth 2 Bearer Token.
/// </summary>
/// <param name="tokens">An instance of <see cref="OAuth2Token"/>.</param>
/// <returns>The invalidated token.</returns>
public static string InvalidateToken(this OAuth2Token tokens)
{
try
{
return from x in Request.HttpPost(
GetInvalidateTokenUrl(tokens.ConnectionOptions),
new Dictionary<string, object>() { { "access_token", Uri.UnescapeDataString(tokens.BearerToken) } },
CreateCredentials(tokens.ConsumerKey, tokens.ConsumerSecret),
tokens.ConnectionOptions).Use()
from y in new StreamReader(x.GetResponseStream()).Use()
select (string)JObject.Parse(y.ReadToEnd())["access_token"];
}
catch(WebException ex)
{
var tex = TwitterException.Create(ex);
if(tex != null)
throw tex;
throw;
}
}
#endif
}
}
| |
#region Apache License, Version 2.0
//
// 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.
//
#endregion
namespace NPanday.VisualStudio.Addin
{
using System.Windows.Forms;
partial class AddArtifactsForm
{
/// <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.addArtifact = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.remoteTabPage = new System.Windows.Forms.TabPage();
this.treeView1 = new System.Windows.Forms.TreeView();
this.localTabPage = new System.Windows.Forms.TabPage();
this.localListView = new System.Windows.Forms.ListView();
this.ArtifactNameHeader = new System.Windows.Forms.ColumnHeader();
this.versionHeader = new System.Windows.Forms.ColumnHeader();
this.artifactTabControl = new System.Windows.Forms.TabControl();
this.ConfigureTab = new System.Windows.Forms.TabPage();
this.UpdateLabel = new System.Windows.Forms.Label();
this.RepoCombo = new System.Windows.Forms.ComboBox();
this.checkBoxSnapshot = new System.Windows.Forms.CheckBox();
this.checkBoxRelease = new System.Windows.Forms.CheckBox();
this.update = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.remoteTabPage.SuspendLayout();
this.localTabPage.SuspendLayout();
this.artifactTabControl.SuspendLayout();
this.ConfigureTab.SuspendLayout();
this.SuspendLayout();
//
// addArtifact
//
this.addArtifact.Location = new System.Drawing.Point(299, 296);
this.addArtifact.Margin = new System.Windows.Forms.Padding(2);
this.addArtifact.Name = "addArtifact";
this.addArtifact.Size = new System.Drawing.Size(83, 26);
this.addArtifact.TabIndex = 1;
this.addArtifact.Text = "&Add";
this.addArtifact.UseVisualStyleBackColor = true;
this.addArtifact.Click += new System.EventHandler(this.addArtifact_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(396, 296);
this.button2.Margin = new System.Windows.Forms.Padding(2);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(86, 26);
this.button2.TabIndex = 2;
this.button2.Text = "&Close";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// remoteTabPage
//
this.remoteTabPage.Controls.Add(this.treeView1);
this.remoteTabPage.Location = new System.Drawing.Point(4, 22);
this.remoteTabPage.Margin = new System.Windows.Forms.Padding(2);
this.remoteTabPage.Name = "remoteTabPage";
this.remoteTabPage.Padding = new System.Windows.Forms.Padding(2);
this.remoteTabPage.Size = new System.Drawing.Size(469, 249);
this.remoteTabPage.TabIndex = 1;
this.remoteTabPage.Text = "Remote";
this.remoteTabPage.UseVisualStyleBackColor = true;
this.remoteTabPage.Click += new System.EventHandler(this.remoteTabPage_Click);
//
// treeView1
//
this.treeView1.Location = new System.Drawing.Point(17, 15);
this.treeView1.Margin = new System.Windows.Forms.Padding(2);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(438, 222);
this.treeView1.TabIndex = 0;
this.treeView1.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseDoubleClick);
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// localTabPage
//
this.localTabPage.Controls.Add(this.localListView);
this.localTabPage.Location = new System.Drawing.Point(4, 22);
this.localTabPage.Margin = new System.Windows.Forms.Padding(2);
this.localTabPage.Name = "localTabPage";
this.localTabPage.Padding = new System.Windows.Forms.Padding(2);
this.localTabPage.Size = new System.Drawing.Size(469, 249);
this.localTabPage.TabIndex = 0;
this.localTabPage.Text = "Local";
this.localTabPage.UseVisualStyleBackColor = true;
this.localTabPage.Click += new System.EventHandler(this.localTabPage_Click);
//
// localListView
//
this.localListView.BackgroundImageTiled = true;
this.localListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ArtifactNameHeader,
this.versionHeader});
this.localListView.Location = new System.Drawing.Point(16, 15);
this.localListView.Margin = new System.Windows.Forms.Padding(2);
this.localListView.Name = "localListView";
this.localListView.Size = new System.Drawing.Size(438, 220);
this.localListView.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.localListView.TabIndex = 0;
this.localListView.UseCompatibleStateImageBehavior = false;
this.localListView.SelectedIndexChanged += new System.EventHandler(this.localListView_SelectedIndexChanged);
this.localListView.DoubleClick += new System.EventHandler(this.localListView_DoubleClick);
//
// ArtifactNameHeader
//
this.ArtifactNameHeader.Text = "Artifact Name";
this.ArtifactNameHeader.Width = 240;
//
// versionHeader
//
this.versionHeader.Text = "Version";
this.versionHeader.Width = 120;
//
// artifactTabControl
//
this.artifactTabControl.Controls.Add(this.localTabPage);
this.artifactTabControl.Controls.Add(this.remoteTabPage);
this.artifactTabControl.Controls.Add(this.ConfigureTab);
this.artifactTabControl.Location = new System.Drawing.Point(9, 10);
this.artifactTabControl.Margin = new System.Windows.Forms.Padding(2);
this.artifactTabControl.Name = "artifactTabControl";
this.artifactTabControl.SelectedIndex = 0;
this.artifactTabControl.Size = new System.Drawing.Size(477, 275);
this.artifactTabControl.TabIndex = 0;
this.artifactTabControl.SelectedIndexChanged += new System.EventHandler(this.artifactTabControl_SelectedIndexChanged);
//
// ConfigureTab
//
this.ConfigureTab.Controls.Add(this.UpdateLabel);
this.ConfigureTab.Controls.Add(this.RepoCombo);
this.ConfigureTab.Controls.Add(this.checkBoxSnapshot);
this.ConfigureTab.Controls.Add(this.checkBoxRelease);
this.ConfigureTab.Controls.Add(this.update);
this.ConfigureTab.Controls.Add(this.label1);
this.ConfigureTab.Location = new System.Drawing.Point(4, 22);
this.ConfigureTab.Name = "ConfigureTab";
this.ConfigureTab.Padding = new System.Windows.Forms.Padding(3);
this.ConfigureTab.Size = new System.Drawing.Size(469, 249);
this.ConfigureTab.TabIndex = 2;
this.ConfigureTab.Text = "Configure Repository";
this.ConfigureTab.UseVisualStyleBackColor = true;
this.ConfigureTab.Click += new System.EventHandler(this.ConfigureTab_Click);
//
// UpdateLabel
//
this.UpdateLabel.AutoSize = true;
this.UpdateLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.UpdateLabel.Location = new System.Drawing.Point(66, 183);
this.UpdateLabel.Name = "UpdateLabel";
this.UpdateLabel.Size = new System.Drawing.Size(0, 20);
this.UpdateLabel.TabIndex = 11;
//
// RepoCombo
//
this.RepoCombo.FormattingEnabled = true;
this.RepoCombo.Location = new System.Drawing.Point(56, 77);
this.RepoCombo.Name = "RepoCombo";
this.RepoCombo.Size = new System.Drawing.Size(329, 21);
this.RepoCombo.TabIndex = 10;
this.RepoCombo.SelectedIndexChanged += new System.EventHandler(this.RepoCombo_SelectedIndexChanged);
//
// checkBoxSnapshot
//
this.checkBoxSnapshot.AutoSize = true;
this.checkBoxSnapshot.Location = new System.Drawing.Point(194, 138);
this.checkBoxSnapshot.Margin = new System.Windows.Forms.Padding(2);
this.checkBoxSnapshot.Name = "checkBoxSnapshot";
this.checkBoxSnapshot.Size = new System.Drawing.Size(118, 17);
this.checkBoxSnapshot.TabIndex = 9;
this.checkBoxSnapshot.Text = "Snapshots Enabled";
this.checkBoxSnapshot.UseVisualStyleBackColor = true;
//
// checkBoxRelease
//
this.checkBoxRelease.AutoSize = true;
this.checkBoxRelease.Location = new System.Drawing.Point(55, 138);
this.checkBoxRelease.Margin = new System.Windows.Forms.Padding(2);
this.checkBoxRelease.Name = "checkBoxRelease";
this.checkBoxRelease.Size = new System.Drawing.Size(112, 17);
this.checkBoxRelease.TabIndex = 8;
this.checkBoxRelease.Text = "Releases Enabled";
this.checkBoxRelease.UseVisualStyleBackColor = true;
//
// update
//
this.update.Location = new System.Drawing.Point(335, 135);
this.update.Margin = new System.Windows.Forms.Padding(2);
this.update.Name = "update";
this.update.Size = new System.Drawing.Size(50, 21);
this.update.TabIndex = 7;
this.update.Text = "Update";
this.update.UseVisualStyleBackColor = true;
this.update.Click += new System.EventHandler(this.update_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(53, 45);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(167, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Remote Repository Location";
//
// AddArtifactsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(508, 336);
this.Controls.Add(this.button2);
this.Controls.Add(this.addArtifact);
this.Controls.Add(this.artifactTabControl);
this.Margin = new System.Windows.Forms.Padding(2);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AddArtifactsForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Add Maven Artifact";
this.remoteTabPage.ResumeLayout(false);
this.localTabPage.ResumeLayout(false);
this.artifactTabControl.ResumeLayout(false);
this.ConfigureTab.ResumeLayout(false);
this.ConfigureTab.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button addArtifact;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TabPage remoteTabPage;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.TabPage localTabPage;
private System.Windows.Forms.ListView localListView;
private System.Windows.Forms.ColumnHeader ArtifactNameHeader;
private System.Windows.Forms.ColumnHeader versionHeader;
private System.Windows.Forms.TabControl artifactTabControl;
private TabPage ConfigureTab;
private CheckBox checkBoxSnapshot;
private CheckBox checkBoxRelease;
private Button update;
private Label label1;
private ComboBox RepoCombo;
private Label UpdateLabel;
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek and Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
using PHP.Core.Emit;
namespace PHP.Core.Emit
{
#region PlaceHolder, IPlace
/// <summary>
/// Type of the place where a value is stored.
/// </summary>
internal enum PlaceHolder
{
/// <summary>
/// The value has no storage, it is a direct value.
/// </summary>
None,
/// <summary>
/// The value is stored in a method argument.
/// </summary>
Argument,
/// <summary>
/// The value is stored in a local variable.
/// </summary>
Local,
/// <summary>
/// The value is stored in a field.
/// </summary>
Field
}
/// <summary>
/// Interface supported by storage places.
/// </summary>
public interface IPlace
{
/// <summary>
/// Emits code that loads the value from this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
void EmitLoad(ILEmitter il);
/// <summary>
/// Emits code that stores a value to this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
void EmitStore(ILEmitter il);
/// <summary>
/// Emits code that loads address of this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
void EmitLoadAddress(ILEmitter il);
/// <summary>
/// Gets whether the place has an address.
/// </summary>
bool HasAddress { get; }
/// <summary>
/// Returns the <see cref="Type"/> of the value stored in this storage place.
/// </summary>
Type PlaceType { get; }
}
#endregion
#region IndexedPlace
/// <summary>
/// A storage place that represents a local variable or a method argument given by their index,
/// or a direct integer value.
/// </summary>
internal sealed class IndexedPlace : IPlace
{
/// <summary>
/// The type of this place - can be either <see cref="PlaceHolder.None"/>, <see cref="PlaceHolder.Argument"/> or
/// <see cref="PlaceHolder.Local"/>.
/// </summary>
private PlaceHolder holder;
/// <summary>
/// Sets or gets the index (direct value).
/// </summary>
public int Index { get { return index; } set { index = value; } }
/// <summary>
/// The index/direct value.
/// </summary>
private int index;
/// <summary>
/// A special read-only <see cref="IndexedPlace"/> that loads <B>this</B> (0th argument).
/// </summary>
public static readonly IndexedPlace ThisArg = new IndexedPlace(PlaceHolder.Argument, 0);
/// <summary>
/// Creates a new <see cref="IndexedPlace"/> of a given type and with a given index/direct value.
/// </summary>
/// <param name="holder">The place type. Should be either <see cref="PlaceHolder.None"/>,
/// <see cref="PlaceHolder.Argument"/> or <see cref="PlaceHolder.Local"/>.</param>
/// <param name="index">The index (direct value).</param>
public IndexedPlace(PlaceHolder holder, int index)
{
if (holder != PlaceHolder.None && holder != PlaceHolder.Argument && holder != PlaceHolder.Local)
throw new ArgumentOutOfRangeException("holder");
this.holder = holder;
this.index = index;
}
/// <summary>
/// Creates a new <see cref="IndexedPlace"/> of given local variable.
/// </summary>
/// <param name="local">Local variable to be used.</param>
public IndexedPlace(LocalBuilder/*!*/local)
:this(PlaceHolder.Local, local.LocalIndex)
{
}
/// <summary>
/// Emits code that loads the value from this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitLoad(ILEmitter il)
{
switch (holder)
{
case PlaceHolder.Local: il.Ldloc(index); break;
case PlaceHolder.Argument: il.Ldarg(index); break;
case PlaceHolder.None: il.LdcI4(index); break;
}
}
/// <summary>
/// Emits code that loads address of this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitLoadAddress(ILEmitter il)
{
switch (holder)
{
case PlaceHolder.Local: il.Ldloca(index); break;
case PlaceHolder.Argument: il.Ldarga(index); break;
case PlaceHolder.None: throw new InvalidOperationException();
}
}
/// <summary>
/// Gets whether the place has an address.
/// </summary>
public bool HasAddress
{
get
{
switch (holder)
{
case PlaceHolder.Local:
case PlaceHolder.Argument: return true;
default: return false;
}
}
}
/// <summary>
/// Emits code that stores a value to this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitStore(ILEmitter il)
{
switch (holder)
{
case PlaceHolder.Local: il.Stloc(index); break;
case PlaceHolder.Argument: il.Starg(index); break;
case PlaceHolder.None: throw new InvalidOperationException();
}
}
/// <summary>
/// Returns the <see cref="Type"/> of the value stored in this storage place.
/// </summary>
public Type PlaceType
{
get
{
switch (holder)
{
case PlaceHolder.Local: throw new InvalidOperationException();
case PlaceHolder.Argument: throw new InvalidOperationException();
case PlaceHolder.None: return typeof(int);
}
return null;
}
}
}
#endregion
#region TokenPlace
/// <summary>
/// A read-only storage place that represents a metadata token.
/// </summary>
internal sealed class TokenPlace : IPlace
{
/// <summary>
/// Runtime representation of the token.
/// </summary>
private MemberInfo source;
/// <summary>
/// Creates a new <see cref="TokenPlace"/> given a <see cref="MemberInfo"/>.
/// </summary>
/// <param name="source">The <see cref="MemberInfo"/>.</param>
public TokenPlace(MemberInfo source)
{
this.source = source;
}
#region IPlace Members
/// <summary>
/// Emits code that loads the value from this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitLoad(ILEmitter il)
{
MethodInfo method;
FieldInfo field;
Type type;
if ((type = source as Type) != null)
{
il.Emit(OpCodes.Ldtoken, type);
}
else
if ((method = source as MethodInfo) != null)
{
il.Emit(OpCodes.Ldtoken, method);
}
else
if ((field = source as FieldInfo) != null)
{
il.Emit(OpCodes.Ldtoken, field);
}
else
throw new InvalidOperationException();
}
public void EmitLoadAddress(ILEmitter il)
{
throw new InvalidOperationException();
}
public bool HasAddress { get { return false; } }
/// <summary>
/// Emits code that stores a value to this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitStore(ILEmitter il)
{
throw new InvalidOperationException();
}
/// <summary>
/// Returns the <see cref="Type"/> of the value stored in this storage place.
/// </summary>
public Type PlaceType
{
get
{
MethodInfo method;
FieldInfo field;
Type type;
if ((type = source as Type) != null) return typeof(RuntimeTypeHandle);
else
if ((method = source as MethodInfo) != null) return typeof(RuntimeMethodHandle);
else
if ((field = source as FieldInfo) != null) return typeof(RuntimeFieldHandle);
else
throw new InvalidOperationException();
}
}
#endregion
}
#endregion
#region Place
/// <summary>
/// A storage place that represents a local variable, a field, or a property given by their
/// <see cref="LocalBuilder"/>, <see cref="FieldInfo"/>, or <see cref="PropertyInfo"/>.
/// </summary>
internal sealed class Place : IPlace
{
/// <summary>
/// Holder of the field or a <B>null</B> reference (a local variable or a static field).
/// </summary>
private IPlace holder;
/// <summary>
/// The <see cref="LocalBuilder"/>, <see cref="FieldInfo"/>, or <see cref="PropertyInfo"/>
/// where the value is stored.
/// </summary>
private object/*!*/ source;
#region Construction
/// <summary>
/// Creates a new <see cref="Place"/> given an <see cref="IPlace"/> representing an instance
/// and a <see cref="FieldInfo"/>.
/// </summary>
/// <param name="holder">The instance <see cref="IPlace"/> (<B>null</B> for static fields).</param>
/// <param name="field">The <see cref="FieldInfo"/>.</param>
public Place(IPlace holder, FieldInfo/*!*/ field)
{
Debug.Assert(field != null && (holder == null) == field.IsStatic);
this.holder = holder;
this.source = field;
}
/// <summary>
/// Creates a new <see cref="Place"/> given an <see cref="IPlace"/> representing an instance
/// and a <see cref="PropertyInfo"/>.
/// </summary>
/// <param name="holder">The instance <see cref="IPlace"/> (<B>null</B> for static properties).</param>
/// <param name="property">The <see cref="PropertyInfo"/>.</param>
public Place(IPlace holder, PropertyInfo/*!*/ property)
{
Debug.Assert(property != null && (holder == null) == property.GetGetMethod().IsStatic);
this.holder = holder;
this.source = property;
}
/// <summary>
/// Creates a new <see cref="Place"/> given a <see cref="LocalBuilder"/>.
/// </summary>
/// <param name="local">The <see cref="LocalBuilder"/>.</param>
public Place(LocalBuilder/*!*/ local)
{
Debug.Assert(local != null);
holder = null;
source = local;
}
#endregion
#region IPlace Members
/// <summary>
/// Emits code that loads the value from this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitLoad(ILEmitter il)
{
if (holder != null) il.Load(holder);
il.Load(source);
}
/// <summary>
/// Emits code that stores a value to this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitStore(ILEmitter il)
{
if (holder != null) il.Store(holder);
il.Store(source);
}
/// <summary>
/// Emits code that loads address of this storage place.
/// </summary>
/// <param name="il">The <see cref="ILEmitter"/> to emit the code to.</param>
public void EmitLoadAddress(ILEmitter il)
{
if (holder != null) il.Load(holder);
il.LoadAddress(source);
}
/// <summary>
/// Gets whether the place has an address.
/// </summary>
public bool HasAddress
{
get
{
return ILEmitter.HasAddress(source);
}
}
/// <summary>
/// Returns the <see cref="Type"/> of the value stored in this storage place.
/// </summary>
public Type PlaceType
{
get
{
LocalBuilder local;
FieldInfo field;
if ((local = source as LocalBuilder) != null)
return local.LocalType;
else if ((field = source as FieldInfo) != null)
return field.FieldType;
else
return ((PropertyInfo)source).PropertyType;
}
}
#endregion
}
#endregion
#region LiteralPlace
/// <summary>
/// Represents a literal.
/// </summary>
internal sealed class LiteralPlace : IPlace
{
/// <summary>
/// Literal represented by the place.
/// </summary>
private object literal;
/// <summary>
/// A special read-only <see cref="Place"/> that loads <B>null</B>.
/// </summary>
public static readonly LiteralPlace Null = new LiteralPlace(null);
public LiteralPlace(object literal)
{
this.literal = literal;
}
public void EmitLoad(ILEmitter il)
{
il.LoadLiteral(literal);
}
public void EmitStore(ILEmitter il)
{
throw new InvalidOperationException();
}
public void EmitLoadAddress(ILEmitter il)
{
throw new InvalidOperationException();
}
public bool HasAddress
{
get
{
return false;
}
}
public Type PlaceType
{
get
{
return (literal != null) ? literal.GetType() : null;
}
}
}
#endregion
#region MethodCallPlace
internal sealed class MethodCallPlace : IPlace
{
private MethodInfo/*!*/ methodInfo;
private IPlace[]/*!!*/ argumentPlaces;
private bool virtualCall;
public MethodCallPlace(MethodInfo/*!*/ methodInfo, bool virtualCall, params IPlace[]/*!!*/ argumentPlaces)
{
Debug.Assert(methodInfo.ReturnParameter.ParameterType != Types.Void);
this.methodInfo = methodInfo;
this.argumentPlaces = argumentPlaces;
this.virtualCall = virtualCall;
}
#region IPlace Members
public void EmitLoad(ILEmitter/*!*/ il)
{
for (int i = 0; i < argumentPlaces.Length; i++)
argumentPlaces[i].EmitLoad(il);
il.Emit((virtualCall) ? OpCodes.Callvirt : OpCodes.Call, methodInfo);
}
public void EmitStore(ILEmitter/*!*/ il)
{
throw new InvalidOperationException();
}
public void EmitLoadAddress(ILEmitter/*!*/ il)
{
throw new InvalidOperationException();
}
public bool HasAddress
{
get { return false; }
}
public Type/*!*/ PlaceType
{
get { return methodInfo.ReturnType; }
}
#endregion
}
#endregion
#region NewobjPlace
internal sealed class NewobjPlace : IPlace
{
private ConstructorInfo/*!*/ ctorInfo;
private IPlace[]/*!!*/ argumentPlaces;
public NewobjPlace(ConstructorInfo/*!*/ ctorInfo, params IPlace[]/*!!*/ argumentPlaces)
{
Debug.Assert(argumentPlaces.Length == ctorInfo.GetParameters().Length);
this.ctorInfo = ctorInfo;
this.argumentPlaces = argumentPlaces;
}
#region IPlace Members
public void EmitLoad(ILEmitter/*!*/ il)
{
for (int i = 0; i < argumentPlaces.Length; ++i)
argumentPlaces[i].EmitLoad(il);
il.Emit(OpCodes.Newobj, ctorInfo);
}
public void EmitStore(ILEmitter/*!*/ il)
{
throw new InvalidOperationException();
}
public void EmitLoadAddress(ILEmitter/*!*/ il)
{
throw new InvalidOperationException();
}
public bool HasAddress
{
get { return false; }
}
public Type/*!*/ PlaceType
{
get { return ctorInfo.DeclaringType; }
}
#endregion
}
#endregion
}
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Configuration;
using System.Reflection;
using log4net.Util;
using log4net.Repository;
namespace log4net.Core
{
/// <summary>
/// Static manager that controls the creation of repositories
/// </summary>
/// <remarks>
/// <para>
/// Static manager that controls the creation of repositories
/// </para>
/// <para>
/// This class is used by the wrapper managers (e.g. <see cref="log4net.LogManager"/>)
/// to provide access to the <see cref="ILogger"/> objects.
/// </para>
/// <para>
/// This manager also holds the <see cref="IRepositorySelector"/> that is used to
/// lookup and create repositories. The selector can be set either programmatically using
/// the <see cref="RepositorySelector"/> property, or by setting the <c>log4net.RepositorySelector</c>
/// AppSetting in the applications config file to the fully qualified type name of the
/// selector to use.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class LoggerManager
{
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances. Only static methods should be used.
/// </summary>
/// <remarks>
/// <para>
/// Private constructor to prevent instances. Only static methods should be used.
/// </para>
/// </remarks>
private LoggerManager()
{
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Hook the shutdown event
/// </summary>
/// <remarks>
/// <para>
/// On the full .NET runtime, the static constructor hooks up the
/// <c>AppDomain.ProcessExit</c> and <c>AppDomain.DomainUnload</c>> events.
/// These are used to shutdown the log4net system as the application exits.
/// </para>
/// </remarks>
static LoggerManager()
{
try
{
// Register the AppDomain events, note we have to do this with a
// method call rather than directly here because the AppDomain
// makes a LinkDemand which throws the exception during the JIT phase.
RegisterAppDomainEvents();
}
catch(System.Security.SecurityException)
{
LogLog.Debug("LoggerManager: Security Exception (ControlAppDomain LinkDemand) while trying "+
"to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+
"will not be called automatically when the AppDomain exits. It must be called "+
"programmatically.");
}
// Dump out our assembly version into the log if debug is enabled
LogLog.Debug(GetVersionInfo());
// Set the default repository selector
#if NETCF
s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
#else
// Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector'
string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector");
if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0)
{
// Resolve the config string into a Type
Type appRepositorySelectorType = null;
try
{
appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true);
}
catch(Exception ex)
{
LogLog.Error("LoggerManager: Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex);
}
if (appRepositorySelectorType != null)
{
// Create an instance of the RepositorySelectorType
object appRepositorySelectorObj = null;
try
{
appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType);
}
catch(Exception ex)
{
LogLog.Error("LoggerManager: Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex);
}
if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector)
{
s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj;
}
else
{
LogLog.Error("LoggerManager: RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector");
}
}
}
// Create the DefaultRepositorySelector if not configured above
if (s_repositorySelector == null)
{
s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
}
#endif
}
/// <summary>
/// Register for ProcessExit and DomainUnload events on the AppDomain
/// </summary>
/// <remarks>
/// <para>
/// This needs to be in a separate method because the events make
/// a LinkDemand for the ControlAppDomain SecurityPermission. Because
/// this is a LinkDemand it is demanded at JIT time. Therefore we cannot
/// catch the exception in the method itself, we have to catch it in the
/// caller.
/// </para>
/// </remarks>
private static void RegisterAppDomainEvents()
{
#if !NETCF
// ProcessExit seems to be fired if we are part of the default domain
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
// Otherwise DomainUnload is fired
AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload);
#endif
}
#endregion Static Constructor
#region Public Static Methods
/// <summary>
/// Return the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repository">the repository to lookup in</param>
/// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the repository specified
/// by the <paramref name="repository"/> argument.
/// </para>
/// </remarks>
[Obsolete("Use GetRepository instead of GetLoggerRepository")]
public static ILoggerRepository GetLoggerRepository(string repository)
{
return GetRepository(repository);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
[Obsolete("Use GetRepository instead of GetLoggerRepository")]
public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly)
{
return GetRepository(repositoryAssembly);
}
/// <summary>
/// Return the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repository">the repository to lookup in</param>
/// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the repository specified
/// by the <paramref name="repository"/> argument.
/// </para>
/// </remarks>
public static ILoggerRepository GetRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.GetRepository(repository);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
/// <remarks>
/// <para>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </para>
/// </remarks>
public static ILoggerRepository GetRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return RepositorySelector.GetRepository(repositoryAssembly);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the named logger does not exist in the
/// specified repository.
/// </returns>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified repository) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
public static ILogger Exists(string repository, string name)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repository).Exists(name);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the named logger does not exist in the
/// specified assembly's repository.
/// </returns>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified assembly's repository) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
public static ILogger Exists(Assembly repositoryAssembly, string name)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repositoryAssembly).Exists(name);
}
/// <summary>
/// Returns all the currently defined loggers in the specified repository.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <returns>All the defined loggers.</returns>
/// <remarks>
/// <para>
/// The root logger is <b>not</b> included in the returned array.
/// </para>
/// </remarks>
public static ILogger[] GetCurrentLoggers(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.GetRepository(repository).GetCurrentLoggers();
}
/// <summary>
/// Returns all the currently defined loggers in the specified assembly's repository.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>All the defined loggers.</returns>
/// <remarks>
/// <para>
/// The root logger is <b>not</b> included in the returned array.
/// </para>
/// </remarks>
public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers();
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
public static ILogger GetLogger(string repository, string name)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repository).GetLogger(name);
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
public static ILogger GetLogger(Assembly repositoryAssembly, string name)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name);
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Gets the logger for the fully qualified name of the type specified.
/// </para>
/// </remarks>
public static ILogger GetLogger(string repository, Type type)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
return RepositorySelector.GetRepository(repository).GetLogger(type.FullName);
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <param name="repositoryAssembly">the assembly to use to lookup the repository</param>
/// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Gets the logger for the fully qualified name of the type specified.
/// </para>
/// </remarks>
public static ILogger GetLogger(Assembly repositoryAssembly, Type type)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName);
}
/// <summary>
/// Shuts down the log4net system.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in all the
/// default repositories.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void Shutdown()
{
foreach(ILoggerRepository repository in GetAllRepositories())
{
repository.Shutdown();
}
}
/// <summary>
/// Shuts down the repository for the repository specified.
/// </summary>
/// <param name="repository">The repository to shutdown.</param>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the <paramref name="repository"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
RepositorySelector.GetRepository(repository).Shutdown();
}
/// <summary>
/// Shuts down the repository for the repository specified.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the repository. The repository is looked up using
/// the <paramref name="repositoryAssembly"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
RepositorySelector.GetRepository(repositoryAssembly).Shutdown();
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <param name="repository">The repository to reset.</param>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
RepositorySelector.GetRepository(repository).ResetConfiguration();
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration();
}
/// <summary>
/// Creates a repository with the specified name.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique amongst repositories.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b>
/// </para>
/// <para>
/// Creates the default type of <see cref="ILoggerRepository"/> which is a
/// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object.
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
[Obsolete("Use CreateRepository instead of CreateDomain")]
public static ILoggerRepository CreateDomain(string repository)
{
return CreateRepository(repository);
}
/// <summary>
/// Creates a repository with the specified name.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique amongst repositories.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// Creates the default type of <see cref="ILoggerRepository"/> which is a
/// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object.
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
public static ILoggerRepository CreateRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.CreateRepository(repository, null);
}
/// <summary>
/// Creates a repository with the specified name and repository type.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique to the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b>
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An Exception will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
[Obsolete("Use CreateRepository instead of CreateDomain")]
public static ILoggerRepository CreateDomain(string repository, Type repositoryType)
{
return CreateRepository(repository, repositoryType);
}
/// <summary>
/// Creates a repository with the specified name and repository type.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique to the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An Exception will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
public static ILoggerRepository CreateRepository(string repository, Type repositoryType)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (repositoryType == null)
{
throw new ArgumentNullException("repositoryType");
}
return RepositorySelector.CreateRepository(repository, repositoryType);
}
/// <summary>
/// Creates a repository for the specified assembly and repository type.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b>
/// </para>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// </remarks>
[Obsolete("Use CreateRepository instead of CreateDomain")]
public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType)
{
return CreateRepository(repositoryAssembly, repositoryType);
}
/// <summary>
/// Creates a repository for the specified assembly and repository type.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// </remarks>
public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (repositoryType == null)
{
throw new ArgumentNullException("repositoryType");
}
return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType);
}
/// <summary>
/// Gets an array of all currently defined repositories.
/// </summary>
/// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns>
/// <remarks>
/// <para>
/// Gets an array of all currently defined repositories.
/// </para>
/// </remarks>
public static ILoggerRepository[] GetAllRepositories()
{
return RepositorySelector.GetAllRepositories();
}
/// <summary>
/// Gets or sets the repository selector used by the <see cref="LogManager" />.
/// </summary>
/// <value>
/// The repository selector used by the <see cref="LogManager" />.
/// </value>
/// <remarks>
/// <para>
/// The repository selector (<see cref="IRepositorySelector"/>) is used by
/// the <see cref="LogManager"/> to create and select repositories
/// (<see cref="ILoggerRepository"/>).
/// </para>
/// <para>
/// The caller to <see cref="LogManager"/> supplies either a string name
/// or an assembly (if not supplied the assembly is inferred using
/// <see cref="Assembly.GetCallingAssembly()"/>).
/// </para>
/// <para>
/// This context is used by the selector to lookup a specific repository.
/// </para>
/// <para>
/// For the full .NET Framework, the default repository is <c>DefaultRepositorySelector</c>;
/// for the .NET Compact Framework <c>CompactRepositorySelector</c> is the default
/// repository.
/// </para>
/// </remarks>
public static IRepositorySelector RepositorySelector
{
get { return s_repositorySelector; }
set { s_repositorySelector = value; }
}
#endregion Public Static Methods
#region Private Static Methods
/// <summary>
/// Internal method to get pertinent version info.
/// </summary>
/// <returns>A string of version info.</returns>
private static string GetVersionInfo()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Grab the currently executing assembly
Assembly myAssembly = Assembly.GetExecutingAssembly();
// Build Up message
sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. ");
sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. ");
sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]");
#if (!SSCLI)
sb.Append(" on ").Append(Environment.OSVersion.ToString());
#endif
sb.Append(")");
return sb.ToString();
}
#if (!NETCF)
/// <summary>
/// Called when the <see cref="AppDomain.DomainUnload"/> event fires
/// </summary>
/// <param name="sender">the <see cref="AppDomain"/> that is exiting</param>
/// <param name="e">null</param>
/// <remarks>
/// <para>
/// Called when the <see cref="AppDomain.DomainUnload"/> event fires.
/// </para>
/// <para>
/// When the event is triggered the log4net system is <see cref="Shutdown()"/>.
/// </para>
/// </remarks>
private static void OnDomainUnload(object sender, EventArgs e)
{
Shutdown();
}
/// <summary>
/// Called when the <see cref="AppDomain.ProcessExit"/> event fires
/// </summary>
/// <param name="sender">the <see cref="AppDomain"/> that is exiting</param>
/// <param name="e">null</param>
/// <remarks>
/// <para>
/// Called when the <see cref="AppDomain.ProcessExit"/> event fires.
/// </para>
/// <para>
/// When the event is triggered the log4net system is <see cref="Shutdown()"/>.
/// </para>
/// </remarks>
private static void OnProcessExit(object sender, EventArgs e)
{
Shutdown();
}
#endif
#endregion Private Static Methods
#region Private Static Fields
/// <summary>
/// Initialize the default repository selector
/// </summary>
private static IRepositorySelector s_repositorySelector;
#endregion Private Static Fields
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Name used for AGGDECLs in the symbol table.
// AggregateSymbol - a symbol representing an aggregate type. These are classes,
// interfaces, and structs. Parent is a namespace or class. Children are methods,
// properties, and member variables, and types (including its own AGGTYPESYMs).
internal class AggregateSymbol : NamespaceOrAggregateSymbol
{
public Type AssociatedSystemType;
public Assembly AssociatedAssembly;
// The instance type. Created when first needed.
private AggregateType _atsInst;
private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused.
private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct.
private TypeArray _ifaces; // The explicit base interfaces for a class or interface.
private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces.
private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations.
private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes.
private TypeManager _pTypeManager; // This is so AGGTYPESYMs can instantiate their baseClass and ifacesAll members on demand.
// First UD conversion operator. This chain is for this type only (not base types).
// The hasConversion flag indicates whether this or any base types have UD conversions.
private MethodSymbol _pConvFirst;
// ------------------------------------------------------------------------
//
// Put members that are bits under here in a contiguous section.
//
// ------------------------------------------------------------------------
private AggKindEnum _aggKind;
// Where this came from - fabricated, source, import
// Fabricated AGGs have isSource == true but hasParseTree == false.
// N.B.: in incremental builds, it is quite possible for
// isSource==TRUE and hasParseTree==FALSE. Be
// sure you use the correct variable for what you are trying to do!
// Predefined
private bool _isPredefined; // A special predefined type.
private PredefinedType _iPredef; // index of the predefined type, if isPredefined.
// Flags
private bool _isAbstract; // Can it be instantiated?
private bool _isSealed; // Can it be derived from?
// Constructors
private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args
// User defined operators
private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate).
// When this is unset we don't know if we have conversions. When this
// is set it indicates if this type or any base type has user defined
// conversion operators
private bool? _hasConversion;
// ----------------------------------------------------------------------------
// AggregateSymbol
// ----------------------------------------------------------------------------
public AggregateSymbol GetBaseAgg()
{
return _pBaseClass?.OwningAggregate;
}
public AggregateType getThisType()
{
if (_atsInst == null)
{
Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested());
AggregateType pOuterType = isNested() ? GetOuterAgg().getThisType() : null;
_atsInst = _pTypeManager.GetAggregate(this, pOuterType, GetTypeVars());
}
//Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count);
return _atsInst;
}
public bool FindBaseAgg(AggregateSymbol agg)
{
for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg())
{
if (aggT == agg)
return true;
}
return false;
}
public NamespaceOrAggregateSymbol Parent => parent as NamespaceOrAggregateSymbol;
public bool isNested() => parent is AggregateSymbol;
public AggregateSymbol GetOuterAgg() => parent as AggregateSymbol;
public bool isPredefAgg(PredefinedType pt)
{
return _isPredefined && (PredefinedType)_iPredef == pt;
}
// ----------------------------------------------------------------------------
// The following are the Accessor functions for AggregateSymbol.
// ----------------------------------------------------------------------------
public AggKindEnum AggKind()
{
return (AggKindEnum)_aggKind;
}
public void SetAggKind(AggKindEnum aggKind)
{
// NOTE: When importing can demote types:
// - enums with no underlying type go to struct
// - delegates which are abstract or have no .ctor/Invoke method goto class
_aggKind = aggKind;
//An interface is always abstract
if (aggKind == AggKindEnum.Interface)
{
SetAbstract(true);
}
}
public bool IsClass()
{
return AggKind() == AggKindEnum.Class;
}
public bool IsDelegate()
{
return AggKind() == AggKindEnum.Delegate;
}
public bool IsInterface()
{
return AggKind() == AggKindEnum.Interface;
}
public bool IsStruct()
{
return AggKind() == AggKindEnum.Struct;
}
public bool IsEnum()
{
return AggKind() == AggKindEnum.Enum;
}
public bool IsValueType()
{
return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum;
}
public bool IsRefType()
{
return AggKind() == AggKindEnum.Class ||
AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate;
}
public bool IsStatic()
{
return (_isAbstract && _isSealed);
}
public bool IsAbstract()
{
return _isAbstract;
}
public void SetAbstract(bool @abstract)
{
_isAbstract = @abstract;
}
public bool IsPredefined()
{
return _isPredefined;
}
public void SetPredefined(bool predefined)
{
_isPredefined = predefined;
}
public PredefinedType GetPredefType()
{
return (PredefinedType)_iPredef;
}
public void SetPredefType(PredefinedType predef)
{
_iPredef = predef;
}
public bool IsSealed()
{
return _isSealed == true;
}
public void SetSealed(bool @sealed)
{
_isSealed = @sealed;
}
////////////////////////////////////////////////////////////////////////////////
public bool HasConversion(SymbolLoader pLoader)
{
pLoader.RuntimeBinderSymbolTable.AddConversionsForType(AssociatedSystemType);
if (!_hasConversion.HasValue)
{
// ok, we tried defining all the conversions, and we didn't get anything
// for this type. However, we will still think this type has conversions
// if it's base type has conversions.
_hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(pLoader);
}
return _hasConversion.Value;
}
////////////////////////////////////////////////////////////////////////////////
public void SetHasConversion()
{
_hasConversion = true;
}
////////////////////////////////////////////////////////////////////////////////
public bool HasPubNoArgCtor()
{
return _hasPubNoArgCtor == true;
}
public void SetHasPubNoArgCtor(bool hasPubNoArgCtor)
{
_hasPubNoArgCtor = hasPubNoArgCtor;
}
public bool IsSkipUDOps()
{
return _isSkipUDOps == true;
}
public void SetSkipUDOps(bool skipUDOps)
{
_isSkipUDOps = skipUDOps;
}
public TypeArray GetTypeVars()
{
return _typeVarsThis;
}
public void SetTypeVars(TypeArray typeVars)
{
if (typeVars == null)
{
_typeVarsThis = null;
_typeVarsAll = null;
}
else
{
TypeArray outerTypeVars;
if (GetOuterAgg() != null)
{
Debug.Assert(GetOuterAgg().GetTypeVars() != null);
Debug.Assert(GetOuterAgg().GetTypeVarsAll() != null);
outerTypeVars = GetOuterAgg().GetTypeVarsAll();
}
else
{
outerTypeVars = BSYMMGR.EmptyTypeArray();
}
_typeVarsThis = typeVars;
_typeVarsAll = _pTypeManager.ConcatenateTypeArrays(outerTypeVars, typeVars);
}
}
public TypeArray GetTypeVarsAll()
{
return _typeVarsAll;
}
public AggregateType GetBaseClass()
{
return _pBaseClass;
}
public void SetBaseClass(AggregateType baseClass)
{
_pBaseClass = baseClass;
}
public AggregateType GetUnderlyingType()
{
return _pUnderlyingType;
}
public void SetUnderlyingType(AggregateType underlyingType)
{
_pUnderlyingType = underlyingType;
}
public TypeArray GetIfaces()
{
return _ifaces;
}
public void SetIfaces(TypeArray ifaces)
{
_ifaces = ifaces;
}
public TypeArray GetIfacesAll()
{
return _ifacesAll;
}
public void SetIfacesAll(TypeArray ifacesAll)
{
_ifacesAll = ifacesAll;
}
public TypeManager GetTypeManager()
{
return _pTypeManager;
}
public void SetTypeManager(TypeManager typeManager)
{
_pTypeManager = typeManager;
}
public MethodSymbol GetFirstUDConversion()
{
return _pConvFirst;
}
public void SetFirstUDConversion(MethodSymbol conv)
{
_pConvFirst = conv;
}
public bool InternalsVisibleTo(Assembly assembly)
{
return _pTypeManager.InternalsVisibleTo(AssociatedAssembly, assembly);
}
}
}
| |
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using MessageStream2;
using System.IO;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayerServer
{
public class ClientHandler
{
//No point support IPv6 until KSP enables it on their windows builds.
private static TcpListener TCPServer;
private static ReadOnlyCollection<ClientObject> clients = new List<ClientObject>().AsReadOnly();
//When a client hits 100kb on the send queue, DMPServer will throw out old duplicate messages
private const int OPTIMIZE_QUEUE_LIMIT = 100 * 1024;
public static void ThreadMain()
{
try
{
clients = new List<ClientObject>().AsReadOnly();
Messages.WarpControl.Reset();
Messages.Chat.Reset();
Messages.ScreenshotLibrary.Reset();
SetupTCPServer();
while (Server.serverRunning)
{
//Process current clients
foreach (ClientObject client in clients)
{
Messages.Heartbeat.CheckHeartBeat(client);
}
//Check timers
NukeKSC.CheckTimer();
Dekessler.CheckTimer();
Messages.WarpControl.CheckTimer();
//Run plugin update
DMPPluginHandler.FireOnUpdate();
Thread.Sleep(10);
}
}
catch (Exception e)
{
DarkLog.Error("Fatal error thrown, exception: " + e);
Server.ShutDown("Crashed!");
}
try
{
long disconnectTime = DateTime.UtcNow.Ticks;
bool sendingHighPriotityMessages = true;
while (sendingHighPriotityMessages)
{
if ((DateTime.UtcNow.Ticks - disconnectTime) > 50000000)
{
DarkLog.Debug("Shutting down with " + Server.playerCount + " players, " + clients.Count + " connected clients");
break;
}
sendingHighPriotityMessages = false;
foreach (ClientObject client in clients)
{
if (client.authenticated && (client.sendMessageQueueHigh.Count > 0))
{
sendingHighPriotityMessages = true;
}
}
Thread.Sleep(10);
}
ShutdownTCPServer();
}
catch (Exception e)
{
DarkLog.Fatal("Fatal error thrown during shutdown, exception: " + e);
throw;
}
}
private static void SetupTCPServer()
{
try
{
IPAddress bindAddress = IPAddress.Parse(Settings.settingsStore.address);
TCPServer = new TcpListener(new IPEndPoint(bindAddress, Settings.settingsStore.port));
try
{
if (System.Net.Sockets.Socket.OSSupportsIPv6)
{
//Windows defaults to v6 only, but this option does not exist in mono so it has to be in a try/catch block along with the casted int.
if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix)
{
TCPServer.Server.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
}
}
}
catch
{
//Don't care - On linux and mac this throws because it's already set, and on windows it just works.
}
TCPServer.Start(4);
TCPServer.BeginAcceptTcpClient(new AsyncCallback(NewClientCallback), null);
}
catch (Exception e)
{
DarkLog.Normal("Error setting up server, Exception: " + e);
Server.serverRunning = false;
}
Server.serverStarting = false;
}
private static void ShutdownTCPServer()
{
TCPServer.Stop();
}
private static void NewClientCallback(IAsyncResult ar)
{
if (Server.serverRunning)
{
try
{
TcpClient newClient = TCPServer.EndAcceptTcpClient(ar);
SetupClient(newClient);
DarkLog.Normal("New client connection from " + newClient.Client.RemoteEndPoint);
}
catch
{
DarkLog.Normal("Error accepting client!");
}
TCPServer.BeginAcceptTcpClient(new AsyncCallback(NewClientCallback), null);
}
}
private static void SetupClient(TcpClient newClientConnection)
{
ClientObject newClientObject = new ClientObject();
newClientObject.subspace = Messages.WarpControl.GetLatestSubspace();
newClientObject.playerStatus = new PlayerStatus();
newClientObject.connectionStatus = ConnectionStatus.CONNECTED;
newClientObject.endpoint = newClientConnection.Client.RemoteEndPoint.ToString();
newClientObject.ipAddress = (newClientConnection.Client.RemoteEndPoint as IPEndPoint).Address;
//Keep the connection reference
newClientObject.connection = newClientConnection;
StartReceivingIncomingMessages(newClientObject);
StartSendingOutgoingMessages(newClientObject);
DMPPluginHandler.FireOnClientConnect(newClientObject);
Messages.Handshake.SendHandshakeChallange(newClientObject);
lock (clients)
{
List<ClientObject> newList = new List<ClientObject>(clients);
newList.Add(newClientObject);
clients = newList.AsReadOnly();
Server.playerCount = GetActiveClientCount();
Server.players = GetActivePlayerNames();
DarkLog.Debug("Online players is now: " + Server.playerCount + ", connected: " + clients.Count);
}
}
public static int GetActiveClientCount()
{
int authenticatedCount = 0;
foreach (ClientObject client in clients)
{
if (client.authenticated)
{
authenticatedCount++;
}
}
return authenticatedCount;
}
public static string GetActivePlayerNames()
{
string playerString = "";
foreach (ClientObject client in clients)
{
if (client.authenticated)
{
if (playerString != "")
{
playerString += ", ";
}
playerString += client.playerName;
}
}
return playerString;
}
private static void StartSendingOutgoingMessages(ClientObject client)
{
Thread clientSendThread = new Thread(new ParameterizedThreadStart(SendOutgoingMessages));
clientSendThread.IsBackground = true;
clientSendThread.Start(client);
}
//ParameterizedThreadStart takes an object
private static void SendOutgoingMessages(object client)
{
SendOutgoingMessages((ClientObject)client);
}
private static void SendOutgoingMessages(ClientObject client)
{
while (client.connectionStatus == ConnectionStatus.CONNECTED)
{
ServerMessage message = null;
if (message == null && client.sendMessageQueueHigh.Count > 0)
{
client.sendMessageQueueHigh.TryDequeue(out message);
}
//Don't send low or split during server shutdown.
if (Server.serverRunning)
{
if (message == null && client.sendMessageQueueSplit.Count > 0)
{
client.sendMessageQueueSplit.TryDequeue(out message);
}
if (message == null && client.sendMessageQueueLow.Count > 0)
{
client.sendMessageQueueLow.TryDequeue(out message);
//Splits large messages to higher priority messages can get into the queue faster
SplitAndRewriteMessage(client, ref message);
}
}
if (message != null)
{
SendNetworkMessage(client, message);
}
else
{
//Give the chance for the thread to terminate
client.sendEvent.WaitOne(1000);
}
}
}
private static void SplitAndRewriteMessage(ClientObject client, ref ServerMessage message)
{
if (message == null)
{
return;
}
if (message.data == null)
{
return;
}
if (message.data.Length > Common.SPLIT_MESSAGE_LENGTH)
{
ServerMessage newSplitMessage = new ServerMessage();
newSplitMessage.type = ServerMessageType.SPLIT_MESSAGE;
int splitBytesLeft = message.data.Length;
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)message.type);
mw.Write<int>(message.data.Length);
byte[] firstSplit = new byte[Common.SPLIT_MESSAGE_LENGTH];
Array.Copy(message.data, 0, firstSplit, 0, Common.SPLIT_MESSAGE_LENGTH);
mw.Write<byte[]>(firstSplit);
splitBytesLeft -= Common.SPLIT_MESSAGE_LENGTH;
newSplitMessage.data = mw.GetMessageBytes();
//SPLIT_MESSAGE metadata header length.
client.bytesQueuedOut += 8;
client.sendMessageQueueSplit.Enqueue(newSplitMessage);
}
while (splitBytesLeft > 0)
{
ServerMessage currentSplitMessage = new ServerMessage();
currentSplitMessage.type = ServerMessageType.SPLIT_MESSAGE;
currentSplitMessage.data = new byte[Math.Min(splitBytesLeft, Common.SPLIT_MESSAGE_LENGTH)];
Array.Copy(message.data, message.data.Length - splitBytesLeft, currentSplitMessage.data, 0, currentSplitMessage.data.Length);
splitBytesLeft -= currentSplitMessage.data.Length;
//SPLIT_MESSAGE network frame header length.
client.bytesQueuedOut += 8;
client.sendMessageQueueSplit.Enqueue(currentSplitMessage);
}
client.sendMessageQueueSplit.TryDequeue(out message);
}
}
private static void SendNetworkMessage(ClientObject client, ServerMessage message)
{
//Write the send times down in SYNC_TIME_REPLY packets
if (message.type == ServerMessageType.SYNC_TIME_REPLY)
{
try
{
using (MessageWriter mw = new MessageWriter())
{
using (MessageReader mr = new MessageReader(message.data))
{
client.bytesQueuedOut += 8;
//Client send time
mw.Write<long>(mr.Read<long>());
//Server receive time
mw.Write<long>(mr.Read<long>());
//Server send time
mw.Write<long>(DateTime.UtcNow.Ticks);
message.data = mw.GetMessageBytes();
}
}
}
catch (Exception e)
{
DarkLog.Debug("Error rewriting SYNC_TIME packet, Exception " + e);
}
}
//Continue sending
byte[] messageBytes = Common.PrependNetworkFrame((int)message.type, message.data);
client.lastSendTime = Server.serverClock.ElapsedMilliseconds;
client.bytesQueuedOut -= messageBytes.Length;
client.bytesSent += messageBytes.Length;
if (client.connectionStatus == ConnectionStatus.CONNECTED)
{
try
{
client.connection.GetStream().Write(messageBytes, 0, messageBytes.Length);
}
catch (Exception e)
{
HandleDisconnectException("Send Network Message", client, e);
return;
}
}
DMPPluginHandler.FireOnMessageSent(client, message);
if (message.type == ServerMessageType.CONNECTION_END)
{
using (MessageReader mr = new MessageReader(message.data))
{
string reason = mr.Read<string>();
DarkLog.Normal("Disconnecting client " + client.playerName + ", sent CONNECTION_END (" + reason + ") to endpoint " + client.endpoint);
client.disconnectClient = true;
DisconnectClient(client);
}
}
if (message.type == ServerMessageType.HANDSHAKE_REPLY)
{
using (MessageReader mr = new MessageReader(message.data))
{
int response = mr.Read<int>();
string reason = mr.Read<string>();
if (response != 0)
{
DarkLog.Normal("Disconnecting client " + client.playerName + ", sent HANDSHAKE_REPLY (" + reason + ") to endpoint " + client.endpoint);
client.disconnectClient = true;
DisconnectClient(client);
}
}
}
}
private static void StartReceivingIncomingMessages(ClientObject client)
{
client.lastReceiveTime = Server.serverClock.ElapsedMilliseconds;
//Allocate byte for header
client.receiveMessage = new ClientMessage();
client.receiveMessage.data = new byte[8];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
try
{
client.connection.GetStream().BeginRead(client.receiveMessage.data, client.receiveMessage.data.Length - client.receiveMessageBytesLeft, client.receiveMessageBytesLeft, new AsyncCallback(ReceiveCallback), client);
}
catch (Exception e)
{
HandleDisconnectException("Start Receive", client, e);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
ClientObject client = (ClientObject)ar.AsyncState;
int bytesRead = 0;
try
{
bytesRead = client.connection.GetStream().EndRead(ar);
}
catch (Exception e)
{
HandleDisconnectException("ReceiveCallback", client, e);
return;
}
client.bytesReceived += bytesRead;
client.receiveMessageBytesLeft -= bytesRead;
if (client.receiveMessageBytesLeft == 0)
{
//We either have the header or the message data, let's do something
if (!client.isReceivingMessage)
{
//We have the header
using (MessageReader mr = new MessageReader(client.receiveMessage.data))
{
int messageType = mr.Read<int>();
int messageLength = mr.Read<int>();
if (messageType > (Enum.GetNames(typeof(ClientMessageType)).Length - 1))
{
//Malformed message, most likely from a non DMP-client.
Messages.ConnectionEnd.SendConnectionEnd(client, "Invalid DMP message. Disconnected.");
DarkLog.Normal("Invalid DMP message from " + client.endpoint);
//Returning from ReceiveCallback will break the receive loop and stop processing any further messages.
return;
}
client.receiveMessage.type = (ClientMessageType)messageType;
if (messageLength == 0)
{
//Null message, handle it.
client.receiveMessage.data = null;
HandleMessage(client, client.receiveMessage);
client.receiveMessage.type = 0;
client.receiveMessage.data = new byte[8];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
}
else
{
if (messageLength < Common.MAX_MESSAGE_SIZE)
{
client.isReceivingMessage = true;
client.receiveMessage.data = new byte[messageLength];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
}
else
{
//Malformed message, most likely from a non DMP-client.
Messages.ConnectionEnd.SendConnectionEnd(client, "Invalid DMP message. Disconnected.");
DarkLog.Normal("Invalid DMP message from " + client.endpoint);
//Returning from ReceiveCallback will break the receive loop and stop processing any further messages.
return;
}
}
}
}
else
{
//We have the message data to a non-null message, handle it
client.isReceivingMessage = false;
#if !DEBUG
try
{
#endif
HandleMessage(client, client.receiveMessage);
#if !DEBUG
}
catch (Exception e)
{
HandleDisconnectException("ReceiveCallback", client, e);
return;
}
#endif
client.receiveMessage.type = 0;
client.receiveMessage.data = new byte[8];
client.receiveMessageBytesLeft = client.receiveMessage.data.Length;
}
}
if (client.connectionStatus == ConnectionStatus.CONNECTED)
{
client.lastReceiveTime = Server.serverClock.ElapsedMilliseconds;
try
{
client.connection.GetStream().BeginRead(client.receiveMessage.data, client.receiveMessage.data.Length - client.receiveMessageBytesLeft, client.receiveMessageBytesLeft, new AsyncCallback(ReceiveCallback), client);
}
catch (Exception e)
{
HandleDisconnectException("ReceiveCallback", client, e);
return;
}
}
}
private static void HandleDisconnectException(string location, ClientObject client, Exception e)
{
lock (client.disconnectLock)
{
if (!client.disconnectClient && client.connectionStatus != ConnectionStatus.DISCONNECTED)
{
if (e.InnerException != null)
{
DarkLog.Normal("Client " + client.playerName + " disconnected in " + location + ", endpoint " + client.endpoint + ", error: " + e.Message + " (" + e.InnerException.Message + ")");
}
else
{
DarkLog.Normal("Client " + client.playerName + " disconnected in " + location + ", endpoint " + client.endpoint + ", error: " + e.Message);
}
}
DisconnectClient(client);
}
}
internal static void DisconnectClient(ClientObject client)
{
lock (client.disconnectLock)
{
//Remove clients from list
if (clients.Contains(client))
{
List<ClientObject> newList = new List<ClientObject>(clients);
newList.Remove(client);
clients = newList.AsReadOnly();
Server.playerCount = GetActiveClientCount();
Server.players = GetActivePlayerNames();
DarkLog.Debug("Online players is now: " + Server.playerCount + ", connected: " + clients.Count);
if (!Settings.settingsStore.keepTickingWhileOffline && clients.Count == 0)
{
Messages.WarpControl.HoldSubspace();
}
Messages.WarpControl.DisconnectPlayer(client.playerName);
}
//Disconnect
if (client.connectionStatus != ConnectionStatus.DISCONNECTED)
{
DMPPluginHandler.FireOnClientDisconnect(client);
if (client.playerName != null)
{
Messages.Chat.RemovePlayer(client.playerName);
}
client.connectionStatus = ConnectionStatus.DISCONNECTED;
if (client.authenticated)
{
ServerMessage newMessage = new ServerMessage();
newMessage.type = ServerMessageType.PLAYER_DISCONNECT;
using (MessageWriter mw = new MessageWriter())
{
mw.Write<string>(client.playerName);
newMessage.data = mw.GetMessageBytes();
}
SendToAll(client, newMessage, true);
LockSystem.fetch.ReleasePlayerLocks(client.playerName);
}
try
{
if (client.connection != null)
{
client.connection.GetStream().Close();
client.connection.Close();
}
}
catch (Exception e)
{
DarkLog.Debug("Error closing client connection: " + e.Message);
}
Server.lastPlayerActivity = Server.serverClock.ElapsedMilliseconds;
}
}
}
internal static void HandleMessage(ClientObject client, ClientMessage message)
{
//Prevent plugins from dodging SPLIT_MESSAGE. If they are modified, every split message will be broken.
if (message.type != ClientMessageType.SPLIT_MESSAGE)
{
DMPPluginHandler.FireOnMessageReceived(client, message);
if (message.handled)
{
//a plugin has handled this message and requested suppression of the default DMP behavior
return;
}
}
//Clients can only send HEARTBEATS, HANDSHAKE_REQUEST or CONNECTION_END's until they are authenticated.
if (!client.authenticated && !(message.type == ClientMessageType.HEARTBEAT || message.type == ClientMessageType.HANDSHAKE_RESPONSE || message.type == ClientMessageType.CONNECTION_END))
{
Messages.ConnectionEnd.SendConnectionEnd(client, "You must authenticate before attempting to send a " + message.type.ToString() + " message");
return;
}
#if !DEBUG
try
{
#endif
switch (message.type)
{
case ClientMessageType.HEARTBEAT:
//Don't do anything for heartbeats, they just keep the connection alive
break;
case ClientMessageType.HANDSHAKE_RESPONSE:
Messages.Handshake.HandleHandshakeResponse(client, message.data);
break;
case ClientMessageType.CHAT_MESSAGE:
Messages.Chat.HandleChatMessage(client, message.data);
break;
case ClientMessageType.PLAYER_STATUS:
Messages.PlayerStatus.HandlePlayerStatus(client, message.data);
break;
case ClientMessageType.PLAYER_COLOR:
Messages.PlayerColor.HandlePlayerColor(client, message.data);
break;
case ClientMessageType.SCENARIO_DATA:
Messages.ScenarioData.HandleScenarioModuleData(client, message.data);
break;
case ClientMessageType.SYNC_TIME_REQUEST:
Messages.SyncTimeRequest.HandleSyncTimeRequest(client, message.data);
break;
case ClientMessageType.KERBALS_REQUEST:
Messages.KerbalsRequest.HandleKerbalsRequest(client);
break;
case ClientMessageType.KERBAL_PROTO:
Messages.KerbalProto.HandleKerbalProto(client, message.data);
break;
case ClientMessageType.VESSELS_REQUEST:
Messages.VesselRequest.HandleVesselsRequest(client, message.data);
break;
case ClientMessageType.VESSEL_PROTO:
Messages.VesselProto.HandleVesselProto(client, message.data);
break;
case ClientMessageType.VESSEL_UPDATE:
Messages.VesselUpdate.HandleVesselUpdate(client, message.data);
break;
case ClientMessageType.VESSEL_REMOVE:
Messages.VesselRemove.HandleVesselRemoval(client, message.data);
break;
case ClientMessageType.CRAFT_LIBRARY:
Messages.CraftLibrary.HandleCraftLibrary(client, message.data);
break;
case ClientMessageType.SCREENSHOT_LIBRARY:
Messages.ScreenshotLibrary.HandleScreenshotLibrary(client, message.data);
break;
case ClientMessageType.FLAG_SYNC:
Messages.FlagSync.HandleFlagSync(client, message.data);
break;
case ClientMessageType.PING_REQUEST:
Messages.PingRequest.HandlePingRequest(client, message.data);
break;
case ClientMessageType.MOTD_REQUEST:
Messages.MotdRequest.HandleMotdRequest(client);
break;
case ClientMessageType.WARP_CONTROL:
Messages.WarpControl.HandleWarpControl(client, message.data);
break;
case ClientMessageType.LOCK_SYSTEM:
Messages.LockSystem.HandleLockSystemMessage(client, message.data);
break;
case ClientMessageType.MOD_DATA:
Messages.ModData.HandleModDataMessage(client, message.data);
break;
case ClientMessageType.SPLIT_MESSAGE:
Messages.SplitMessage.HandleSplitMessage(client, message.data);
break;
case ClientMessageType.CONNECTION_END:
Messages.ConnectionEnd.HandleConnectionEnd(client, message.data);
break;
default:
DarkLog.Debug("Unhandled message type " + message.type);
Messages.ConnectionEnd.SendConnectionEnd(client, "Unhandled message type " + message.type);
#if DEBUG
throw new NotImplementedException("Message type not implemented");
#else
break;
#endif
}
#if !DEBUG
}
catch (Exception e)
{
DarkLog.Debug("Error handling " + message.type + " from " + client.playerName + ", exception: " + e);
Messages.ConnectionEnd.SendConnectionEnd(client, "Server failed to process " + message.type + " message");
}
#endif
}
//Call with null client to send to all clients. Also called from Dekessler and NukeKSC.
public static void SendToAll(ClientObject ourClient, ServerMessage message, bool highPriority)
{
foreach (ClientObject otherClient in clients)
{
if (ourClient != otherClient)
{
SendToClient(otherClient, message, highPriority);
}
}
}
//Call with null client to send to all clients. Auto selects wether to use the compressed or decompressed message.
public static void SendToAllAutoCompressed(ClientObject ourClient, ServerMessage compressed, ServerMessage decompressed, bool highPriority)
{
foreach (ClientObject otherClient in clients)
{
if (ourClient != otherClient)
{
if (otherClient.compressionEnabled && (compressed != null))
{
SendToClient(otherClient, compressed, highPriority);
}
else
{
SendToClient(otherClient, decompressed, highPriority);
}
}
}
}
public static void SendToClient(ClientObject client, ServerMessage message, bool highPriority)
{
//Because we dodge the queue, we need to lock it up again...
lock (client.sendLock)
{
if (message == null)
{
return;
}
//All messages have an 8 byte header
client.bytesQueuedOut += 8;
if (message.data != null)
{
//Count the payload if we have one.
client.bytesQueuedOut += message.data.Length;
}
if (highPriority)
{
client.sendMessageQueueHigh.Enqueue(message);
}
else
{
client.sendMessageQueueLow.Enqueue(message);
//If we need to optimize
if (client.bytesQueuedOut > OPTIMIZE_QUEUE_LIMIT)
{
//And we haven't optimized in the last 5 seconds
long currentTime = DateTime.UtcNow.Ticks;
long optimizedBytes = 0;
if ((currentTime - client.lastQueueOptimizeTime) > 50000000)
{
client.lastQueueOptimizeTime = currentTime;
DarkLog.Debug("Optimizing " + client.playerName + " (" + client.bytesQueuedOut + " bytes queued)");
//Create a temporary filter list
List<ServerMessage> oldClientMessagesToSend = new List<ServerMessage>();
List<ServerMessage> newClientMessagesToSend = new List<ServerMessage>();
//Steal all the messages from the queue and put them into a list
ServerMessage stealMessage = null;
while (client.sendMessageQueueLow.TryDequeue(out stealMessage))
{
oldClientMessagesToSend.Add(stealMessage);
}
//Clear the client send queue
List<string> seenProtovesselUpdates = new List<string>();
List<string> seenPositionUpdates = new List<string>();
//Iterate backwards over the list
oldClientMessagesToSend.Reverse();
foreach (ServerMessage currentMessage in oldClientMessagesToSend)
{
if (currentMessage.type != ServerMessageType.VESSEL_PROTO && currentMessage.type != ServerMessageType.VESSEL_UPDATE)
{
//Message isn't proto or position, don't skip it.
newClientMessagesToSend.Add(currentMessage);
}
else
{
//Message is proto or position
if (currentMessage.type == ServerMessageType.VESSEL_PROTO)
{
using (MessageReader mr = new MessageReader(currentMessage.data))
{
//Don't care about the send time, it's already the latest in the queue.
mr.Read<double>();
string vesselID = mr.Read<string>();
if (!seenProtovesselUpdates.Contains(vesselID))
{
seenProtovesselUpdates.Add(vesselID);
newClientMessagesToSend.Add(currentMessage);
}
else
{
optimizedBytes += 8 + currentMessage.data.Length;
}
}
}
if (currentMessage.type == ServerMessageType.VESSEL_UPDATE)
{
using (MessageReader mr = new MessageReader(currentMessage.data))
{
//Don't care about the send time, it's already the latest in the queue.
mr.Read<double>();
string vesselID = mr.Read<string>();
if (!seenPositionUpdates.Contains(vesselID))
{
seenPositionUpdates.Add(vesselID);
newClientMessagesToSend.Add(currentMessage);
}
else
{
//8 byte message header plus payload
optimizedBytes += 8 + currentMessage.data.Length;
}
}
}
}
}
//Flip it back to the right order
newClientMessagesToSend.Reverse();
foreach (ServerMessage putBackMessage in newClientMessagesToSend)
{
client.sendMessageQueueLow.Enqueue(putBackMessage);
}
float optimizeTime = (DateTime.UtcNow.Ticks - currentTime) / 10000f;
client.bytesQueuedOut -= optimizedBytes;
DarkLog.Debug("Optimized " + optimizedBytes + " bytes in " + Math.Round(optimizeTime, 3) + " ms.");
}
}
}
client.sendEvent.Set();
}
}
public static ClientObject[] GetClients()
{
List<ClientObject> returnArray = new List<ClientObject>(clients);
return returnArray.ToArray();
}
public static bool ClientConnected(ClientObject client)
{
return clients.Contains(client);
}
public static ClientObject GetClientByName(string playerName)
{
ClientObject findClient = null;
foreach (ClientObject testClient in clients)
{
if (testClient.authenticated && testClient.playerName == playerName)
{
findClient = testClient;
break;
}
}
return findClient;
}
public static ClientObject GetClientByIP(IPAddress ipAddress)
{
ClientObject findClient = null;
foreach (ClientObject testClient in clients)
{
if (testClient.authenticated && testClient.ipAddress == ipAddress)
{
findClient = testClient;
break;
}
}
return findClient;
}
public static ClientObject GetClientByPublicKey(string publicKey)
{
ClientObject findClient = null;
foreach (ClientObject testClient in clients)
{
if (testClient.authenticated && testClient.publicKey == publicKey)
{
findClient = testClient;
break;
}
}
return findClient;
}
}
public class ClientObject
{
public bool authenticated;
public byte[] challange;
public string playerName = "Unknown";
public string clientVersion;
public bool isBanned;
public IPAddress ipAddress;
public string publicKey;
//subspace tracking
public int subspace = -1;
public float subspaceRate = 1f;
//vessel tracking
public string activeVessel = "";
//connection
public string endpoint;
public TcpClient connection;
//Send buffer
public long lastSendTime;
public ConcurrentQueue<ServerMessage> sendMessageQueueHigh = new ConcurrentQueue<ServerMessage>();
public ConcurrentQueue<ServerMessage> sendMessageQueueSplit = new ConcurrentQueue<ServerMessage>();
public ConcurrentQueue<ServerMessage> sendMessageQueueLow = new ConcurrentQueue<ServerMessage>();
public long lastReceiveTime;
public bool disconnectClient;
//Receive buffer
public bool isReceivingMessage;
public int receiveMessageBytesLeft;
public ClientMessage receiveMessage;
//Receive split buffer
public bool isReceivingSplitMessage;
public int receiveSplitMessageBytesLeft;
public ClientMessage receiveSplitMessage;
//State tracking
public ConnectionStatus connectionStatus;
public PlayerStatus playerStatus;
public float[] playerColor;
//Network traffic tracking
public long bytesQueuedOut = 0;
public long bytesSent = 0;
public long bytesReceived = 0;
public long lastQueueOptimizeTime = 0;
//Send lock
public AutoResetEvent sendEvent = new AutoResetEvent(false);
public object sendLock = new object();
public object disconnectLock = new object();
//Compression
public bool compressionEnabled = false;
}
}
| |
/*
* 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.Reflection;
using log4net;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.CoreModules.World.Terrain
{
public abstract class TerrainModifier : ITerrainModifier
{
protected ITerrainModule m_module;
protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected TerrainModifier(ITerrainModule module)
{
m_module = module;
}
public abstract string ModifyTerrain(ITerrainChannel map, string[] args);
public abstract string GetUsage();
public abstract double operate(double[,] map, TerrainModifierData data, int x, int y);
protected String parseParameters(string[] args, out TerrainModifierData data)
{
string val;
string arg;
string result;
data = new TerrainModifierData();
data.shape = String.Empty;
data.bevel = String.Empty;
data.dx = 0;
data.dy = 0;
if (args.Length < 4)
{
result = "Usage: " + GetUsage();
}
else
{
result = this.parseFloat(args[3], out data.elevation);
}
if (result == String.Empty)
{
int index = 3;
while(++index < args.Length && result == String.Empty)
{
arg = args[index];
// check for shape
if (arg.StartsWith("-rec=") || arg.StartsWith("-ell="))
{
if (data.shape != String.Empty)
{
result = "Only 1 '-rec' or '-ell' parameter is permitted.";
}
else
{
data.shape = arg.StartsWith("-ell=") ? "ellipse" : "rectangle";
val = arg.Substring(arg.IndexOf("=") + 1);
string[] coords = val.Split(new char[] {','});
if ((coords.Length < 3) || (coords.Length > 4))
{
result = String.Format("Bad format for shape parameter {0}", arg);
}
else
{
result = this.parseInt(coords[0], out data.x0);
if (result == String.Empty)
{
result = this.parseInt(coords[1], out data.y0);
}
if (result == String.Empty)
{
result = this.parseInt(coords[2], out data.dx);
}
if (result == String.Empty)
{
if (coords.Length == 4)
{
result = this.parseInt(coords[3], out data.dy);
}
else
{
data.dy = data.dx;
}
}
if (result == String.Empty)
{
if ((data.dx <= 0) || (data.dy <= 0))
{
result = "Shape sizes must be positive integers";
}
}
else
{
result = String.Format("Bad value in shape parameters {0}", arg);
}
}
}
}
else if (arg.StartsWith("-taper="))
{
if (data.bevel != String.Empty)
{
result = "Only 1 '-taper' parameter is permitted.";
}
else
{
data.bevel = "taper";
val = arg.Substring(arg.IndexOf("=") + 1);
result = this.parseFloat(val, out data.bevelevation);
if (result != String.Empty)
{
result = String.Format("Bad format for taper parameter {0}", arg);
}
}
}
else
{
result = String.Format("Unrecognized parameter {0}", arg);
}
}
}
return result;
}
protected string parseFloat(String s, out float f)
{
string result;
double d;
if (Double.TryParse(s, out d))
{
try
{
f = (float)d;
result = String.Empty;
}
catch(InvalidCastException)
{
result = String.Format("{0} is invalid", s);
f = -1.0f;
}
}
else
{
f = -1.0f;
result = String.Format("{0} is invalid", s);
}
return result;
}
protected string parseInt(String s, out int i)
{
string result;
if (Int32.TryParse(s, out i))
{
result = String.Empty;
}
else
{
result = String.Format("{0} is invalid", s);
}
return result;
}
protected void applyModification(ITerrainChannel map, TerrainModifierData data)
{
bool[,] mask;
int xMax;
int yMax;
int xMid;
int yMid;
if (data.shape == "ellipse")
{
mask = this.ellipticalMask(data.dx, data.dy);
xMax = mask.GetLength(0);
yMax = mask.GetLength(1);
xMid = xMax / 2 + xMax % 2;
yMid = yMax / 2 + yMax % 2;
}
else
{
mask = this.rectangularMask(data.dx, data.dy);
xMax = mask.GetLength(0);
yMax = mask.GetLength(1);
xMid = 0;
yMid = 0;
}
// m_log.DebugFormat("Apply {0} mask {1}x{2} @ {3},{4}", data.shape, xMax, yMax, xMid, yMid);
double[,] buffer = map.GetDoubles();
int yDim = yMax;
while(--yDim >= 0)
{
int yPos = data.y0 + yDim - yMid;
if ((yPos >= 0) && (yPos < map.Height))
{
int xDim = xMax;
while(--xDim >= 0)
{
int xPos = data.x0 + xDim - xMid;
if ((xPos >= 0) && (xPos < map.Width) && (mask[xDim, yDim]))
{
double endElevation = this.operate(buffer, data, xPos, yPos);
map[xPos, yPos] = endElevation;
}
}
}
}
}
protected double computeBevel(TerrainModifierData data, int x, int y)
{
int deltaX;
int deltaY;
int xMax;
int yMax;
double factor;
if (data.bevel == "taper")
{
if (data.shape == "ellipse")
{
deltaX = x - data.x0;
deltaY = y - data.y0;
xMax = data.dx;
yMax = data.dy;
factor = (double)((deltaX * deltaX) + (deltaY * deltaY));
factor /= ((xMax * xMax) + (yMax * yMax));
}
else
{
// pyramid
xMax = data.dx / 2 + data.dx % 2;
yMax = data.dy / 2 + data.dy % 2;
deltaX = Math.Abs(data.x0 + xMax - x);
deltaY = Math.Abs(data.y0 + yMax - y);
factor = Math.Max(((double)(deltaY) / yMax), ((double)(deltaX) / xMax));
}
}
else
{
factor = 0.0;
}
return factor;
}
private bool[,] rectangularMask(int xSize, int ySize)
{
bool[,] mask = new bool[xSize, ySize];
int yPos = ySize;
while(--yPos >= 0)
{
int xPos = xSize;
while(--xPos >= 0)
{
mask[xPos, yPos] = true;
}
}
return mask;
}
/*
* Fast ellipse-based derivative of Bresenham algorithm.
* https://web.archive.org/web/20120225095359/http://homepage.smc.edu/kennedy_john/belipse.pdf
*/
private bool[,] ellipticalMask(int xRadius, int yRadius)
{
long twoASquared = 2L * xRadius * xRadius;
long twoBSquared = 2L * yRadius * yRadius;
bool[,] mask = new bool[2 * xRadius + 1, 2 * yRadius + 1];
long ellipseError = 0L;
long stoppingX = twoBSquared * xRadius;
long stoppingY = 0L;
long xChange = yRadius * yRadius * (1L - 2L * xRadius);
long yChange = xRadius * xRadius;
int xPos = xRadius;
int yPos = 0;
// first set of points
while(stoppingX >= stoppingY)
{
int yUpper = yRadius + yPos;
int yLower = yRadius - yPos;
// fill in the mask
int xNow = xPos;
while(xNow >= 0)
{
mask[xRadius + xNow, yUpper] = true;
mask[xRadius - xNow, yUpper] = true;
mask[xRadius + xNow, yLower] = true;
mask[xRadius - xNow, yLower] = true;
--xNow;
}
yPos++;
stoppingY += twoASquared;
ellipseError += yChange;
yChange += twoASquared;
if ((2L * ellipseError + xChange) > 0L)
{
xPos--;
stoppingX -= twoBSquared;
ellipseError += xChange;
xChange += twoBSquared;
}
}
// second set of points
xPos = 0;
yPos = yRadius;
xChange = yRadius * yRadius;
yChange = xRadius * xRadius * (1L - 2L * yRadius);
ellipseError = 0L;
stoppingX = 0L;
stoppingY = twoASquared * yRadius;
while(stoppingX <= stoppingY)
{
int xUpper = xRadius + xPos;
int xLower = xRadius - xPos;
// fill in the mask
int yNow = yPos;
while(yNow >= 0)
{
mask[xUpper, yRadius + yNow] = true;
mask[xUpper, yRadius - yNow] = true;
mask[xLower, yRadius + yNow] = true;
mask[xLower, yRadius - yNow] = true;
--yNow;
}
xPos++;
stoppingX += twoBSquared;
ellipseError += xChange;
xChange += twoBSquared;
if ((2L * ellipseError + yChange) > 0L)
{
yPos--;
stoppingY -= twoASquared;
ellipseError += yChange;
yChange += twoASquared;
}
}
return mask;
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
// Allow to manage different GUI Styles without conflict
//==============================================================================
$SceneEditor_DropSinglePosition = "";
$SceneEditor_AddObjectLastZ = true;
$SceneEditor_AddObjectCurrentSel = true;
//==============================================================================
// CHeck for custom drop setting, if not the WorldEditor will use it dropType
// When $SceneEd_SkipEditorDrop is true, the WorldEditor dropSelection is skip
// and position is set from script
function Scene::getCreateObjectPosition() {
%focusPoint = LocalClientConnection.getControlObject().getLookAtPoint();
$SceneEd_SkipEditorDrop = true;
if ($SceneEditor_DropSinglePosition !$= "")
%dropPos = $SceneEditor_DropSinglePosition;
else if (Scene.dropMode $= "currentSel" && isObject(EWorldEditor.getSelectedObject(0)))
%dropPos = EWorldEditor.getSelectedObject(0).position;
else if (Scene.dropMode $= "currentSel" )
warnLog("Can't drop object at current selection, because nothing is selected");
//else if( %focusPoint $= "" && strFind(strlwr(EWorldEditor.droptype),"toterrain"))
// %dropPos = "0 0 0";
$SceneEditor_DropSinglePosition = "";
if (%dropPos !$= "")
return %dropPos;
%position = getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 );
if (%position.z !$= "" && Scene.dropMode $= "currentSelZ") {
%position = getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 );
if ($WorldEditor_LastSelZ !$= "")
%position.z = $WorldEditor_LastSelZ;
return %position;
}
$SceneEd_SkipEditorDrop = false;
return %position;
}
//------------------------------------------------------------------------------
//==============================================================================
// CHeck for custom drop setting, if not the WorldEditor will use it dropType
// When $SceneEd_SkipEditorDrop is true, the WorldEditor dropSelection is skip
// and position is set from script
function Scene::getCreateObjectTransform() {
%position = Scene.getCreateObjectPosition();
%transform = %position SPC "1 0 0 0";
if (!$Cfg_Scene_IgnoreDropSelRotation && (Scene.dropMode $= "currentSel" || Scene.dropMode $= "currentSelZ")){
%selRot = EWorldEditor.getSelectedObject(0).rotation;
%transform = %position SPC %selRot;
logd("Dropping object at selected rotation:",%selRot);
}
return %transform;
}
//------------------------------------------------------------------------------
//==============================================================================
function Scene::onObjectCreated( %this, %objId,%noDrop ) {
// Can we submit an undo action?
if ( isObject( %objId ) )
MECreateUndoAction::submit( %objId );
SceneEditorTree.clearSelection();
EWorldEditor.clearSelection();
EWorldEditor.selectObject( %objId );
if (!%noDrop)
EWorldEditor.dropSelection( true );
}
//------------------------------------------------------------------------------
//==============================================================================
function Scene::onFinishCreateObject( %this, %objId ) {
%activeGroup = Scene.getActiveSimGroup();
%activeGroup.add( %objId );
if( %objId.isMemberOfClass( "SceneObject" )||%objId.isMemberOfClass( "Trigger" ) ) {
%objId.position = %this.getCreateObjectPosition();
%transform = %this.getCreateObjectTransform();
%position = getWords(%transform,0,2);
%rotation = getWords(%transform,3,6);
%objId.position = %position;
%objId.rotation = %rotation;
//flush new position
%objId.setTransform( %objId.getTransform() );
}
%this.onObjectCreated( %objId );
}
//------------------------------------------------------------------------------
//==============================================================================
//Scene.createSimGroup();
function Scene::createSimGroup( %this ) {
if ( !$missionRunning )
return;
%addToGroup = Scene.getActiveSimGroup();
%objId = new SimGroup() {
internalName = getUniqueInternalName( %this.objectGroup.internalName, MissionGroup, true );
position = %this.getCreateObjectPosition();
parentGroup = %addToGroup;
};
}
//------------------------------------------------------------------------------
//==============================================================================
function Scene::createStatic( %this, %file,%trans ) {
if ( !$missionRunning )
return;
%addToGroup = Scene.getActiveSimGroup();
if (%trans !$= ""){
%transform = %trans;
$SceneEd_SkipEditorDrop = true;
}
else
%transform = %this.getCreateObjectTransform();
%position = getWords(%transform,0,2);
%rotation = getWords(%transform,3,6);
%objId = new TSStatic() {
shapeName = %file;
position = %position;
rotation = %rotation;
parentGroup = %addToGroup;
};
%objId.setTransform(%transform);
%this.onObjectCreated( %objId,$SceneEd_SkipEditorDrop );
}
//------------------------------------------------------------------------------
//==============================================================================
function Scene::createPrefab( %this, %file ) {
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
Scene.setNewObjectGroup( MissionGroup );
%transform = %this.getCreateObjectTransform();
%position = getWords(%transform,0,2);
%rotation = getWords(%transform,3,6);
%objId = new Prefab() {
filename = %file;
position = %position;
rotation = %rotation;
parentGroup = %this.objectGroup;
};
if( isObject( %objId ) )
%this.onFinishCreateObject( %objId );
//%this.onObjectCreated( %objId );
}
//------------------------------------------------------------------------------
//==============================================================================
function Scene::createObject( %this, %cmd ) {
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
Scene.setNewObjectGroup( MissionGroup );
devLog("SkipDrop",$SceneEd_SkipEditorDrop,"Pos",%objId.position);
pushInstantGroup();
%objId = eval(%cmd);
popInstantGroup();
if( isObject( %objId ) )
%this.onFinishCreateObject( %objId );
return %objId;
}
//------------------------------------------------------------------------------
//==============================================================================
function Scene::createMesh( %this, %file ) {
if ( !$missionRunning )
return;
%addToGroup = Scene.getActiveSimGroup();
%transform = %this.getCreateObjectTransform();
%position = getWords(%transform,0,2);
%rotation = getWords(%transform,3,6);
%objId = new TSStatic() {
shapeName = %file;
position = %position;
rotation = %rotation;
parentGroup = %addToGroup;
internalName = fileBase(%file);
allowPlayerStep = $Cfg_TSStatic_Default_AllowPlayerStep;
};
// Get a TSShapeConstructor for this object (use the ShapeLab
// utility functions to create one if it does not already exist).
%shapePath = getObjectShapeFile( %objId );
%shape = findConstructor( %shapePath );
if ( !isObject( %shape ) )
%shape = createConstructor( %shapePath );
if ( !isObject( %shape ) )
{
echo( "Failed to create TSShapeConstructor for " @ %objId.getId() );
}else {
if ( %shape.getNodeIndex( "NoWalk" ) !$= "-1" ){
info("Node NoWalk found on object:",%objId,"allowPlayerStep set to false");
%objId.allowPlayerStep = false;
}
}
%this.onObjectCreated( %objId,$SceneEd_SkipEditorDrop );
}
//------------------------------------------------------------------------------
function genericCreateObject( %class ) {
if ( !isClass( %class ) ) {
warn( "createObject( " @ %class @ " ) - Was not a valid class." );
return;
}
%cmd = "return new " @ %class @ "();";
%obj = Scene.createObject( %cmd );
// In case the caller wants it.
return %obj;
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using CURLcode = Interop.Http.CURLcode;
using CURLINFO = Interop.Http.CURLINFO;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private static class SslProvider
{
private static readonly Interop.Http.SslCtxCallback s_sslCtxCallback = SslCtxCallback;
private static readonly Interop.Ssl.AppVerifyCallback s_sslVerifyCallback = VerifyCertChain;
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
{
Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual);
// Create a client certificate provider if client certs may be used.
X509Certificate2Collection clientCertificates = easy._handler._clientCertificates;
ClientCertificateProvider certProvider =
clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic
clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs
null; // manual without certs
IntPtr userPointer = IntPtr.Zero;
if (certProvider != null)
{
// The client cert provider needs to be passed through to the callback, and thus
// we create a GCHandle to keep it rooted. This handle needs to be cleaned up
// when the request has completed, and a simple and pay-for-play way to do that
// is by cleaning it up in a continuation off of the request.
userPointer = GCHandle.ToIntPtr(certProvider._gcHandle);
easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider,
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
// Register the callback with libcurl. We need to register even if there's no user-provided
// server callback and even if there are no client certificates, because we support verifying
// server certificates against more than those known to OpenSSL.
CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer);
switch (answer)
{
case CURLcode.CURLE_OK:
// We successfully registered. If we'll be invoking a user-provided callback to verify the server
// certificate as part of that, disable libcurl's verification of the host name. The user's callback
// needs to be given the opportunity to examine the cert, and our logic will determine whether
// the host name matches and will inform the callback of that.
if (easy._handler.ServerCertificateValidationCallback != null)
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the peer cert's hostname
// We don't change the SSL_VERIFYPEER setting, as setting it to 0 will cause
// SSL and libcurl to ignore the result of the server callback.
}
// The allowed SSL protocols will be set in the configuration callback.
break;
case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior
case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later
// It's ok if we failed to register the callback if all of the defaults are in play
// with relation to handling of certificates. But if that's not the case, failing to
// register the callback will result in those options not being factored in, which is
// a significant enough error that we need to fail.
EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported: {0}", answer, easy: easy);
if (certProvider != null ||
easy._handler.ServerCertificateValidationCallback != null ||
easy._handler.CheckCertificateRevocationList)
{
throw new PlatformNotSupportedException(
SR.Format(SR.net_http_unix_invalid_certcallback_option, CurlVersionDescription, CurlSslVersionDescription));
}
// Since there won't be a callback to configure the allowed SSL protocols, configure them here.
SetSslVersion(easy);
break;
default:
ThrowIfCURLEError(answer);
break;
}
}
private static void SetSslVersion(EasyRequest easy, IntPtr sslCtx = default(IntPtr))
{
// Get the requested protocols.
SslProtocols protocols = easy._handler.SslProtocols;
if (protocols == SslProtocols.None)
{
// Let libcurl use its defaults if None is set.
return;
}
// We explicitly disallow choosing SSL2/3. Make sure they were filtered out.
Debug.Assert((protocols & ~SecurityProtocol.AllowedSecurityProtocols) == 0,
"Disallowed protocols should have been filtered out.");
// libcurl supports options for either enabling all of the TLS1.* protocols or enabling
// just one of them; it doesn't currently support enabling two of the three, e.g. you can't
// pick TLS1.1 and TLS1.2 but not TLS1.0, but you can select just TLS1.2.
Interop.Http.CurlSslVersion curlSslVersion;
switch (protocols)
{
case SslProtocols.Tls:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_0;
break;
case SslProtocols.Tls11:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_1;
break;
case SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1_2;
break;
case SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12:
curlSslVersion = Interop.Http.CurlSslVersion.CURL_SSLVERSION_TLSv1;
break;
default:
throw new NotSupportedException(SR.net_securityprotocolnotsupported);
}
try
{
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSLVERSION, (long)curlSslVersion);
}
catch (CurlException e) when (e.HResult == (int)CURLcode.CURLE_UNKNOWN_OPTION)
{
throw new NotSupportedException(SR.net_securityprotocolnotsupported, e);
}
}
private static CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer)
{
EasyRequest easy;
if (!TryGetEasyRequest(curl, out easy))
{
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
// Configure the SSL protocols allowed.
SslProtocols protocols = easy._handler.SslProtocols;
if (protocols == SslProtocols.None)
{
// If None is selected, let OpenSSL use its defaults, but with SSL2/3 explicitly disabled.
// Since the shim/OpenSSL work on a disabling system, where any protocols for which bits aren't
// set are disabled, we set all of the bits other than those we want disabled.
#pragma warning disable 0618 // the enum values are obsolete
protocols = ~(SslProtocols.Ssl2 | SslProtocols.Ssl3);
#pragma warning restore 0618
}
Interop.Ssl.SetProtocolOptions(sslCtx, protocols);
// Configure the SSL server certificate verification callback.
Interop.Ssl.SslCtxSetCertVerifyCallback(sslCtx, s_sslVerifyCallback, curl);
// If a client certificate provider was provided, also configure the client certificate callback.
if (userPointer != IntPtr.Zero)
{
try
{
// Provider is passed in via a GCHandle. Get the provider, which contains
// the client certificate callback delegate.
GCHandle handle = GCHandle.FromIntPtr(userPointer);
ClientCertificateProvider provider = (ClientCertificateProvider)handle.Target;
if (provider == null)
{
Debug.Fail($"Expected non-null provider in {nameof(SslCtxCallback)}");
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
// Register the callback.
Interop.Ssl.SslCtxSetClientCertCallback(sslCtx, provider._callback);
EventSourceTrace("Registered client certificate callback.", easy: easy);
}
catch (Exception e)
{
Debug.Fail($"Exception in {nameof(SslCtxCallback)}", e.ToString());
return CURLcode.CURLE_ABORTED_BY_CALLBACK;
}
}
return CURLcode.CURLE_OK;
}
private static bool TryGetEasyRequest(IntPtr curlPtr, out EasyRequest easy)
{
Debug.Assert(curlPtr != IntPtr.Zero, "curlPtr is not null");
IntPtr gcHandlePtr;
CURLcode getInfoResult = Interop.Http.EasyGetInfoPointer(curlPtr, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
if (getInfoResult == CURLcode.CURLE_OK)
{
return MultiAgent.TryGetEasyRequestFromGCHandle(gcHandlePtr, out easy);
}
Debug.Fail($"Failed to get info on a completing easy handle: {getInfoResult}");
easy = null;
return false;
}
private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr)
{
EasyRequest easy;
if (!TryGetEasyRequest(curlPtr, out easy))
{
EventSourceTrace("Could not find associated easy request: {0}", curlPtr);
return 0;
}
using (var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false))
{
IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
if (IntPtr.Zero == leafCertPtr)
{
EventSourceTrace("Invalid certificate pointer", easy: easy);
return 0;
}
using (X509Certificate2 leafCert = new X509Certificate2(leafCertPtr))
{
// We need to respect the user's server validation callback if there is one. If there isn't one,
// we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
// as OpenSSL doesn't do that.
if (easy._handler.ServerCertificateValidationCallback == null &&
!easy._handler.CheckCertificateRevocationList)
{
// Start by using the default verification provided directly by OpenSSL.
// If it succeeds in verifying the cert chain, we're done. Employing this instead of
// our custom implementation will need to be revisited if we ever decide to introduce a
// "disallowed" store that enables users to "untrust" certs the system trusts.
int sslResult = Interop.Crypto.X509VerifyCert(storeCtx);
if (sslResult == 1)
{
return 1;
}
// X509_verify_cert can return < 0 in the case of programmer error
Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult);
}
// Either OpenSSL verification failed, or there was a server validation callback.
// Either way, fall back to manual and more expensive verification that includes
// checking the user's certs (not just the system store ones as OpenSSL does).
X509Certificate2[] otherCerts;
int otherCertsCount = 0;
bool success;
using (X509Chain chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
{
if (extraStack.IsInvalid)
{
otherCerts = Array.Empty<X509Certificate2>();
}
else
{
int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
otherCerts = new X509Certificate2[extraSize];
for (int i = 0; i < extraSize; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
if (certPtr != IntPtr.Zero)
{
X509Certificate2 cert = new X509Certificate2(certPtr);
otherCerts[otherCertsCount++] = cert;
chain.ChainPolicy.ExtraStore.Add(cert);
}
}
}
}
var serverCallback = easy._handler._serverCertificateValidationCallback;
if (serverCallback == null)
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: false, hostName: null); // libcurl already verifies the host name
success = errors == SslPolicyErrors.None;
}
else
{
SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
try
{
success = serverCallback(easy._requestMessage, leafCert, chain, errors);
}
catch (Exception exc)
{
EventSourceTrace("Server validation callback threw exception: {0}", exc, easy: easy);
easy.FailRequest(exc);
success = false;
}
}
}
for (int i = 0; i < otherCertsCount; i++)
{
otherCerts[i].Dispose();
}
return success ? 1 : 0;
}
}
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public class MegaBindInf
{
public float dist;
public int face;
public int i0;
public int i1;
public int i2;
public Vector3 bary;
public float weight;
public float area;
}
[System.Serializable]
public class MegaBindVert
{
public float weight;
public List<MegaBindInf> verts = new List<MegaBindInf>();
}
public struct MegaCloseFace
{
public int face;
public float dist;
}
[ExecuteInEditMode]
public class MegaWrap : MonoBehaviour
{
public float gap = 0.0f;
public float shrink = 1.0f;
public List<int> neededVerts = new List<int>();
public Vector3[] skinnedVerts;
public Mesh mesh = null;
public Vector3 offset = Vector3.zero;
public bool targetIsSkin = false;
public bool sourceIsSkin = false;
public int nomapcount = 0;
public Matrix4x4[] bindposes;
public BoneWeight[] boneweights;
public Transform[] bones;
public float size = 0.01f;
public int vertindex = 0;
public Vector3[] freeverts; // position for any vert with no attachments
public Vector3[] startverts;
public Vector3[] verts;
public MegaBindVert[] bindverts;
public MegaModifyObject target;
public float maxdist = 0.25f;
public int maxpoints = 4;
public bool WrapEnabled = true;
public MegaNormalMethod NormalMethod = MegaNormalMethod.Unity;
#if UNITY_5 || UNITY_2017
public bool UseBakedMesh = true;
#endif
[ContextMenu("Help")]
public void Help()
{
Application.OpenURL("http://www.west-racing.com/mf/?page_id=3709");
}
Vector4 Plane(Vector3 v1, Vector3 v2, Vector3 v3)
{
Vector3 normal = Vector4.zero;
normal.x = (v2.y - v1.y) * (v3.z - v1.z) - (v2.z - v1.z) * (v3.y - v1.y);
normal.y = (v2.z - v1.z) * (v3.x - v1.x) - (v2.x - v1.x) * (v3.z - v1.z);
normal.z = (v2.x - v1.x) * (v3.y - v1.y) - (v2.y - v1.y) * (v3.x - v1.x);
normal = normal.normalized;
return new Vector4(normal.x, normal.y, normal.z, -Vector3.Dot(v2, normal));
}
float PlaneDist(Vector3 p, Vector4 plane)
{
Vector3 n = plane;
return Vector3.Dot(n, p) + plane.w;
}
public float GetDistance(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
return MegaNearestPointTest.DistPoint3Triangle3Dbl(p, p0, p1, p2);
}
public float GetPlaneDistance(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector4 pl = Plane(p0, p1, p2);
return PlaneDist(p, pl);
}
public Vector3 MyBary(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 bary = Vector3.zero;
Vector3 normal = FaceNormal(p0, p1, p2);
float areaABC = Vector3.Dot(normal, Vector3.Cross((p1 - p0), (p2 - p0)));
float areaPBC = Vector3.Dot(normal, Vector3.Cross((p1 - p), (p2 - p)));
float areaPCA = Vector3.Dot(normal, Vector3.Cross((p2 - p), (p0 - p)));
bary.x = areaPBC / areaABC; // alpha
bary.y = areaPCA / areaABC; // beta
bary.z = 1.0f - bary.x - bary.y; // gamma
return bary;
}
public Vector3 MyBary1(Vector3 p, Vector3 a, Vector3 b, Vector3 c)
{
Vector3 v0 = b - a, v1 = c - a, v2 = p - a;
float d00 = Vector3.Dot(v0, v0);
float d01 = Vector3.Dot(v0, v1);
float d11 = Vector3.Dot(v1, v1);
float d20 = Vector3.Dot(v2, v0);
float d21 = Vector3.Dot(v2, v1);
float denom = d00 * d11 - d01 * d01;
float w = (d11 * d20 - d01 * d21) / denom;
float v = (d00 * d21 - d01 * d20) / denom;
float u = 1.0f - v - w;
return new Vector3(u, v, w);
}
public Vector3 CalcBary(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
return MyBary(p, p0, p1, p2);
}
public float CalcArea(Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 e1 = p1 - p0;
Vector3 e2 = p2 - p0;
Vector3 e3 = Vector3.Cross(e1, e2);
return 0.5f * e3.magnitude;
}
Vector3 e11 = Vector3.zero;
Vector3 e22 = Vector3.zero;
Vector3 cr = Vector3.zero;
public Vector3 FaceNormal(Vector3 p0, Vector3 p1, Vector3 p2)
{
//Vector3 e1 = p1 - p0;
//Vector3 e2 = p2 - p0;
e11.x = p1.x - p0.x;
e11.y = p1.y - p0.y;
e11.z = p1.z - p0.z;
e22.x = p2.x - p0.x;
e22.y = p2.y - p0.y;
e22.z = p2.z - p0.z;
//Vector3 e2 = p2 - p0;
cr.x = e11.y * e22.z - e22.y * e11.z;
cr.y = -(e11.x * e22.z - e22.x * e11.z); // * -1;
cr.z = e11.x * e22.y - e22.x * e11.y;
return cr; //Vector3.Cross(e11, e22);
}
static void CopyBlendShapes(Mesh mesh1, Mesh clonemesh)
{
#if UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6 || UNITY_2017
int bcount = mesh1.blendShapeCount; //GetBlendShapeFrameCount();
Vector3[] deltaverts = new Vector3[mesh1.vertexCount];
Vector3[] deltanorms = new Vector3[mesh1.vertexCount];
Vector3[] deltatans = new Vector3[mesh1.vertexCount];
for ( int j = 0; j < bcount; j++ )
{
int frames = mesh1.GetBlendShapeFrameCount(j);
string bname = mesh1.GetBlendShapeName(j);
for ( int f = 0; f < frames; f++ )
{
mesh1.GetBlendShapeFrameVertices(j, f, deltaverts, deltanorms, deltatans);
float weight = mesh1.GetBlendShapeFrameWeight(j, f);
clonemesh.AddBlendShapeFrame(bname, weight, deltaverts, deltanorms, deltatans);
}
}
#endif
}
public Mesh CloneMesh(Mesh m)
{
Mesh clonemesh = new Mesh();
clonemesh.vertices = m.vertices;
#if UNITY_5_0 || UNITY_5_1 || UNITY_5 || UNITY_2017
clonemesh.uv2 = m.uv2;
clonemesh.uv3 = m.uv3;
clonemesh.uv4 = m.uv4;
#else
clonemesh.uv1 = m.uv1;
clonemesh.uv2 = m.uv2;
#endif
clonemesh.uv = m.uv;
clonemesh.normals = m.normals;
clonemesh.tangents = m.tangents;
clonemesh.colors = m.colors;
clonemesh.subMeshCount = m.subMeshCount;
for ( int s = 0; s < m.subMeshCount; s++ )
clonemesh.SetTriangles(m.GetTriangles(s), s);
CopyBlendShapes(m, clonemesh);
clonemesh.boneWeights = m.boneWeights;
clonemesh.bindposes = m.bindposes;
clonemesh.name = m.name; // + "_copy";
clonemesh.RecalculateBounds();
return clonemesh;
}
[ContextMenu("Reset Mesh")]
public void ResetMesh()
{
if ( mesh )
{
mesh.vertices = startverts;
mesh.RecalculateBounds();
RecalcNormals();
//mesh.RecalculateNormals();
}
target = null;
bindverts = null;
}
public void SetMesh()
{
MeshFilter mf = GetComponent<MeshFilter>();
Mesh srcmesh = null;
if ( mf != null )
srcmesh = mf.sharedMesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
if ( smesh != null )
srcmesh = smesh.sharedMesh;
}
if ( srcmesh != null )
{
mesh = CloneMesh(srcmesh);
if ( mf )
mf.sharedMesh = mesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
smesh.sharedMesh = mesh;
}
}
}
public void Attach(MegaModifyObject modobj)
{
targetIsSkin = false;
sourceIsSkin = false;
if ( mesh && startverts != null )
mesh.vertices = startverts;
if ( modobj == null )
{
bindverts = null;
return;
}
nomapcount = 0;
if ( mesh )
mesh.vertices = startverts;
MeshFilter mf = GetComponent<MeshFilter>();
Mesh srcmesh = null;
if ( mf != null )
{
//skinned = false;
srcmesh = mf.mesh;
}
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
if ( smesh != null )
{
//skinned = true;
srcmesh = smesh.sharedMesh;
sourceIsSkin = true;
}
}
if ( srcmesh == null )
{
Debug.LogWarning("No Mesh found on the target object, make sure target has a mesh and MegaFiers modifier attached!");
return;
}
if ( mesh == null )
mesh = CloneMesh(srcmesh); //mf.mesh);
if ( mf )
mf.mesh = mesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
smesh.sharedMesh = mesh;
}
if ( sourceIsSkin == false )
{
SkinnedMeshRenderer tmesh = (SkinnedMeshRenderer)modobj.GetComponent(typeof(SkinnedMeshRenderer));
if ( tmesh != null )
{
targetIsSkin = true;
if ( !sourceIsSkin )
{
Mesh sm = tmesh.sharedMesh;
bindposes = sm.bindposes;
boneweights = sm.boneWeights;
bones = tmesh.bones;
skinnedVerts = sm.vertices; //new Vector3[sm.vertexCount];
}
}
}
if ( targetIsSkin )
{
if ( boneweights == null || boneweights.Length == 0 )
targetIsSkin = false;
}
neededVerts.Clear();
verts = mesh.vertices;
startverts = mesh.vertices;
freeverts = new Vector3[startverts.Length];
Vector3[] baseverts = modobj.verts; //basemesh.vertices;
int[] basefaces = modobj.tris; //basemesh.triangles;
bindverts = new MegaBindVert[verts.Length];
// matrix to get vertex into local space of target
Matrix4x4 tm = transform.localToWorldMatrix * modobj.transform.worldToLocalMatrix;
List<MegaCloseFace> closefaces = new List<MegaCloseFace>();
Vector3 p0 = Vector3.zero;
Vector3 p1 = Vector3.zero;
Vector3 p2 = Vector3.zero;
for ( int i = 0; i < verts.Length; i++ )
{
MegaBindVert bv = new MegaBindVert();
bindverts[i] = bv;
Vector3 p = tm.MultiplyPoint(verts[i]);
p = transform.TransformPoint(verts[i]);
p = modobj.transform.InverseTransformPoint(p);
freeverts[i] = p;
closefaces.Clear();
for ( int t = 0; t < basefaces.Length; t += 3 )
{
if ( targetIsSkin && !sourceIsSkin )
{
p0 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t]));
p1 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 1]));
p2 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 2]));
}
else
{
p0 = baseverts[basefaces[t]];
p1 = baseverts[basefaces[t + 1]];
p2 = baseverts[basefaces[t + 2]];
}
float dist = GetDistance(p, p0, p1, p2);
if ( Mathf.Abs(dist) < maxdist )
{
MegaCloseFace cf = new MegaCloseFace();
cf.dist = Mathf.Abs(dist);
cf.face = t;
bool inserted = false;
for ( int k = 0; k < closefaces.Count; k++ )
{
if ( cf.dist < closefaces[k].dist )
{
closefaces.Insert(k, cf);
inserted = true;
break;
}
}
if ( !inserted )
closefaces.Add(cf);
}
}
float tweight = 0.0f;
int maxp = maxpoints;
if ( maxp == 0 )
maxp = closefaces.Count;
for ( int j = 0; j < maxp; j++ )
{
if ( j < closefaces.Count )
{
int t = closefaces[j].face;
if ( targetIsSkin && !sourceIsSkin )
{
p0 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t]));
p1 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 1]));
p2 = modobj.transform.InverseTransformPoint(GetSkinPos(basefaces[t + 2]));
}
else
{
p0 = baseverts[basefaces[t]];
p1 = baseverts[basefaces[t + 1]];
p2 = baseverts[basefaces[t + 2]];
}
Vector3 normal = FaceNormal(p0, p1, p2);
float dist = closefaces[j].dist; //GetDistance(p, p0, p1, p2);
MegaBindInf bi = new MegaBindInf();
bi.dist = GetPlaneDistance(p, p0, p1, p2); //dist;
bi.face = t;
bi.i0 = basefaces[t];
bi.i1 = basefaces[t + 1];
bi.i2 = basefaces[t + 2];
bi.bary = CalcBary(p, p0, p1, p2);
bi.weight = 1.0f / (1.0f + dist);
bi.area = normal.magnitude * 0.5f; //CalcArea(baseverts[basefaces[t]], baseverts[basefaces[t + 1]], baseverts[basefaces[t + 2]]); // Could calc once at start
tweight += bi.weight;
bv.verts.Add(bi);
}
}
if ( maxpoints > 0 && maxpoints < bv.verts.Count )
bv.verts.RemoveRange(maxpoints, bv.verts.Count - maxpoints);
// Only want to calculate skin vertices we use
if ( !sourceIsSkin && targetIsSkin )
{
for ( int fi = 0; fi < bv.verts.Count; fi++ )
{
if ( !neededVerts.Contains(bv.verts[fi].i0) )
neededVerts.Add(bv.verts[fi].i0);
if ( !neededVerts.Contains(bv.verts[fi].i1) )
neededVerts.Add(bv.verts[fi].i1);
if ( !neededVerts.Contains(bv.verts[fi].i2) )
neededVerts.Add(bv.verts[fi].i2);
}
}
if ( tweight == 0.0f )
nomapcount++;
bv.weight = tweight;
}
}
void LateUpdate()
{
DoUpdate();
}
public Vector3 GetSkinPos(int i)
{
Vector3 pos = target.sverts[i];
Vector3 bpos = bindposes[boneweights[i].boneIndex0].MultiplyPoint(pos);
Vector3 p = bones[boneweights[i].boneIndex0].TransformPoint(bpos) * boneweights[i].weight0;
bpos = bindposes[boneweights[i].boneIndex1].MultiplyPoint(pos);
p += bones[boneweights[i].boneIndex1].TransformPoint(bpos) * boneweights[i].weight1;
bpos = bindposes[boneweights[i].boneIndex2].MultiplyPoint(pos);
p += bones[boneweights[i].boneIndex2].TransformPoint(bpos) * boneweights[i].weight2;
bpos = bindposes[boneweights[i].boneIndex3].MultiplyPoint(pos);
p += bones[boneweights[i].boneIndex3].TransformPoint(bpos) * boneweights[i].weight3;
return p;
}
Vector3 gcp = Vector3.zero;
public Vector3 GetCoordMine(Vector3 A, Vector3 B, Vector3 C, Vector3 bary)
{
//Vector3 p = Vector3.zero;
gcp.x = (bary.x * A.x) + (bary.y * B.x) + (bary.z * C.x);
gcp.y = (bary.x * A.y) + (bary.y * B.y) + (bary.z * C.y);
gcp.z = (bary.x * A.z) + (bary.y * B.z) + (bary.z * C.z);
return gcp;
}
SkinnedMeshRenderer tmesh;
#if UNITY_5 || UNITY_2017
Mesh bakedmesh = null;
#endif
void DoUpdate()
{
if ( WrapEnabled == false || target == null || bindverts == null ) //|| bindposes == null )
return;
if ( mesh == null )
SetMesh();
if ( mesh == null )
return;
if ( targetIsSkin && neededVerts != null && neededVerts.Count > 0 ) //|| (targetIsSkin && boneweights == null) )
{
if ( boneweights == null || tmesh == null )
{
tmesh = (SkinnedMeshRenderer)target.GetComponent(typeof(SkinnedMeshRenderer));
if ( tmesh != null )
{
if ( !sourceIsSkin )
{
Mesh sm = tmesh.sharedMesh;
bindposes = sm.bindposes;
bones = tmesh.bones;
boneweights = sm.boneWeights;
}
}
}
#if UNITY_5 || UNITY_2017
if ( tmesh == null )
tmesh = (SkinnedMeshRenderer)target.GetComponent(typeof(SkinnedMeshRenderer));
if ( UseBakedMesh )
{
if ( bakedmesh == null )
bakedmesh = new Mesh();
tmesh.BakeMesh(bakedmesh);
skinnedVerts = bakedmesh.vertices;
}
else
{
for ( int i = 0; i < neededVerts.Count; i++ )
skinnedVerts[neededVerts[i]] = GetSkinPos(neededVerts[i]);
}
#else
for ( int i = 0; i < neededVerts.Count; i++ )
skinnedVerts[neededVerts[i]] = GetSkinPos(neededVerts[i]);
#endif
}
Matrix4x4 stm = Matrix4x4.identity;
Vector3 p = Vector3.zero;
if ( targetIsSkin && !sourceIsSkin )
{
#if UNITY_5 || UNITY_2017
if ( UseBakedMesh )
stm = transform.worldToLocalMatrix * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
else
stm = transform.worldToLocalMatrix; // * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
#else
stm = transform.worldToLocalMatrix; // * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
#endif
for ( int i = 0; i < bindverts.Length; i++ )
{
if ( bindverts[i].verts.Count > 0 )
{
p = Vector3.zero;
float oow = 1.0f / bindverts[i].weight;
int cnt = bindverts[i].verts.Count;
for ( int j = 0; j < cnt; j++ )
{
MegaBindInf bi = bindverts[i].verts[j];
Vector3 p0 = skinnedVerts[bi.i0];
Vector3 p1 = skinnedVerts[bi.i1];
Vector3 p2 = skinnedVerts[bi.i2];
Vector3 cp = GetCoordMine(p0, p1, p2, bi.bary);
Vector3 norm = FaceNormal(p0, p1, p2);
float sq = 1.0f / Mathf.Sqrt(norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
float d = (bi.dist * shrink) + gap;
//cp += d * norm.x;
cp.x += d * norm.x * sq;
cp.y += d * norm.y * sq;
cp.z += d * norm.z * sq;
float bw = bi.weight * oow;
if ( j == 0 )
{
p.x = cp.x * bw;
p.y = cp.y * bw;
p.z = cp.z * bw;
}
else
{
p.x += cp.x * bw;
p.y += cp.y * bw;
p.z += cp.z * bw;
}
//cp += ((bi.dist * shrink) + gap) * norm.normalized;
//p += cp * (bi.weight / bindverts[i].weight);
}
Vector3 pp = stm.MultiplyPoint3x4(p);
verts[i].x = pp.x + offset.x;
verts[i].y = pp.y + offset.y;
verts[i].z = pp.z + offset.z;
//verts[i] = transform.InverseTransformPoint(p) + offset;
}
}
}
else
{
stm = transform.worldToLocalMatrix * target.transform.localToWorldMatrix; // * transform.worldToLocalMatrix;
//Matrix4x4 tm = target.transform.localToWorldMatrix;
for ( int i = 0; i < bindverts.Length; i++ )
{
if ( bindverts[i].verts.Count > 0 )
{
p = Vector3.zero;
float oow = 1.0f / bindverts[i].weight;
for ( int j = 0; j < bindverts[i].verts.Count; j++ )
{
MegaBindInf bi = bindverts[i].verts[j];
Vector3 p0 = target.sverts[bi.i0];
Vector3 p1 = target.sverts[bi.i1];
Vector3 p2 = target.sverts[bi.i2];
Vector3 cp = GetCoordMine(p0, p1, p2, bi.bary);
Vector3 norm = FaceNormal(p0, p1, p2);
float sq = 1.0f / Mathf.Sqrt(norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
float d = (bi.dist * shrink) + gap;
//cp += d * norm.x;
cp.x += d * norm.x * sq;
cp.y += d * norm.y * sq;
cp.z += d * norm.z * sq;
float bw = bi.weight * oow;
if ( j == 0 )
{
p.x = cp.x * bw;
p.y = cp.y * bw;
p.z = cp.z * bw;
}
else
{
p.x += cp.x * bw;
p.y += cp.y * bw;
p.z += cp.z * bw;
}
//cp += ((bi.dist * shrink) + gap) * norm.normalized;
//p += cp * (bi.weight / bindverts[i].weight);
}
}
else
p = freeverts[i]; //startverts[i];
Vector3 pp = stm.MultiplyPoint3x4(p);
verts[i].x = pp.x + offset.x;
verts[i].y = pp.y + offset.y;
verts[i].z = pp.z + offset.z;
//p = target.transform.TransformPoint(p);
//verts[i] = transform.InverseTransformPoint(p) + offset;
}
}
mesh.vertices = verts;
RecalcNormals();
mesh.RecalculateBounds();
}
public MegaNormMap[] mapping;
public int[] tris;
public Vector3[] facenorms;
public Vector3[] norms;
int[] FindFacesUsing(Vector3 p, Vector3 n)
{
List<int> faces = new List<int>();
Vector3 v = Vector3.zero;
for ( int i = 0; i < tris.Length; i += 3 )
{
v = verts[tris[i]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i]]) )
faces.Add(i / 3);
}
else
{
v = verts[tris[i + 1]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i + 1]]) )
faces.Add(i / 3);
}
else
{
v = verts[tris[i + 2]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i + 2]]) )
faces.Add(i / 3);
}
}
}
}
return faces.ToArray();
}
// Should call this from inspector when we change to mega
public void BuildNormalMapping(Mesh mesh, bool force)
{
if ( mapping == null || mapping.Length == 0 || force )
{
// so for each normal we have a vertex, so find all faces that share that vertex
tris = mesh.triangles;
norms = mesh.normals;
facenorms = new Vector3[tris.Length / 3];
mapping = new MegaNormMap[verts.Length];
for ( int i = 0; i < verts.Length; i++ )
{
mapping[i] = new MegaNormMap();
mapping[i].faces = FindFacesUsing(verts[i], norms[i]);
}
}
}
public void RecalcNormals()
{
if ( NormalMethod == MegaNormalMethod.Unity ) //|| mapping == null )
mesh.RecalculateNormals();
else
{
if ( mapping == null )
BuildNormalMapping(mesh, false);
RecalcNormals(mesh, verts);
}
}
public void RecalcNormals(Mesh ms, Vector3[] _verts)
{
int index = 0;
Vector3 v30 = Vector3.zero;
Vector3 v31 = Vector3.zero;
Vector3 v32 = Vector3.zero;
Vector3 va = Vector3.zero;
Vector3 vb = Vector3.zero;
for ( int f = 0; f < tris.Length; f += 3 )
{
v30 = _verts[tris[f]];
v31 = _verts[tris[f + 1]];
v32 = _verts[tris[f + 2]];
va.x = v31.x - v30.x;
va.y = v31.y - v30.y;
va.z = v31.z - v30.z;
vb.x = v32.x - v31.x;
vb.y = v32.y - v31.y;
vb.z = v32.z - v31.z;
v30.x = va.y * vb.z - va.z * vb.y;
v30.y = va.z * vb.x - va.x * vb.z;
v30.z = va.x * vb.y - va.y * vb.x;
// Uncomment this if you dont want normals weighted by poly size
//float l = v30.x * v30.x + v30.y * v30.y + v30.z * v30.z;
//l = 1.0f / Mathf.Sqrt(l);
//v30.x *= l;
//v30.y *= l;
//v30.z *= l;
facenorms[index++] = v30;
}
for ( int n = 0; n < norms.Length; n++ )
{
if ( mapping[n].faces.Length > 0 )
{
Vector3 norm = facenorms[mapping[n].faces[0]];
for ( int i = 1; i < mapping[n].faces.Length; i++ )
{
v30 = facenorms[mapping[n].faces[i]];
norm.x += v30.x;
norm.y += v30.y;
norm.z += v30.z;
}
float l = norm.x * norm.x + norm.y * norm.y + norm.z * norm.z;
l = 1.0f / Mathf.Sqrt(l);
norm.x *= l;
norm.y *= l;
norm.z *= l;
norms[n] = norm;
}
else
norms[n] = Vector3.up;
}
ms.normals = norms;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
datablock SFXProfile( MineArmedSound )
{
filename = "data/FPSGameplay/sound/weapons/mine_armed";
description = AudioClose3d;
preload = true;
};
datablock SFXProfile( MineSwitchinSound )
{
filename = "data/FPSGameplay/sound/weapons/wpn_proximitymine_switchin";
description = AudioClose3D;
preload = true;
};
datablock SFXProfile( MineTriggeredSound )
{
filename = "data/FPSGameplay/sound/weapons/mine_trigger";
description = AudioClose3d;
preload = true;
};
datablock ProximityMineData( ProxMine )
{
// ShapeBaseData fields
category = "Weapon";
shapeFile = "data/FPSGameplay/art/shapes/weapons/ProxMine/TP_ProxMine.DAE";
explosion = GrenadeLauncherExplosion;
// ItemData fields
sticky = true;
mass = 2;
elasticity = 0.2;
friction = 0.6;
simpleServerCollision = false;
// ProximityMineData fields
armingDelay = 3.5;
armingSound = MineArmedSound;
autoTriggerDelay = 0;
triggerOnOwner = true;
triggerRadius = 3.0;
triggerDelay = 0.45;
triggerSound = MineTriggeredSound;
explosionOffset = 0.1;
// dynamic fields
pickUpName = "a proximity mine";
description = "Proximity Mine";
maxInventory = 20;
image = ProxMineImage;
previewImage = 'mine.png';
reticle = 'blank';
zoomReticle = 'blank';
damageType = "MineDamage"; // type of damage applied to objects in radius
radiusDamage = 300; // amount of damage to apply to objects in radius
damageRadius = 8; // search radius to damage objects when exploding
areaImpulse = 2000; // magnitude of impulse to apply to objects in radius
};
datablock ShapeBaseImageData( ProxMineImage )
{
// Basic Item properties
shapeFile = "data/FPSGameplay/art/shapes/weapons/ProxMine/TP_ProxMine.DAE";
shapeFileFP = "data/FPSGameplay/art/shapes/weapons/ProxMine/FP_ProxMine.DAE";
imageAnimPrefix = "ProxMine";
imageAnimPrefixFP = "ProxMine";
// Specify mount point & offset for 3rd person, and eye offset
// for first person rendering.
mountPoint = 0;
firstPerson = true;
useEyeNode = true;
// When firing from a point offset from the eye, muzzle correction
// will adjust the muzzle vector to point to the eye LOS point.
// Since this weapon doesn't actually fire from the muzzle point,
// we need to turn this off.
correctMuzzleVector = false;
// Add the WeaponImage namespace as a parent, WeaponImage namespace
// provides some hooks into the inventory system.
class = "WeaponImage";
className = "WeaponImage";
// Projectiles and Ammo.
item = ProxMine;
// Shake camera while firing.
shakeCamera = false;
camShakeFreq = "0 0 0";
camShakeAmp = "0 0 0";
// Images have a state system which controls how the animations
// are run, which sounds are played, script callbacks, etc. This
// state system is downloaded to the client so that clients can
// predict state changes and animate accordingly. The following
// system supports basic ready->fire->reload transitions as
// well as a no-ammo->dryfire idle state.
// Initial start up state
stateName[0] = "Preactivate";
stateTransitionOnLoaded[0] = "Activate";
stateTransitionOnNoAmmo[0] = "Activate";
// Activating the gun. Called when the weapon is first
// mounted and there is ammo.
stateName[1] = "Activate";
stateTransitionGeneric0In[1] = "SprintEnter";
stateTransitionOnTimeout[1] = "Ready";
stateTimeoutValue[1] = 3.0;
stateSequence[1] = "switch_in";
stateShapeSequence[1] = "Reload";
stateSound[1] = MineSwitchinSound;
// Ready to fire, just waiting for the trigger
stateName[2] = "Ready";
stateTransitionGeneric0In[2] = "SprintEnter";
stateTransitionOnMotion[2] = "ReadyMotion";
stateTransitionOnTriggerDown[2] = "Fire";
stateScaleAnimation[2] = false;
stateScaleAnimationFP[2] = false;
stateSequence[2] = "idle";
// Ready to fire with player moving
stateName[3] = "ReadyMotion";
stateTransitionGeneric0In[3] = "SprintEnter";
stateTransitionOnNoMotion[3] = "Ready";
stateScaleAnimation[3] = false;
stateScaleAnimationFP[3] = false;
stateSequenceTransitionIn[3] = true;
stateSequenceTransitionOut[3] = true;
stateTransitionOnTriggerDown[3] = "Fire";
stateSequence[3] = "run";
// Wind up to throw the ProxMine
stateName[4] = "Fire";
stateTransitionGeneric0In[4] = "SprintEnter";
stateTransitionOnTimeout[4] = "Fire2";
stateTimeoutValue[4] = 0.8;
stateFire[4] = true;
stateRecoil[4] = "";
stateAllowImageChange[4] = false;
stateSequence[4] = "Fire";
stateSequenceNeverTransition[4] = true;
stateShapeSequence[4] = "Fire";
// Throw the actual mine
stateName[5] = "Fire2";
stateTransitionGeneric0In[5] = "SprintEnter";
stateTransitionOnTriggerUp[5] = "Reload";
stateTimeoutValue[5] = 0.7;
stateAllowImageChange[5] = false;
stateSequenceNeverTransition[5] = true;
stateSequence[5] = "fire_release";
stateShapeSequence[5] = "Fire_Release";
stateScript[5] = "onFire";
// Play the reload animation, and transition into
stateName[6] = "Reload";
stateTransitionGeneric0In[6] = "SprintEnter";
stateTransitionOnTimeout[6] = "Ready";
stateWaitForTimeout[6] = true;
stateTimeoutValue[6] = 3.0;
stateSequence[6] = "switch_in";
stateShapeSequence[6] = "Reload";
stateSound[6] = MineSwitchinSound;
// Start Sprinting
stateName[7] = "SprintEnter";
stateTransitionGeneric0Out[7] = "SprintExit";
stateTransitionOnTimeout[7] = "Sprinting";
stateWaitForTimeout[7] = false;
stateTimeoutValue[7] = 0.25;
stateWaitForTimeout[7] = false;
stateScaleAnimation[7] = true;
stateScaleAnimationFP[7] = true;
stateSequenceTransitionIn[7] = true;
stateSequenceTransitionOut[7] = true;
stateAllowImageChange[7] = false;
stateSequence[7] = "run2sprint";
// Sprinting
stateName[8] = "Sprinting";
stateTransitionGeneric0Out[8] = "SprintExit";
stateWaitForTimeout[8] = false;
stateScaleAnimation[8] = false;
stateScaleAnimationFP[8] = false;
stateSequenceTransitionIn[8] = true;
stateSequenceTransitionOut[8] = true;
stateAllowImageChange[8] = false;
stateSequence[8] = "sprint";
// Stop Sprinting
stateName[9] = "SprintExit";
stateTransitionGeneric0In[9] = "SprintEnter";
stateTransitionOnTimeout[9] = "Ready";
stateWaitForTimeout[9] = false;
stateTimeoutValue[9] = 0.5;
stateSequenceTransitionIn[9] = true;
stateSequenceTransitionOut[9] = true;
stateAllowImageChange[9] = false;
stateSequence[9] = "sprint2run";
};
| |
namespace MonoRpg.Engine.UI {
using global::System;
using global::System.Collections.Generic;
using global::System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoRpg.Engine.RenderEngine;
public class Selection<T> {
public int Height { get; set; }
public int Width { get; set; }
public Action<Renderer, int, int, T> RenderItem { get; set; }
public int DisplayRows { get; set; }
public Action<int, T> OnSelection { get; set; }
public float Scale { get; set; }
public int DisplayStart { get; set; }
public int MaxRows { get; set; }
public bool DisplayCursor { get; set; }
public int CursorWidth { get; set; }
public Sprite Cursor { get; set; }
public int SpacingY { get; set; }
public int SpacingX { get; set; }
public int FocusY { get; set; }
public int FocusX { get; set; }
public int Columns { get; set; }
public List<T> DataSource { get; set; }
public int X { get; set; }
public int Y { get; set; }
public Selection(Renderer renderer, SelectionArgs<T> args) {
X = 0;
Y = 0;
DataSource = args.DataSource;
Columns = args.Columns;
FocusX = 0;
FocusY = 0;
SpacingX = args.SpacingX;
SpacingY = args.SpacingY;
Cursor = new Sprite();
var cursorTex = System.Content.FindTexture(args.Cursor);
Cursor.Texture = cursorTex;
CursorWidth = cursorTex.Width;
DisplayCursor = true;
MaxRows = args.Rows;
DisplayStart = 0;
Scale = 1f;
TextScale = 1f;
OnSelection = args.OnSelection;
DisplayRows = args.DisplayRows;
RenderItem = args.RenderItem ?? RenderItemFunc;
Width = CalcWidth(renderer);
Height = CalcHeight();
}
private void RenderItemFunc(Renderer renderer, int x, int y, T item) {
RenderItemFunc(this, renderer, x, y, item);
}
public static void RenderItemFunc(Selection<T> select, Renderer renderer, int x, int y, T item) {
if (item == null) {
return;
}
var itemName = item.ToString();
if (string.IsNullOrEmpty(itemName)) {
renderer.DrawText2D(x, y, "--", Color.White, select.Scale * select.TextScale);
} else {
renderer.DrawText2D(x, y, itemName, Color.White, select.Scale * select.TextScale);
}
}
public void HandleInput() {
if (System.Keys.WasPressed(Keys.Up)) {
MoveUp();
} else if (System.Keys.WasPressed(Keys.Down)) {
MoveDown();
} else if (System.Keys.WasPressed(Keys.Left)) {
MoveLeft();
} else if (System.Keys.WasPressed(Keys.Right)) {
MoveRight();
} else if (System.Keys.WasPressed(Keys.Space)) {
OnClick();
}
}
private void MoveUp() {
FocusY = Math.Max(FocusY - 1, 0);
if (FocusY < DisplayStart) {
MoveDisplayUp();
}
}
private void MoveDown() {
FocusY = Math.Min(FocusY + 1, (int)Math.Ceiling(DataSource.Count / (float)Columns)-1);
if (FocusY >= DisplayStart + DisplayRows) {
MoveDisplayDown();
}
}
private void MoveLeft() {
FocusX = Math.Max(FocusX - 1, 0);
}
private void MoveRight() {
FocusX = Math.Min(FocusX + 1, Columns - 1);
}
public void OnClick() {
var index = GetIndex();
OnSelection(index, DataSource[index]);
}
private void MoveDisplayUp() { DisplayStart -= 1; }
private void MoveDisplayDown() { DisplayStart += 1; }
public int GetIndex() { return FocusX + FocusY * Columns; }
public void Render(Renderer renderer) {
var displayStart = DisplayStart;
var displayEnd = displayStart + DisplayRows;
var x = X;
var y = Y;
var cursorWidth = CursorWidth * Scale;
var spacingX = SpacingX * Scale;
var rowHeight = SpacingY * Scale;
Cursor.Scale = new Vector2(Scale);
var itemIndex = displayStart * Columns;
for (var i = displayStart; i < displayEnd; i++) {
for (var j = 0; j < Columns; j++) {
if (i == FocusY && j == FocusX && DisplayCursor) {
Cursor.Position = new Vector2(x, y);
renderer.DrawSprite(Cursor);
}
var item = itemIndex < DataSource.Count ? DataSource[itemIndex] : default(T);
RenderItem(renderer, (int)(x + cursorWidth), y, item);
x += (int)spacingX;
itemIndex++;
}
y -= (int)rowHeight;
x = X;
}
}
public int GetWidth() { return (int)(Width * Scale); }
public int GetHeight() { return (int)(Height * Scale); }
private int CalcWidth(Renderer renderer) {
if (Columns == 1) {
var maxEntryWidth = 0;
foreach (var item in DataSource) {
var width = renderer.MeasureText(item.ToString(), -1, TextScale).X;
maxEntryWidth = (int)Math.Max(width, maxEntryWidth);
}
return maxEntryWidth;
}
return SpacingX * Columns;
}
private int CalcHeight() {
var height = DisplayRows * SpacingY;
return height - SpacingY / 2;
}
public void ShowCursor() { DisplayCursor = true; }
public void HideCursor() { DisplayCursor = false; }
public Vector2 Position {
get => new Vector2(X, Y);
set {
X = (int)value.X;
Y = (int)value.Y;
}
}
public float PercentageShown => DisplayRows / (float)MaxRows;
public float PercentageScrolled {
get {
var onePercent = 1.0f / MaxRows;
var currentPercent = FocusY / (float)MaxRows;
if (currentPercent <= onePercent) {
return 0;
}
return currentPercent;
}
}
public T SelectedItem {
get {
var index = GetIndex();
if (index < DataSource.Count) {
return DataSource[index];
}
return default(T);
}
}
public float TextScale { get; set; }
}
public class SelectionArgs<T> {
public SelectionArgs(List<T> items) {
DataSource = items ?? new List<T>();
Columns = 1;
SpacingX = 128;
SpacingY = 24;
Cursor = "cursor.png";
_rows = -1;
OnSelection = (index, selectedItem) => { };
DisplayRows = Rows;
}
public SelectionArgs(params T[] items) : this(items.ToList()) {
}
public Action<int, T> OnSelection { get; set; }
public string Cursor { get; set; }
public int SpacingY { get; set; }
public int SpacingX { get; set; }
public List<T> DataSource { get; set; }
public int Columns { get; set; }
private int _rows;
public int Rows {
get => _rows > 0 ? _rows : DataSource.Count / Columns;
set => _rows = value;
}
public int DisplayRows { get; set; }
public Action<Renderer, int, int, T> RenderItem { get; set; }
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Reflection;
using System.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
using System.Collections.Generic;
using System.IO;
#if !PORTABLE && !NETSTANDARD1_6
using System.Diagnostics;
using System.Security;
using System.Windows.Forms;
#endif
namespace NUnit.Framework.Api
{
/// <summary>
/// Implementation of ITestAssemblyRunner
/// </summary>
public class NUnitTestAssemblyRunner : ITestAssemblyRunner
{
private static Logger log = InternalTrace.GetLogger("DefaultTestAssemblyRunner");
private ITestAssemblyBuilder _builder;
private ManualResetEvent _runComplete = new ManualResetEvent(false);
#if !PORTABLE
// Saved Console.Out and Console.Error
private TextWriter _savedOut;
private TextWriter _savedErr;
#endif
#if PARALLEL
// Event Pump
private EventPump _pump;
#endif
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NUnitTestAssemblyRunner"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public NUnitTestAssemblyRunner(ITestAssemblyBuilder builder)
{
_builder = builder;
}
#endregion
#region Properties
#if PARALLEL
/// <summary>
/// Gets the default level of parallel execution (worker threads)
/// </summary>
public static int DefaultLevelOfParallelism
{
get { return Math.Max(Environment.ProcessorCount, 2); }
}
#endif
/// <summary>
/// The tree of tests that was loaded by the builder
/// </summary>
public ITest LoadedTest { get; private set; }
/// <summary>
/// The test result, if a run has completed
/// </summary>
public ITestResult Result
{
get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; }
}
/// <summary>
/// Indicates whether a test is loaded
/// </summary>
public bool IsTestLoaded
{
get { return LoadedTest != null; }
}
/// <summary>
/// Indicates whether a test is running
/// </summary>
public bool IsTestRunning
{
get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Running; }
}
/// <summary>
/// Indicates whether a test run is complete
/// </summary>
public bool IsTestComplete
{
get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Complete; }
}
/// <summary>
/// Our settings, specified when loading the assembly
/// </summary>
private IDictionary<string, object> Settings { get; set; }
/// <summary>
/// The top level WorkItem created for the assembly as a whole
/// </summary>
private WorkItem TopLevelWorkItem { get; set; }
/// <summary>
/// The TestExecutionContext for the top level WorkItem
/// </summary>
private TestExecutionContext Context { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Loads the tests found in an Assembly
/// </summary>
/// <param name="assemblyName">File name of the assembly to load</param>
/// <param name="settings">Dictionary of option settings for loading the assembly</param>
/// <returns>True if the load was successful</returns>
public ITest Load(string assemblyName, IDictionary<string, object> settings)
{
Settings = settings;
if (settings.ContainsKey(FrameworkPackageSettings.RandomSeed))
Randomizer.InitialSeed = (int)settings[FrameworkPackageSettings.RandomSeed];
return LoadedTest = _builder.Build(assemblyName, settings);
}
/// <summary>
/// Loads the tests found in an Assembly
/// </summary>
/// <param name="assembly">The assembly to load</param>
/// <param name="settings">Dictionary of option settings for loading the assembly</param>
/// <returns>True if the load was successful</returns>
public ITest Load(Assembly assembly, IDictionary<string, object> settings)
{
Settings = settings;
if (settings.ContainsKey(FrameworkPackageSettings.RandomSeed))
Randomizer.InitialSeed = (int)settings[FrameworkPackageSettings.RandomSeed];
return LoadedTest = _builder.Build(assembly, settings);
}
/// <summary>
/// Count Test Cases using a filter
/// </summary>
/// <param name="filter">The filter to apply</param>
/// <returns>The number of test cases found</returns>
public int CountTestCases(ITestFilter filter)
{
if (LoadedTest == null)
throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded");
return CountTestCases(LoadedTest, filter);
}
/// <summary>
/// Run selected tests and return a test result. The test is run synchronously,
/// and the listener interface is notified as it progresses.
/// </summary>
/// <param name="listener">Interface to receive EventListener notifications.</param>
/// <param name="filter">A test filter used to select tests to be run</param>
/// <returns></returns>
public ITestResult Run(ITestListener listener, ITestFilter filter)
{
RunAsync(listener, filter);
WaitForCompletion(Timeout.Infinite);
return Result;
}
/// <summary>
/// Run selected tests asynchronously, notifying the listener interface as it progresses.
/// </summary>
/// <param name="listener">Interface to receive EventListener notifications.</param>
/// <param name="filter">A test filter used to select tests to be run</param>
/// <remarks>
/// RunAsync is a template method, calling various abstract and
/// virtual methods to be overridden by derived classes.
/// </remarks>
public void RunAsync(ITestListener listener, ITestFilter filter)
{
log.Info("Running tests");
if (LoadedTest == null)
throw new InvalidOperationException("The Run method was called but no test has been loaded");
_runComplete.Reset();
CreateTestExecutionContext(listener);
TopLevelWorkItem = WorkItem.CreateWorkItem(LoadedTest, filter);
TopLevelWorkItem.InitializeContext(Context);
TopLevelWorkItem.Completed += OnRunCompleted;
StartRun(listener);
}
/// <summary>
/// Wait for the ongoing run to complete.
/// </summary>
/// <param name="timeout">Time to wait in milliseconds</param>
/// <returns>True if the run completed, otherwise false</returns>
public bool WaitForCompletion(int timeout)
{
return _runComplete.WaitOne(timeout);
}
/// <summary>
/// Signal any test run that is in process to stop. Return without error if no test is running.
/// </summary>
/// <param name="force">If true, kill any tests that are currently running</param>
public void StopRun(bool force)
{
if (IsTestRunning)
{
Context.ExecutionStatus = force
? TestExecutionStatus.AbortRequested
: TestExecutionStatus.StopRequested;
Context.Dispatcher.CancelRun(force);
}
}
#endregion
#region Helper Methods
/// <summary>
/// Initiate the test run.
/// </summary>
private void StartRun(ITestListener listener)
{
#if !PORTABLE
// Save Console.Out and Error for later restoration
_savedOut = Console.Out;
_savedErr = Console.Error;
Console.SetOut(new TextCapture(Console.Out));
Console.SetError(new EventListenerTextWriter("Error", Console.Error));
#endif
#if PARALLEL
// Queue and pump events, unless settings have SynchronousEvents == false
if (!Settings.ContainsKey(FrameworkPackageSettings.SynchronousEvents) || !(bool)Settings[FrameworkPackageSettings.SynchronousEvents])
{
QueuingEventListener queue = new QueuingEventListener();
Context.Listener = queue;
_pump = new EventPump(listener, queue.Events);
_pump.Start();
}
#endif
if (!System.Diagnostics.Debugger.IsAttached &&
Settings.ContainsKey(FrameworkPackageSettings.DebugTests) &&
(bool)Settings[FrameworkPackageSettings.DebugTests])
System.Diagnostics.Debugger.Launch();
#if !PORTABLE && !NETSTANDARD1_6
if (Settings.ContainsKey(FrameworkPackageSettings.PauseBeforeRun) &&
(bool)Settings[FrameworkPackageSettings.PauseBeforeRun])
PauseBeforeRun();
#endif
Context.Dispatcher.Start(TopLevelWorkItem);
}
/// <summary>
/// Create the initial TestExecutionContext used to run tests
/// </summary>
/// <param name="listener">The ITestListener specified in the RunAsync call</param>
private void CreateTestExecutionContext(ITestListener listener)
{
Context = new TestExecutionContext();
// Apply package settings to the context
if (Settings.ContainsKey(FrameworkPackageSettings.DefaultTimeout))
Context.TestCaseTimeout = (int)Settings[FrameworkPackageSettings.DefaultTimeout];
if (Settings.ContainsKey(FrameworkPackageSettings.StopOnError))
Context.StopOnError = (bool)Settings[FrameworkPackageSettings.StopOnError];
// Apply attributes to the context
// Set the listener - overriding runners may replace this
Context.Listener = listener;
#if PARALLEL
int levelOfParallelism = GetLevelOfParallelism();
if (levelOfParallelism > 0)
Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism);
else
Context.Dispatcher = new SimpleWorkItemDispatcher();
#else
Context.Dispatcher = new SimpleWorkItemDispatcher();
#endif
}
/// <summary>
/// Handle the the Completed event for the top level work item
/// </summary>
private void OnRunCompleted(object sender, EventArgs e)
{
#if PARALLEL
if (_pump != null)
_pump.Dispose();
#endif
#if !PORTABLE
Console.SetOut(_savedOut);
Console.SetError(_savedErr);
#endif
_runComplete.Set();
}
private int CountTestCases(ITest test, ITestFilter filter)
{
if (!test.IsSuite)
return 1;
int count = 0;
foreach (ITest child in test.Tests)
if (filter.Pass(child))
count += CountTestCases(child, filter);
return count;
}
#if PARALLEL
private int GetLevelOfParallelism()
{
return Settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers)
? (int)Settings[FrameworkPackageSettings.NumberOfTestWorkers]
: (LoadedTest.Properties.ContainsKey(PropertyNames.LevelOfParallelism)
? (int)LoadedTest.Properties.Get(PropertyNames.LevelOfParallelism)
: NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
}
#endif
#if !PORTABLE && !NETSTANDARD1_6
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
private static void PauseBeforeRun()
{
var process = Process.GetCurrentProcess();
string attachMessage = string.Format("Attach debugger to Process {0}.exe with Id {1} if desired.", process.ProcessName, process.Id);
MessageBox.Show(attachMessage, process.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endif
#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.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject
{
public IOSSL_Api m_OSSL_Functions;
public void ApiTypeOSSL(IScriptApi api)
{
if (!(api is IOSSL_Api))
return;
m_OSSL_Functions = (IOSSL_Api)api;
Prim = new OSSLPrim(this);
}
public void osSetRegionWaterHeight(double height)
{
m_OSSL_Functions.osSetRegionWaterHeight(height);
}
public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour)
{
m_OSSL_Functions.osSetRegionSunSettings(useEstateSun, sunFixed, sunHour);
}
public void osSetEstateSunSettings(bool sunFixed, double sunHour)
{
m_OSSL_Functions.osSetEstateSunSettings(sunFixed, sunHour);
}
public double osGetCurrentSunHour()
{
return m_OSSL_Functions.osGetCurrentSunHour();
}
public double osGetSunParam(string param)
{
return m_OSSL_Functions.osGetSunParam(param);
}
// Deprecated
public double osSunGetParam(string param)
{
return m_OSSL_Functions.osSunGetParam(param);
}
public void osSetSunParam(string param, double value)
{
m_OSSL_Functions.osSetSunParam(param, value);
}
// Deprecated
public void osSunSetParam(string param, double value)
{
m_OSSL_Functions.osSunSetParam(param, value);
}
public string osWindActiveModelPluginName()
{
return m_OSSL_Functions.osWindActiveModelPluginName();
}
public void osSetWindParam(string plugin, string param, LSL_Float value)
{
m_OSSL_Functions.osSetWindParam(plugin, param, value);
}
public LSL_Float osGetWindParam(string plugin, string param)
{
return m_OSSL_Functions.osGetWindParam(plugin, param);
}
public void osParcelJoin(vector pos1, vector pos2)
{
m_OSSL_Functions.osParcelJoin(pos1,pos2);
}
public void osParcelSubdivide(vector pos1, vector pos2)
{
m_OSSL_Functions.osParcelSubdivide(pos1, pos2);
}
public void osSetParcelDetails(vector pos, LSL_List rules)
{
m_OSSL_Functions.osSetParcelDetails(pos, rules);
}
// Deprecated
public void osParcelSetDetails(vector pos, LSL_List rules)
{
m_OSSL_Functions.osParcelSetDetails(pos,rules);
}
public double osList2Double(LSL_Types.list src, int index)
{
return m_OSSL_Functions.osList2Double(src, index);
}
public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams,
int timer)
{
return m_OSSL_Functions.osSetDynamicTextureURL(dynamicID, contentType, url, extraParams, timer);
}
public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams,
int timer)
{
return m_OSSL_Functions.osSetDynamicTextureData(dynamicID, contentType, data, extraParams, timer);
}
public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
int timer, int alpha)
{
return m_OSSL_Functions.osSetDynamicTextureURLBlend(dynamicID, contentType, url, extraParams, timer, alpha);
}
public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
int timer, int alpha)
{
return m_OSSL_Functions.osSetDynamicTextureDataBlend(dynamicID, contentType, data, extraParams, timer, alpha);
}
public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
bool blend, int disp, int timer, int alpha, int face)
{
return m_OSSL_Functions.osSetDynamicTextureURLBlendFace(dynamicID, contentType, url, extraParams,
blend, disp, timer, alpha, face);
}
public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
bool blend, int disp, int timer, int alpha, int face)
{
return m_OSSL_Functions.osSetDynamicTextureDataBlendFace(dynamicID, contentType, data, extraParams,
blend, disp, timer, alpha, face);
}
public LSL_Float osGetTerrainHeight(int x, int y)
{
return m_OSSL_Functions.osGetTerrainHeight(x, y);
}
// Deprecated
public LSL_Float osTerrainGetHeight(int x, int y)
{
return m_OSSL_Functions.osTerrainGetHeight(x, y);
}
public LSL_Integer osSetTerrainHeight(int x, int y, double val)
{
return m_OSSL_Functions.osSetTerrainHeight(x, y, val);
}
// Deprecated
public LSL_Integer osTerrainSetHeight(int x, int y, double val)
{
return m_OSSL_Functions.osTerrainSetHeight(x, y, val);
}
public void osTerrainFlush()
{
m_OSSL_Functions.osTerrainFlush();
}
public int osRegionRestart(double seconds)
{
return m_OSSL_Functions.osRegionRestart(seconds);
}
public int osRegionRestart(double seconds, string msg)
{
return m_OSSL_Functions.osRegionRestart(seconds, msg);
}
public void osRegionNotice(string msg)
{
m_OSSL_Functions.osRegionNotice(msg);
}
public bool osConsoleCommand(string Command)
{
return m_OSSL_Functions.osConsoleCommand(Command);
}
public void osSetParcelMediaURL(string url)
{
m_OSSL_Functions.osSetParcelMediaURL(url);
}
public void osSetParcelSIPAddress(string SIPAddress)
{
m_OSSL_Functions.osSetParcelSIPAddress(SIPAddress);
}
public void osSetPrimFloatOnWater(int floatYN)
{
m_OSSL_Functions.osSetPrimFloatOnWater(floatYN);
}
// Teleport Functions
public void osTeleportAgent(string agent, string regionName, vector position, vector lookat)
{
m_OSSL_Functions.osTeleportAgent(agent, regionName, position, lookat);
}
public void osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat)
{
m_OSSL_Functions.osTeleportAgent(agent, regionX, regionY, position, lookat);
}
public void osTeleportAgent(string agent, vector position, vector lookat)
{
m_OSSL_Functions.osTeleportAgent(agent, position, lookat);
}
public void osTeleportOwner(string regionName, vector position, vector lookat)
{
m_OSSL_Functions.osTeleportOwner(regionName, position, lookat);
}
public void osTeleportOwner(int regionX, int regionY, vector position, vector lookat)
{
m_OSSL_Functions.osTeleportOwner(regionX, regionY, position, lookat);
}
public void osTeleportOwner(vector position, vector lookat)
{
m_OSSL_Functions.osTeleportOwner(position, lookat);
}
// Avatar info functions
public string osGetAgentIP(string agent)
{
return m_OSSL_Functions.osGetAgentIP(agent);
}
public LSL_List osGetAgents()
{
return m_OSSL_Functions.osGetAgents();
}
// Animation Functions
public void osAvatarPlayAnimation(string avatar, string animation)
{
m_OSSL_Functions.osAvatarPlayAnimation(avatar, animation);
}
public void osAvatarStopAnimation(string avatar, string animation)
{
m_OSSL_Functions.osAvatarStopAnimation(avatar, animation);
}
#region Attachment commands
public void osForceAttachToAvatar(int attachmentPoint)
{
m_OSSL_Functions.osForceAttachToAvatar(attachmentPoint);
}
public void osForceAttachToAvatarFromInventory(string itemName, int attachmentPoint)
{
m_OSSL_Functions.osForceAttachToAvatarFromInventory(itemName, attachmentPoint);
}
public void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint)
{
m_OSSL_Functions.osForceAttachToOtherAvatarFromInventory(rawAvatarId, itemName, attachmentPoint);
}
public void osForceDetachFromAvatar()
{
m_OSSL_Functions.osForceDetachFromAvatar();
}
public LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints)
{
return m_OSSL_Functions.osGetNumberOfAttachments(avatar, attachmentPoints);
}
public void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int flags)
{
m_OSSL_Functions.osMessageAttachments(avatar, message, attachmentPoints, flags);
}
#endregion
// Texture Draw functions
public string osMovePen(string drawList, int x, int y)
{
return m_OSSL_Functions.osMovePen(drawList, x, y);
}
public string osDrawLine(string drawList, int startX, int startY, int endX, int endY)
{
return m_OSSL_Functions.osDrawLine(drawList, startX, startY, endX, endY);
}
public string osDrawLine(string drawList, int endX, int endY)
{
return m_OSSL_Functions.osDrawLine(drawList, endX, endY);
}
public string osDrawText(string drawList, string text)
{
return m_OSSL_Functions.osDrawText(drawList, text);
}
public string osDrawEllipse(string drawList, int width, int height)
{
return m_OSSL_Functions.osDrawEllipse(drawList, width, height);
}
public string osDrawRectangle(string drawList, int width, int height)
{
return m_OSSL_Functions.osDrawRectangle(drawList, width, height);
}
public string osDrawFilledRectangle(string drawList, int width, int height)
{
return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height);
}
public string osDrawPolygon(string drawList, LSL_List x, LSL_List y)
{
return m_OSSL_Functions.osDrawPolygon(drawList, x, y);
}
public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y)
{
return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y);
}
public string osSetFontSize(string drawList, int fontSize)
{
return m_OSSL_Functions.osSetFontSize(drawList, fontSize);
}
public string osSetFontName(string drawList, string fontName)
{
return m_OSSL_Functions.osSetFontName(drawList, fontName);
}
public string osSetPenSize(string drawList, int penSize)
{
return m_OSSL_Functions.osSetPenSize(drawList, penSize);
}
public string osSetPenCap(string drawList, string direction, string type)
{
return m_OSSL_Functions.osSetPenCap(drawList, direction, type);
}
public string osSetPenColor(string drawList, string color)
{
return m_OSSL_Functions.osSetPenColor(drawList, color);
}
// Deprecated
public string osSetPenColour(string drawList, string colour)
{
return m_OSSL_Functions.osSetPenColour(drawList, colour);
}
public string osDrawImage(string drawList, int width, int height, string imageUrl)
{
return m_OSSL_Functions.osDrawImage(drawList, width, height, imageUrl);
}
public vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize)
{
return m_OSSL_Functions.osGetDrawStringSize(contentType, text, fontName, fontSize);
}
public void osSetStateEvents(int events)
{
m_OSSL_Functions.osSetStateEvents(events);
}
public string osGetScriptEngineName()
{
return m_OSSL_Functions.osGetScriptEngineName();
}
public LSL_Integer osCheckODE()
{
return m_OSSL_Functions.osCheckODE();
}
public string osGetPhysicsEngineType()
{
return m_OSSL_Functions.osGetPhysicsEngineType();
}
public string osGetPhysicsEngineName()
{
return m_OSSL_Functions.osGetPhysicsEngineName();
}
public string osGetSimulatorVersion()
{
return m_OSSL_Functions.osGetSimulatorVersion();
}
public Hashtable osParseJSON(string JSON)
{
return m_OSSL_Functions.osParseJSON(JSON);
}
public Object osParseJSONNew(string JSON)
{
return m_OSSL_Functions.osParseJSONNew(JSON);
}
public void osMessageObject(key objectUUID,string message)
{
m_OSSL_Functions.osMessageObject(objectUUID,message);
}
public void osMakeNotecard(string notecardName, LSL_Types.list contents)
{
m_OSSL_Functions.osMakeNotecard(notecardName, contents);
}
public string osGetNotecardLine(string name, int line)
{
return m_OSSL_Functions.osGetNotecardLine(name, line);
}
public string osGetNotecard(string name)
{
return m_OSSL_Functions.osGetNotecard(name);
}
public int osGetNumberOfNotecardLines(string name)
{
return m_OSSL_Functions.osGetNumberOfNotecardLines(name);
}
public string osAvatarName2Key(string firstname, string lastname)
{
return m_OSSL_Functions.osAvatarName2Key(firstname, lastname);
}
public string osKey2Name(string id)
{
return m_OSSL_Functions.osKey2Name(id);
}
public string osGetGridNick()
{
return m_OSSL_Functions.osGetGridNick();
}
public string osGetGridName()
{
return m_OSSL_Functions.osGetGridName();
}
public string osGetGridLoginURI()
{
return m_OSSL_Functions.osGetGridLoginURI();
}
public string osGetGridHomeURI()
{
return m_OSSL_Functions.osGetGridHomeURI();
}
public string osGetGridGatekeeperURI()
{
return m_OSSL_Functions.osGetGridGatekeeperURI();
}
public string osGetGridCustom(string key)
{
return m_OSSL_Functions.osGetGridCustom(key);
}
public string osGetAvatarHomeURI(string uuid)
{
return m_OSSL_Functions.osGetAvatarHomeURI(uuid);
}
public LSL_String osFormatString(string str, LSL_List strings)
{
return m_OSSL_Functions.osFormatString(str, strings);
}
public LSL_List osMatchString(string src, string pattern, int start)
{
return m_OSSL_Functions.osMatchString(src, pattern, start);
}
public LSL_String osReplaceString(string src, string pattern, string replace, int count, int start)
{
return m_OSSL_Functions.osReplaceString(src,pattern,replace,count,start);
}
// Information about data loaded into the region
public string osLoadedCreationDate()
{
return m_OSSL_Functions.osLoadedCreationDate();
}
public string osLoadedCreationTime()
{
return m_OSSL_Functions.osLoadedCreationTime();
}
public string osLoadedCreationID()
{
return m_OSSL_Functions.osLoadedCreationID();
}
public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules)
{
return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules);
}
public void osForceCreateLink(string target, int parent)
{
m_OSSL_Functions.osForceCreateLink(target, parent);
}
public void osForceBreakLink(int linknum)
{
m_OSSL_Functions.osForceBreakLink(linknum);
}
public void osForceBreakAllLinks()
{
m_OSSL_Functions.osForceBreakAllLinks();
}
public void osDie(LSL_Key objectUUID)
{
m_OSSL_Functions.osDie(objectUUID);
}
public LSL_Integer osIsNpc(LSL_Key npc)
{
return m_OSSL_Functions.osIsNpc(npc);
}
public key osNpcCreate(string user, string name, vector position, key cloneFrom)
{
return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom);
}
public key osNpcCreate(string user, string name, vector position, key cloneFrom, int options)
{
return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom, options);
}
public key osNpcSaveAppearance(key npc, string notecard)
{
return m_OSSL_Functions.osNpcSaveAppearance(npc, notecard);
}
public void osNpcLoadAppearance(key npc, string notecard)
{
m_OSSL_Functions.osNpcLoadAppearance(npc, notecard);
}
public LSL_Key osNpcGetOwner(LSL_Key npc)
{
return m_OSSL_Functions.osNpcGetOwner(npc);
}
public vector osNpcGetPos(LSL_Key npc)
{
return m_OSSL_Functions.osNpcGetPos(npc);
}
public void osNpcMoveTo(key npc, vector position)
{
m_OSSL_Functions.osNpcMoveTo(npc, position);
}
public void osNpcMoveToTarget(key npc, vector target, int options)
{
m_OSSL_Functions.osNpcMoveToTarget(npc, target, options);
}
public rotation osNpcGetRot(key npc)
{
return m_OSSL_Functions.osNpcGetRot(npc);
}
public void osNpcSetRot(key npc, rotation rot)
{
m_OSSL_Functions.osNpcSetRot(npc, rot);
}
public void osNpcStopMoveToTarget(LSL_Key npc)
{
m_OSSL_Functions.osNpcStopMoveToTarget(npc);
}
public void osNpcSetProfileAbout(LSL_Key npc, string about)
{
m_OSSL_Functions.osNpcSetProfileAbout(npc, about);
}
public void osNpcSetProfileImage(LSL_Key npc, string image)
{
m_OSSL_Functions.osNpcSetProfileImage(npc, image);
}
public void osNpcSay(key npc, string message)
{
m_OSSL_Functions.osNpcSay(npc, message);
}
public void osNpcSay(key npc, int channel, string message)
{
m_OSSL_Functions.osNpcSay(npc, channel, message);
}
public void osNpcShout(key npc, int channel, string message)
{
m_OSSL_Functions.osNpcShout(npc, channel, message);
}
public void osNpcSit(LSL_Key npc, LSL_Key target, int options)
{
m_OSSL_Functions.osNpcSit(npc, target, options);
}
public void osNpcStand(LSL_Key npc)
{
m_OSSL_Functions.osNpcStand(npc);
}
public void osNpcRemove(key npc)
{
m_OSSL_Functions.osNpcRemove(npc);
}
public void osNpcPlayAnimation(LSL_Key npc, string animation)
{
m_OSSL_Functions.osNpcPlayAnimation(npc, animation);
}
public void osNpcStopAnimation(LSL_Key npc, string animation)
{
m_OSSL_Functions.osNpcStopAnimation(npc, animation);
}
public void osNpcWhisper(key npc, int channel, string message)
{
m_OSSL_Functions.osNpcWhisper(npc, channel, message);
}
public void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num)
{
m_OSSL_Functions.osNpcTouch(npcLSL_Key, object_key, link_num);
}
public LSL_Key osOwnerSaveAppearance(string notecard)
{
return m_OSSL_Functions.osOwnerSaveAppearance(notecard);
}
public LSL_Key osAgentSaveAppearance(LSL_Key agentId, string notecard)
{
return m_OSSL_Functions.osAgentSaveAppearance(agentId, notecard);
}
public OSSLPrim Prim;
[Serializable]
public class OSSLPrim
{
internal ScriptBaseClass OSSL;
public OSSLPrim(ScriptBaseClass bc)
{
OSSL = bc;
Position = new OSSLPrim_Position(this);
Rotation = new OSSLPrim_Rotation(this);
}
public OSSLPrim_Position Position;
public OSSLPrim_Rotation Rotation;
private TextStruct _text;
public TextStruct Text
{
get { return _text; }
set
{
_text = value;
OSSL.llSetText(_text.Text, _text.color, _text.alpha);
}
}
[Serializable]
public struct TextStruct
{
public string Text;
public LSL_Types.Vector3 color;
public double alpha;
}
}
[Serializable]
public class OSSLPrim_Position
{
private OSSLPrim prim;
private LSL_Types.Vector3 Position;
public OSSLPrim_Position(OSSLPrim _prim)
{
prim = _prim;
}
private void Load()
{
Position = prim.OSSL.llGetPos();
}
private void Save()
{
/* Remove temporarily until we have a handle to the region size
if (Position.x > ((int)Constants.RegionSize - 1))
Position.x = ((int)Constants.RegionSize - 1);
if (Position.y > ((int)Constants.RegionSize - 1))
Position.y = ((int)Constants.RegionSize - 1);
*/
if (Position.x < 0)
Position.x = 0;
if (Position.y < 0)
Position.y = 0;
if (Position.z < 0)
Position.z = 0;
if (Position.z > Constants.RegionHeight)
Position.z = Constants.RegionHeight;
prim.OSSL.llSetPos(Position);
}
public double x
{
get
{
Load();
return Position.x;
}
set
{
Load();
Position.x = value;
Save();
}
}
public double y
{
get
{
Load();
return Position.y;
}
set
{
Load();
Position.y = value;
Save();
}
}
public double z
{
get
{
Load();
return Position.z;
}
set
{
Load();
Position.z = value;
Save();
}
}
}
[Serializable]
public class OSSLPrim_Rotation
{
private OSSLPrim prim;
private LSL_Types.Quaternion Rotation;
public OSSLPrim_Rotation(OSSLPrim _prim)
{
prim = _prim;
}
private void Load()
{
Rotation = prim.OSSL.llGetRot();
}
private void Save()
{
prim.OSSL.llSetRot(Rotation);
}
public double x
{
get
{
Load();
return Rotation.x;
}
set
{
Load();
Rotation.x = value;
Save();
}
}
public double y
{
get
{
Load();
return Rotation.y;
}
set
{
Load();
Rotation.y = value;
Save();
}
}
public double z
{
get
{
Load();
return Rotation.z;
}
set
{
Load();
Rotation.z = value;
Save();
}
}
public double s
{
get
{
Load();
return Rotation.s;
}
set
{
Load();
Rotation.s = value;
Save();
}
}
}
public string osGetGender(LSL_Key rawAvatarId)
{
return m_OSSL_Functions.osGetGender(rawAvatarId);
}
public key osGetMapTexture()
{
return m_OSSL_Functions.osGetMapTexture();
}
public key osGetRegionMapTexture(string regionName)
{
return m_OSSL_Functions.osGetRegionMapTexture(regionName);
}
public LSL_List osGetRegionStats()
{
return m_OSSL_Functions.osGetRegionStats();
}
public vector osGetRegionSize()
{
return m_OSSL_Functions.osGetRegionSize();
}
/// <summary>
/// Returns the amount of memory in use by the Simulator Daemon.
/// Amount in bytes - if >= 4GB, returns 4GB. (LSL is not 64-bit aware)
/// </summary>
/// <returns></returns>
public LSL_Integer osGetSimulatorMemory()
{
return m_OSSL_Functions.osGetSimulatorMemory();
}
public void osKickAvatar(string FirstName,string SurName,string alert)
{
m_OSSL_Functions.osKickAvatar(FirstName, SurName, alert);
}
public void osSetSpeed(string UUID, LSL_Float SpeedModifier)
{
m_OSSL_Functions.osSetSpeed(UUID, SpeedModifier);
}
public LSL_Float osGetHealth(string avatar)
{
return m_OSSL_Functions.osGetHealth(avatar);
}
public void osCauseDamage(string avatar, double damage)
{
m_OSSL_Functions.osCauseDamage(avatar, damage);
}
public void osCauseHealing(string avatar, double healing)
{
m_OSSL_Functions.osCauseHealing(avatar, healing);
}
public void osSetHealth(string avatar, double health)
{
m_OSSL_Functions.osSetHealth(avatar, health);
}
public void osSetHealRate(string avatar, double health)
{
m_OSSL_Functions.osSetHealRate(avatar, health);
}
public LSL_Float osGetHealRate(string avatar)
{
return m_OSSL_Functions.osGetHealRate(avatar);
}
public void osForceOtherSit(string avatar)
{
m_OSSL_Functions.osForceOtherSit(avatar);
}
public void osForceOtherSit(string avatar, string target)
{
m_OSSL_Functions.osForceOtherSit(avatar, target);
}
public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules)
{
return m_OSSL_Functions.osGetPrimitiveParams(prim, rules);
}
public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules)
{
m_OSSL_Functions.osSetPrimitiveParams(prim, rules);
}
public void osSetProjectionParams(bool projection, LSL_Key texture, double fov, double focus, double amb)
{
m_OSSL_Functions.osSetProjectionParams(projection, texture, fov, focus, amb);
}
public void osSetProjectionParams(LSL_Key prim, bool projection, LSL_Key texture, double fov, double focus, double amb)
{
m_OSSL_Functions.osSetProjectionParams(prim, projection, texture, fov, focus, amb);
}
public LSL_List osGetAvatarList()
{
return m_OSSL_Functions.osGetAvatarList();
}
public LSL_String osUnixTimeToTimestamp(long time)
{
return m_OSSL_Functions.osUnixTimeToTimestamp(time);
}
public LSL_String osGetInventoryDesc(string item)
{
return m_OSSL_Functions.osGetInventoryDesc(item);
}
public LSL_Integer osInviteToGroup(LSL_Key agentId)
{
return m_OSSL_Functions.osInviteToGroup(agentId);
}
public LSL_Integer osEjectFromGroup(LSL_Key agentId)
{
return m_OSSL_Functions.osEjectFromGroup(agentId);
}
public void osSetTerrainTexture(int level, LSL_Key texture)
{
m_OSSL_Functions.osSetTerrainTexture(level, texture);
}
public void osSetTerrainTextureHeight(int corner, double low, double high)
{
m_OSSL_Functions.osSetTerrainTextureHeight(corner, low, high);
}
public LSL_Integer osIsUUID(string thing)
{
return m_OSSL_Functions.osIsUUID(thing);
}
public LSL_Float osMin(double a, double b)
{
return m_OSSL_Functions.osMin(a, b);
}
public LSL_Float osMax(double a, double b)
{
return m_OSSL_Functions.osMax(a, b);
}
public LSL_Key osGetRezzingObject()
{
return m_OSSL_Functions.osGetRezzingObject();
}
public void osSetContentType(LSL_Key id, string type)
{
m_OSSL_Functions.osSetContentType(id,type);
}
public void osDropAttachment()
{
m_OSSL_Functions.osDropAttachment();
}
public void osForceDropAttachment()
{
m_OSSL_Functions.osForceDropAttachment();
}
public void osDropAttachmentAt(vector pos, rotation rot)
{
m_OSSL_Functions.osDropAttachmentAt(pos, rot);
}
public void osForceDropAttachmentAt(vector pos, rotation rot)
{
m_OSSL_Functions.osForceDropAttachmentAt(pos, rot);
}
public LSL_Integer osListenRegex(int channelID, string name, string ID, string msg, int regexBitfield)
{
return m_OSSL_Functions.osListenRegex(channelID, name, ID, msg, regexBitfield);
}
public LSL_Integer osRegexIsMatch(string input, string pattern)
{
return m_OSSL_Functions.osRegexIsMatch(input, pattern);
}
public LSL_String osRequestURL(LSL_List options)
{
return m_OSSL_Functions.osRequestURL(options);
}
public LSL_String osRequestSecureURL(LSL_List options)
{
return m_OSSL_Functions.osRequestSecureURL(options);
}
public void osCollisionSound(string impact_sound, double impact_volume)
{
m_OSSL_Functions.osCollisionSound(impact_sound, impact_volume);
}
public void osVolumeDetect(int detect)
{
m_OSSL_Functions.osVolumeDetect(detect);
}
}
}
| |
// 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.Numerics;
using System.IO;
internal partial class VectorTest
{
public static bool CheckValue<T>(T value, T expectedValue)
{
bool returnVal;
if (typeof(T) == typeof(float))
{
returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon;
}
if (typeof(T) == typeof(double))
{
returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon;
}
else
{
returnVal = value.Equals(expectedValue);
}
if (returnVal == false)
{
Console.WriteLine("CheckValue failed for type " + typeof(T).ToString() + ". Expected: {0} (0x{0:X}), Got: {1} (0x{1:X})", expectedValue, value);
}
return returnVal;
}
private static bool CheckVector<T>(Vector<T> V, T value) where T : struct, IComparable<T>, IEquatable<T>
{
for (int i = 0; i < Vector<T>.Count; i++)
{
if (!(CheckValue<T>(V[i], value)))
{
return false;
}
}
return true;
}
public static T GetValueFromInt<T>(int value)
{
if (typeof(T) == typeof(float))
{
float floatValue = (float)value;
return (T)(object)floatValue;
}
if (typeof(T) == typeof(double))
{
double doubleValue = (double)value;
return (T)(object)doubleValue;
}
if (typeof(T) == typeof(int))
{
return (T)(object)value;
}
if (typeof(T) == typeof(uint))
{
uint uintValue = (uint)value;
return (T)(object)uintValue;
}
if (typeof(T) == typeof(long))
{
long longValue = (long)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ulong))
{
ulong longValue = (ulong)value;
return (T)(object)longValue;
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(ushort)value;
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(byte)value;
}
if (typeof(T) == typeof(short))
{
return (T)(object)(short)value;
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(sbyte)value;
}
else
{
throw new ArgumentException();
}
}
private static void VectorPrint<T>(string mesg, Vector<T> v) where T : struct, IComparable<T>, IEquatable<T>
{
Console.Write(mesg + "[");
for (int i = 0; i < Vector<T>.Count; i++)
{
Console.Write(" " + v[i]);
if (i < (Vector<T>.Count - 1)) Console.Write(",");
}
Console.WriteLine(" ]");
}
private static T Add<T>(T left, T right) where T : struct, IComparable<T>, IEquatable<T>
{
if (typeof(T) == typeof(float))
{
return (T)(object)(((float)(object)left) + ((float)(object)right));
}
if (typeof(T) == typeof(double))
{
return (T)(object)(((double)(object)left) + ((double)(object)right));
}
if (typeof(T) == typeof(int))
{
return (T)(object)(((int)(object)left) + ((int)(object)right));
}
if (typeof(T) == typeof(uint))
{
return (T)(object)(((uint)(object)left) + ((uint)(object)right));
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(((ushort)(object)left) + ((ushort)(object)right));
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(((byte)(object)left) + ((byte)(object)right));
}
if (typeof(T) == typeof(short))
{
return (T)(object)(((short)(object)left) + ((short)(object)right));
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(((sbyte)(object)left) + ((sbyte)(object)right));
}
if (typeof(T) == typeof(long))
{
return (T)(object)(((long)(object)left) + ((long)(object)right));
}
if (typeof(T) == typeof(ulong))
{
return (T)(object)(((ulong)(object)left) + ((ulong)(object)right));
}
else
{
throw new ArgumentException();
}
}
private static T Multiply<T>(T left, T right) where T : struct, IComparable<T>, IEquatable<T>
{
if (typeof(T) == typeof(float))
{
return (T)(object)(((float)(object)left) * ((float)(object)right));
}
if (typeof(T) == typeof(double))
{
return (T)(object)(((double)(object)left) * ((double)(object)right));
}
if (typeof(T) == typeof(int))
{
return (T)(object)(((int)(object)left) * ((int)(object)right));
}
if (typeof(T) == typeof(uint))
{
return (T)(object)(((uint)(object)left) * ((uint)(object)right));
}
if (typeof(T) == typeof(ushort))
{
return (T)(object)(((ushort)(object)left) * ((ushort)(object)right));
}
if (typeof(T) == typeof(byte))
{
return (T)(object)(((byte)(object)left) * ((byte)(object)right));
}
if (typeof(T) == typeof(short))
{
return (T)(object)(((short)(object)left) * ((short)(object)right));
}
if (typeof(T) == typeof(sbyte))
{
return (T)(object)(((sbyte)(object)left) * ((sbyte)(object)right));
}
if (typeof(T) == typeof(long))
{
return (T)(object)(((long)(object)left) * ((long)(object)right));
}
if (typeof(T) == typeof(ulong))
{
return (T)(object)(((ulong)(object)left) * ((ulong)(object)right));
}
else
{
throw new ArgumentException();
}
}
public static T[] GetRandomArray<T>(int size, Random random)
where T : struct, IComparable<T>, IEquatable<T>
{
T[] result = new T[size];
for (int i = 0; i < size; i++)
{
int data = random.Next(100);
result[i] = GetValueFromInt<T>(data);
}
return result;
}
}
class JitLog : IDisposable
{
FileStream fileStream;
bool simdIntrinsicsSupported;
private static String GetLogFileName()
{
String jitLogFileName = Environment.GetEnvironmentVariable("COMPlus_JitFuncInfoLogFile");
return jitLogFileName;
}
public JitLog()
{
fileStream = null;
simdIntrinsicsSupported = Vector.IsHardwareAccelerated;
String jitLogFileName = GetLogFileName();
if (jitLogFileName == null)
{
Console.WriteLine("No JitLogFile");
return;
}
if (!File.Exists(jitLogFileName))
{
Console.WriteLine("JitLogFile " + jitLogFileName + " not found.");
return;
}
File.Copy(jitLogFileName, "Temp.log", true);
fileStream = new FileStream("Temp.log", FileMode.Open, FileAccess.Read, FileShare.Read);
}
public void Dispose()
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
public bool IsEnabled()
{
return (fileStream != null);
}
//------------------------------------------------------------------------
// Check: Check to see whether 'method' was recognized as an intrinsic by the JIT.
//
// Arguments:
// method - The method name, as a string
//
// Return Value:
// If the JitLog is not enabled (either the environment variable is not set,
// or the file was not found, e.g. if the JIT doesn't support it):
// - Returns true
// If SIMD intrinsics are enabled:
// - Returns true if the method was NOT compiled, otherwise false
// Else (if SIMD intrinsics are NOT enabled):
// - Returns true.
// Note that it might be useful to return false if the method was not compiled,
// but it will not be logged as compiled if it is inlined.
//
// Assumptions:
// The JitLog constructor queries Vector.IsHardwareAccelerated to determine
// if SIMD intrinsics are enabled, and depends on its correctness.
//
// Notes:
// It searches for the string verbatim. If 'method' is not fully qualified
// or its signature is not provided, it may result in false matches.
//
// Example:
// CheckJitLog("System.Numerics.Vector4:op_Addition(struct,struct):struct");
//
public bool Check(String method)
{
// Console.WriteLine("Checking for " + method + ":");
if (!IsEnabled())
{
Console.WriteLine("JitLog not enabled.");
return true;
}
try
{
fileStream.Position = 0;
StreamReader reader = new StreamReader(fileStream);
bool methodFound = false;
while ((reader.Peek() >= 0) && (methodFound == false))
{
String s = reader.ReadLine();
if (s.IndexOf(method) != -1)
{
methodFound = true;
}
}
if (simdIntrinsicsSupported && methodFound)
{
Console.WriteLine("Method " + method + " was compiled but should not have been");
return false;
}
// Useful when developing / debugging just to be sure that we reached here:
// Console.WriteLine(method + ((methodFound) ? " WAS COMPILED" : " WAS NOT COMPILED"));
return true;
}
catch (Exception e)
{
Console.WriteLine("Error checking JitLogFile: " + e.Message);
return false;
}
}
// Check: Check to see Vector<'elementType'>:'method' was recognized as an
// intrinsic by the JIT.
//
// Arguments:
// method - The method name, without its containing type (which is Vector<T>)
// elementType - The type with which Vector<T> is instantiated.
//
// Return Value:
// See the other overload, above.
//
// Assumptions:
// The JitLog constructor queries Vector.IsHardwareAccelerated to determine
// if SIMD intrinsics are enabled, and depends on its correctness.
//
// Notes:
// It constructs the search string based on the way generic types are currently
// dumped by the CLR. If the signature is not provided for the method, it
// may result in false matches.
//
// Example:
// CheckJitLog("op_Addition(struct,struct):struct", "Single");
//
public bool Check(String method, String elementType)
{
String checkString = "System.Numerics.Vector`1[" + elementType + "][System." + elementType + "]:" + method;
return Check(checkString);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class UnaryDecrementTests : IncrementDecrementTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUnaryDecrementShortTest(bool useInterpreter)
{
short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementShort(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUnaryDecrementUShortTest(bool useInterpreter)
{
ushort[] values = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementUShort(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUnaryDecrementIntTest(bool useInterpreter)
{
int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementInt(values[i], useInterpreter);
VerifyDecrementIntMakeUnary(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUnaryDecrementUIntTest(bool useInterpreter)
{
uint[] values = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementUInt(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUnaryDecrementLongTest(bool useInterpreter)
{
long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementLong(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUnaryDecrementULongTest(bool useInterpreter)
{
ulong[] values = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementULong(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecrementFloatTest(bool useInterpreter)
{
float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementFloat(values[i], useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecrementDoubleTest(bool useInterpreter)
{
double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
VerifyDecrementDouble(values[i], useInterpreter);
}
}
[Fact]
public static void ToStringTest()
{
UnaryExpression e = Expression.Decrement(Expression.Parameter(typeof(int), "x"));
Assert.Equal("Decrement(x)", e.ToString());
}
[Theory, MemberData(nameof(NonArithmeticObjects), true)]
public static void DecrementNonArithmetic(object value)
{
Expression ex = Expression.Constant(value);
Assert.Throws<InvalidOperationException>(() => Expression.Decrement(ex));
}
[Theory, PerCompilationType(nameof(DecrementableValues), false)]
public static void CustomOpDecrement(Decrementable operand, Decrementable expected, bool useInterpreter)
{
Func<Decrementable> func = Expression.Lambda<Func<Decrementable>>(
Expression.Decrement(Expression.Constant(operand))).Compile(useInterpreter);
Assert.Equal(expected.Value, func().Value);
}
[Theory, PerCompilationType(nameof(DoublyDecrementedDecrementableValues), false)]
public static void UserDefinedOpDecrement(Decrementable operand, Decrementable expected, bool useInterpreter)
{
MethodInfo method = typeof(IncrementDecrementTests).GetMethod(nameof(DoublyDecrement));
Func<Decrementable> func = Expression.Lambda<Func<Decrementable>>(
Expression.Decrement(Expression.Constant(operand), method)).Compile(useInterpreter);
Assert.Equal(expected.Value, func().Value);
}
[Theory, PerCompilationType(nameof(DoublyDecrementedInt32s), false)]
public static void UserDefinedOpDecrementArithmeticType(int operand, int expected, bool useInterpreter)
{
MethodInfo method = typeof(IncrementDecrementTests).GetMethod(nameof(DoublyDecrementInt32));
Func<int> func = Expression.Lambda<Func<int>>(
Expression.Decrement(Expression.Constant(operand), method)).Compile(useInterpreter);
Assert.Equal(expected, func());
}
[Fact]
public static void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.Decrement(null));
}
[Fact]
public static void UnreadableOperand()
{
Expression operand = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
Assert.Throws<ArgumentException>("expression", () => Expression.Decrement(operand));
}
#endregion
#region Test verifiers
private static void VerifyDecrementShort(short value, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Decrement(Expression.Constant(value, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short)(--value)), f());
}
private static void VerifyDecrementUShort(ushort value, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Decrement(Expression.Constant(value, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(--value)), f());
}
private static void VerifyDecrementInt(int value, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Decrement(Expression.Constant(value, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((int)(--value)), f());
}
private static void VerifyDecrementIntMakeUnary(int value, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.MakeUnary(ExpressionType.Decrement, Expression.Constant(value), null),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(--value), f());
}
private static void VerifyDecrementUInt(uint value, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Decrement(Expression.Constant(value, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((uint)(--value)), f());
}
private static void VerifyDecrementLong(long value, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Decrement(Expression.Constant(value, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((long)(--value)), f());
}
private static void VerifyDecrementULong(ulong value, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Decrement(Expression.Constant(value, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ulong)(--value)), f());
}
private static void VerifyDecrementFloat(float value, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Decrement(Expression.Constant(value, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal((float)(--value), f());
}
private static void VerifyDecrementDouble(double value, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Decrement(Expression.Constant(value, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal((double)(--value), f());
}
#endregion
}
}
| |
// Copyright (c) 2015 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 System.Collections;
using System.Text;
using Alachisoft.NCache.Caching.Topologies;
using Alachisoft.NCache.Caching.Statistics;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Caching.Util;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Caching.Queries;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Caching.Queries;
using System.Collections.Generic;
using Runtime = Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Persistence;
namespace Alachisoft.NCache.Caching.Topologies.Local
{
internal class LocalCacheImpl : CacheBase, ICacheEventsListener
{
/// <summary> The en-wrapped instance of cache. </summary>
private CacheBase _cache;
public LocalCacheImpl()
{
}
/// <summary>
/// Default constructor.
/// </summary>
public LocalCacheImpl(CacheBase cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
_cache = cache;
_context = cache.InternalCache.Context;
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
if (_cache != null)
{
_cache.Dispose();
_cache = null;
}
base.Dispose();
}
#endregion
/// <summary>
/// get/set listener of Cache events. 'null' implies no listener.
/// </summary>
public CacheBase Internal
{
get { return _cache; }
set
{
_cache = value;
_context = value.InternalCache.Context;
}
}
/// <summary>
/// Returns the cache local to the node, i.e., internal cache.
/// </summary>
protected internal override CacheBase InternalCache
{
get { return _cache; }
}
public override TypeInfoMap TypeInfoMap
{
get
{
return _cache.TypeInfoMap;
}
}
/// <summary>
/// get/set the name of the cache.
/// </summary>
public override string Name
{
get { return Internal.Name; }
set { Internal.Name = value; }
}
/// <summary>
/// get/set listener of Cache events. 'null' implies no listener.
/// </summary>
public override ICacheEventsListener Listener
{
get { return Internal.Listener; }
set { Internal.Listener = value; }
}
/// <summary>
/// Notifications are enabled.
/// </summary>
public override Notifications Notifiers
{
get { return Internal.Notifiers; }
set { Internal.Notifiers = value; }
}
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public override long Count
{
get
{
return Internal.Count;
}
}
/// <summary>
/// returns the statistics of the Clustered Cache.
/// </summary>
public override CacheStatistics Statistics
{
get
{
return Internal.Statistics;
}
}
/// <summary>
/// returns the statistics of the Clustered Cache.
/// </summary>
internal override CacheStatistics ActualStats
{
get
{
return Internal.ActualStats;
}
}
public override void UpdateClientsList(Hashtable list)
{
Internal.UpdateClientsList(list);
}
#region / --- ICache --- /
/// Removes all entries from the store.
/// </summary>
public override void Clear(CallbackEntry cbEntry, OperationContext operationContext)
{
Internal.Clear(cbEntry, operationContext);
}
/// <summary>
/// Determines whether the cache contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the cache.</param>
/// <returns>true if the cache contains an element
/// with the specified key; otherwise, false.</returns>
public override bool Contains(object key, OperationContext operationContext)
{
return Internal.Contains(key, operationContext);
}
/// <summary>
/// Determines whether the cache contains the specified keys.
/// </summary>
/// <param name="keys">The keys to locate in the cache.</param>
/// <returns>list of existing keys.</returns>
public override Hashtable Contains(object[] keys, OperationContext operationContext)
{
return Internal.Contains(keys, operationContext);
}
/// <summary>
/// Retrieve the object from the cache. A string key is passed as parameter.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="lockId"></param>
/// <param name="lockDate"></param>
/// <param name="lockExpiration"></param>
/// <param name="accessType"></param>
/// <param name="operationContext"></param>
/// <returns>cache entry.</returns>
public override CacheEntry Get(object key, ref object lockId, ref DateTime lockDate, LockExpiration lockExpiration, LockAccessType accessType, OperationContext operationContext)
{
CacheEntry entry = Internal.Get(key, ref lockId, ref lockDate, lockExpiration, accessType, operationContext);
if (entry != null && KeepDeflattedValues)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
return entry;
}
/// <summary>
/// Retrieve the objects from the cache. An array of keys is passed as parameter.
/// </summary>
/// <param name="key">keys of the entries.</param>
/// <returns>cache entries.</returns>
public override Hashtable Get(object[] keys, OperationContext operationContext)
{
Hashtable data = Internal.Get(keys, operationContext);
if (data != null && KeepDeflattedValues)
{
IDictionaryEnumerator ide = data.GetEnumerator();
CacheEntry entry;
while (ide.MoveNext())
{
entry = ide.Value as CacheEntry;
if (entry != null)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
}
}
return data;
}
/// <summary>
/// Adds a pair of key and value to the cache. Throws an exception or reports error
/// if the specified key already exists in the cache.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="cacheEntry">the cache entry.</param>
/// <returns>returns the result of operation.</returns>
public override CacheAddResult Add(object key, CacheEntry cacheEntry, bool notify, OperationContext operationContext)
{
CacheAddResult result = CacheAddResult.Failure;
if (Internal != null)
{
result = Internal.Add(key, cacheEntry, notify, operationContext);
}
return result;
}
/// <summary>
/// Add ExpirationHint against the given key
/// Key must already exists in the cache
/// </summary>
/// <param name="key"></param>
/// <param name="eh"></param>
/// <returns></returns>
public override bool Add(object key, ExpirationHint eh, OperationContext operationContext)
{
bool result = false;
if (Internal != null)
{
result = Internal.Add(key, eh, operationContext);
}
return result;
}
/// <summary>
/// Adds key and value pairs to the cache. Throws an exception or returns the
/// list of keys that already exists in the cache.
/// </summary>
/// <param name="keys">key of the entry.</param>
/// <param name="cacheEntries">the cache entry.</param>
/// <returns>List of keys that are added or that alredy exists in the cache and their status</returns>
public override Hashtable Add(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
{
Hashtable table = new Hashtable();
if (Internal != null)
{
table = Internal.Add(keys, cacheEntries, notify, operationContext);
}
return table;
}
/// <summary>
/// Adds a pair of key and value to the cache. If the specified key already exists
/// in the cache; it is updated, otherwise a new item is added to the cache.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="cacheEntry">the cache entry.</param>
/// <returns>returns the result of operation.</returns>
public override CacheInsResultWithEntry Insert(object key, CacheEntry cacheEntry, bool notify, object lockId, LockAccessType accessType, OperationContext operationContext)
{
CacheInsResultWithEntry retVal = new CacheInsResultWithEntry();
if (Internal != null)
{
retVal = Internal.Insert(key, cacheEntry, notify, lockId, accessType, operationContext);
}
return retVal;
}
/// <summary>
/// Adds key and value pairs to the cache. If any of the specified key already exists
/// in the cache; it is updated, otherwise a new item is added to the cache.
/// </summary>
/// <param name="keys">keys of the entries.</param>
/// <param name="cacheEntries">the cache entries.</param>
/// <returns>returns the results for inserted keys</returns>
public override Hashtable Insert(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext)
{
Hashtable retVal = null;
if (Internal != null)
{
retVal = Internal.Insert(keys, cacheEntries, notify, operationContext);
}
return retVal;
}
public override object RemoveSync(object[] keys, ItemRemoveReason reason, bool notify, OperationContext operationContext)
{
ArrayList depenedentItemList = new ArrayList();
try
{
Hashtable totalRemovedItems = new Hashtable();
CacheEntry entry = null;
IDictionaryEnumerator ide = null;
for (int i = 0; i < keys.Length; i++)
{
try
{
if (keys[i] != null)
entry = Internal.Remove(keys[i], reason, false, null, LockAccessType.IGNORE_LOCK, operationContext);
if (entry != null)
{
totalRemovedItems.Add(keys[i], entry);
}
}
catch (Exception ex)
{
}
}
ide = totalRemovedItems.GetEnumerator();
while (ide.MoveNext())
{
try
{
entry = ide.Value as CacheEntry;
if (entry != null)
{
if (entry.Value is CallbackEntry)
{
EventId eventId = null;
OperationID opId = operationContext.OperatoinID;
CallbackEntry cbEtnry = (CallbackEntry)entry.Value;
EventContext eventContext = null;
if (cbEtnry != null && cbEtnry.ItemRemoveCallbackListener != null && cbEtnry.ItemRemoveCallbackListener.Count > 0)
{
//generate event id
if (!operationContext.Contains(OperationContextFieldName.EventContext)) //for atomic operations
{
eventId = EventId.CreateEventId(opId);
}
else //for bulk
{
eventId = ((EventContext)operationContext.GetValueByField(OperationContextFieldName.EventContext)).EventID;
}
eventId.EventType = EventType.ITEM_REMOVED_CALLBACK;
eventContext = new EventContext();
eventContext.Add(EventContextFieldName.EventID, eventId);
EventCacheEntry eventCacheEntry = CacheHelper.CreateCacheEventEntry(cbEtnry.ItemRemoveCallbackListener, entry);
eventContext.Item = eventCacheEntry;
eventContext.Add(EventContextFieldName.ItemRemoveCallbackList, cbEtnry.ItemRemoveCallbackListener.Clone());
//Will always reaise the whole entry for old clients
NotifyCustomRemoveCallback(ide.Key, entry, reason, true, operationContext, eventContext);
}
}
}
}
catch (Exception ex)
{
}
}
}
catch (Exception)
{
throw;
}
return depenedentItemList;
}
/// <summary>
/// Removes the object and key pair from the cache. The key is specified as parameter.
/// Moreover it take a removal reason and a boolean specifying if a notification should
/// be raised.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="ir"></param>
/// <param name="notify">boolean specifying to raise the event.</param>
/// <param name="lockId"></param>
/// <param name="accessType"></param>
/// <param name="operationContext"></param>
/// <param name="removalReason">reason for the removal.</param>
/// <returns>item value</returns>
public override CacheEntry Remove(object key, ItemRemoveReason ir, bool notify, object lockId, LockAccessType accessType, OperationContext operationContext)
{
CacheEntry retVal = Internal.Remove(key, ir, notify, lockId, accessType, operationContext);
return retVal;
}
/// <summary>
/// Removes the key and pairs from the cache. The keys are specified as parameter.
/// Moreover it take a removal reason and a boolean specifying if a notification should
/// be raised.
/// </summary>
/// <param name="keys">key of the entries.</param>
/// <param name="removalReason">reason for the removal.</param>
/// <param name="notify">boolean specifying to raise the event.</param>
/// <returns>removed keys list</returns>
public override Hashtable Remove(object[] keys, ItemRemoveReason ir, bool notify, OperationContext operationContext)
{
Hashtable retVal = Internal.Remove(keys, ir, notify, operationContext);
return retVal;
}
public override QueryResultSet Search(string query, IDictionary values, OperationContext operationContext)
{
return Internal.Search(query, values, operationContext);
}
public override QueryResultSet SearchEntries(string query, IDictionary values, OperationContext operationContext)
{
QueryResultSet resultSet = Internal.SearchEntries(query, values, operationContext);
if (resultSet.SearchEntriesResult != null && KeepDeflattedValues)
{
IDictionaryEnumerator ide = resultSet.SearchEntriesResult.GetEnumerator();
CacheEntry entry;
while (ide.MoveNext())
{
entry = ide.Value as CacheEntry;
if (entry != null)
{
entry.KeepDeflattedValue(_context.SerializationContext);
}
}
}
return resultSet;
}
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
/// <returns>IDictionaryEnumerator enumerator.</returns>
public override IDictionaryEnumerator GetEnumerator()
{
return Internal.GetEnumerator();
}
public override EnumerationDataChunk GetNextChunk(EnumerationPointer pointer, OperationContext operationContext)
{
return Internal.GetNextChunk(pointer, operationContext);
}
#endregion
#region/ --- Key based notification registration --- /
public override void RegisterKeyNotification(string key, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.RegisterKeyNotification(key, updateCallback, removeCallback, operationContext);
}
public override void RegisterKeyNotification(string[] keys, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.RegisterKeyNotification(keys, updateCallback, removeCallback, operationContext);
}
public override void UnregisterKeyNotification(string key, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.UnregisterKeyNotification(key, updateCallback, removeCallback, operationContext);
}
public override void UnregisterKeyNotification(string[] keys, CallbackInfo updateCallback, CallbackInfo removeCallback, OperationContext operationContext)
{
Internal.UnregisterKeyNotification(keys, updateCallback, removeCallback, operationContext);
}
#endregion
public override void UnLock(object key, object lockId, bool isPreemptive, OperationContext operationContext)
{
Internal.UnLock(key, lockId, isPreemptive, operationContext);
}
public override LockOptions Lock(object key, LockExpiration lockExpiration, ref object lockId, ref DateTime lockDate, OperationContext operationContext)
{
return Internal.Lock(key, lockExpiration, ref lockId, ref lockDate, operationContext);
}
public override LockOptions IsLocked(object key, ref object lockId, ref DateTime lockDate, OperationContext operationContext)
{
return Internal.IsLocked(key, ref lockId, ref lockDate, operationContext);
}
#region ICacheEventsListener Members
void ICacheEventsListener.OnCustomUpdateCallback(object key, object value, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnCustomRemoveCallback(object key, object value, ItemRemoveReason reason, OperationContext operationContext, EventContext eventContext)
{
throw new Exception("The method or operation is not implemented.");
}
void ICacheEventsListener.OnHashmapChanged(Alachisoft.NCache.Common.DataStructures.NewHashmap newHashmap, bool updateClientMap)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
#region Header
//
// CmdNestedFamilies.cs - list nested family files and instances in a family document
//
// Copyright (C) 2010-2021 by Jeremy Tammik, Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace BuildingCoder
{
/// <summary>
/// This class contains functions for dealing with
/// nested families within a Revit family document.
/// </summary>
public class NestedFamilyFunctions
{
#region Public Methods
/// <summary>
/// Returns a list of the nested family files in the
/// given family document whose name matches the given
/// family file name filter. Useful for checking to
/// see if a family desired for nesting into the host
/// family document is already nested in.
/// Filtering is done with a simple Contains (substring)
/// check, so wildcards don't work.
/// </summary>
/// <param name="familyFileNameFilter">The portion of the family file loaded into the family document</param>
/// <param name="familyDocument">The family document being queried</param>
/// <param name="caseSensitiveFiltering">Whether or not the filter checking is case-sensitive</param>
/// <example>
/// GetFilteredNestedFamilyFiles("window", document, false);
/// </example>
/// <remarks>
/// Because standard Revit filtering techniques fail when searching for nested families in a
/// family document, we have no choice but to iterate over all elements in the family.
/// While there usually aren't that many elements at the family level, nonetheless this method
/// has been built for speed.
/// </remarks>
/// <returns>
/// A collection of family file definitions nested into the given family document.
/// </returns>
public static IEnumerable<Family>
GetFilteredNestedFamilyDefinitions(
string familyFileNameFilter,
Document familyDocument,
bool caseSensitiveFiltering)
{
// Following good SOA practices, verify the
// incoming data can be worked with.
ValidateFamilyDocument(familyDocument); // Throws an exception if not a family doc
// The filter can be null, the filter matching function checks for that.
#if _2010
List<Family> oResult = new List<Family>();
ElementIterator it = familyDocument.Elements;
while( it.MoveNext() )
{
Element oElement = it.Current as Element;
if( ( oElement is Family )
&& FilterMatches( oElement.Name,
familyFileNameFilter, caseSensitiveFiltering ) )
{
oResult.Add( oElement as Family );
}
}
#endif // _2010
var collector
= new FilteredElementCollector(familyDocument);
collector.OfClass(typeof(Family));
var familiesMatching =
from f in collector
where FilterMatches(f.Name, familyFileNameFilter, caseSensitiveFiltering)
select f;
return familiesMatching.Cast<Family>();
}
/// <summary>
/// Returns a list of family instances found in the given family document whose family file
/// name matches the given familyFileNameFilter and whose type name matches the given
/// typeNameFilter. If no filter values are provided (or they evaluate to the empty string
/// when trimmed) then all instances will be evaluated.
/// Filtering is done with a simple Contains (substring) check, so wildcards don't work.
/// </summary>
/// <param name="familyFileNameFilter">The portion of the nested family file name (or exact match) to find</param>
/// <param name="typeNameFilter">The portion of the type name (or exact match) to find</param>
/// <param name="familyDocument">The family document to search.</param>
/// <param name="caseSensitiveFiltering">Whether or not the filter checking is case-sensitive</param>
/// <example>
/// GetFilteredNestedFamilyInstances("window", "double-hung", document, false);
/// </example>
/// <remarks>
/// Because standard Revit filtering techniques fail when searching for nested families in a
/// family document, we have no choice but to iterate over all elements in the family.
/// While there usually aren't that many elements at the family level, nonetheless this method
/// has been built for MAXIMUM SPEED.
/// </remarks>
/// <returns>
/// A collection of matching nested family file instances.
/// </returns>
public static List<FamilyInstance>
GetFilteredNestedFamilyInstances(
string familyFileNameFilter,
string typeNameFilter,
Document familyDocument,
bool caseSensitiveFiltering)
{
// Following good SOA practices, verify the
// incoming data can be worked with.
ValidateFamilyDocument(familyDocument); // Throws an exception if not a family doc
// The filters can be null
var oResult
= new List<FamilyInstance>();
FamilyInstance oFamilyInstanceCandidate;
FamilySymbol oFamilySymbolCandidate;
var oMatchingNestedFamilies
= new List<Family>();
var oAllFamilyInstances
= new List<FamilyInstance>();
var bFamilyFileNameFilterExists = true;
var bTypeNameFilterExists = true;
// Set up some fast-to-test boolean values, which will be
// used for short-circuit Boolean evaluation later.
if (string.IsNullOrEmpty(familyFileNameFilter)) bFamilyFileNameFilterExists = false;
if (string.IsNullOrEmpty(typeNameFilter)) bTypeNameFilterExists = false;
// Unfortunately detecting nested families in a family document requires iterating
// over all the elements in the document, because the built-in filtering mechanism
// doesn't work for this case. However, families typically don't have nearly as many
// elements as a whole project, so the performance hit shouldn't be too bad.
// Still, the fastest performance should come by iterating over all elements in the given
// family document exactly once, keeping subsets of the family instances found for
// later testing against the nested family file matches found.
var fFamilyClass = new ElementClassFilter(typeof(Family));
var fFamInstClass = new ElementClassFilter(typeof(FamilyInstance));
var f = new LogicalOrFilter(fFamilyClass, fFamInstClass);
var collector = new FilteredElementCollector(familyDocument);
collector.WherePasses(f);
foreach (var e in collector)
// See if this is a family file nested into the current family document.
if (e is Family oNestedFamilyFileCandidate)
{
// Must ask the "Element" version for it's name, because the Family object's
// name is always the empty string.
if (!bFamilyFileNameFilterExists
|| FilterMatches(oNestedFamilyFileCandidate.Name,
familyFileNameFilter, caseSensitiveFiltering))
// This is a nested family file, and either no valid family file name filter was
// given, or the name of this family file matches the filter.
oMatchingNestedFamilies.Add(oNestedFamilyFileCandidate);
}
else
{
// This element is not a nested family file definition, see if it's a
// nested family instance.
oFamilyInstanceCandidate
= e as FamilyInstance;
if (oFamilyInstanceCandidate != null)
// Just add the family instance to our "all" collection for later testing
// because we may not have yet found all the matching nested family file
// definitions.
oAllFamilyInstances.Add(oFamilyInstanceCandidate);
}
// See if any matching nested family file definitions were found. Only do any
// more work if at least one was found.
foreach (var oMatchingNestedFamilyFile
in oMatchingNestedFamilies)
// Count backwards through the all family instances list. As we find
// matches on this iteration through the matching nested families, we can
// delete them from the candidates list to reduce the number of family
// instance candidates to test for later matching nested family files to be tested
for (var iCounter = oAllFamilyInstances.Count - 1;
iCounter >= 0;
iCounter--)
{
oFamilyInstanceCandidate
= oAllFamilyInstances[iCounter];
#if _2010
oFamilySymbolCandidate
= oFamilyInstanceCandidate.ObjectType
as FamilySymbol;
#endif // _2010
var id = oFamilyInstanceCandidate.GetTypeId();
oFamilySymbolCandidate = familyDocument.GetElement(id)
as FamilySymbol;
if (oFamilySymbolCandidate.Family.UniqueId
== oMatchingNestedFamilyFile.UniqueId)
{
// Only add this family instance to the results if there was no type name
// filter, or this family instance's type matches the given filter.
if (!bTypeNameFilterExists
|| FilterMatches(oFamilyInstanceCandidate.Name,
typeNameFilter, caseSensitiveFiltering))
oResult.Add(oFamilyInstanceCandidate);
// No point in testing this one again,
// since we know its family definition
// has already been processed.
oAllFamilyInstances.RemoveAt(iCounter);
}
} // Next family instance candidate
return oResult;
}
/// <summary>
/// Returns a reference to the FAMILY parameter (as a simple Parameter data type) on the given instance
/// for the parameter with the given name. Will return the parameter
/// whether it is an instance or type parameter.
/// Returns null if no parameter on the instance was found.
/// </summary>
/// <param name="nestedFamilyInstance">An instance of a nested family file</param>
/// <param name="parameterName">The name of the desired parameter to get a reference to</param>
/// <remarks>
/// Even though the data type returned is the more generic Parameter type, it will
/// actually be for the data of the internal FamilyParameter object.
/// </remarks>
/// <returns></returns>
public static Parameter GetFamilyParameter(
FamilyInstance nestedFamilyInstance,
string parameterName)
{
// Following good SOA practices, verify the
// incoming parameters before attempting to proceed.
if (nestedFamilyInstance == null)
throw new ArgumentNullException(
"nestedFamilyInstance");
if (string.IsNullOrEmpty(parameterName))
throw new ArgumentNullException(
"parameterName");
Parameter oResult = null;
// See if the parameter is an Instance parameter
//oResult = nestedFamilyInstance.get_Parameter( parameterName ); // 2014
Debug.Assert(2 > nestedFamilyInstance.GetParameters(parameterName).Count,
"ascertain that there are not more than one parameter of the given name");
oResult = nestedFamilyInstance.LookupParameter(parameterName); // 2015
// No? See if it's a Type parameter
if (oResult == null)
{
//oResult = nestedFamilyInstance.Symbol.get_Parameter( parameterName ); // 2014
Debug.Assert(2 > nestedFamilyInstance.Symbol.GetParameters(parameterName).Count,
"ascertain that there are not more than one parameter of the given name");
oResult = nestedFamilyInstance.Symbol.LookupParameter(parameterName); // 2015
}
return oResult;
}
/// <summary>
/// This method takes an instance of a nested family and links a parameter on it to
/// a parameter on the given host family instance. This allows a change at the host
/// level to automatically be sent down and applied to the nested family instance.
/// </summary>
/// <param name="hostFamilyDocument">The host family document to have one of its parameters be linked to a parameter on the given nested family instance</param>
/// <param name="nestedFamilyInstance">The nested family whose parameter should be linked to a parameter on the host family</param>
/// <param name="nestedFamilyParameterName">The name of the parameter on the nested family to link to the host family parameter</param>
/// <param name="hostFamilyParameterNameToLink">The name of the parameter on the host family to link to a parameter on the given nested family instance</param>
public static void
LinkNestedFamilyParameterToHostFamilyParameter(
Document hostFamilyDocument,
FamilyInstance nestedFamilyInstance,
string nestedFamilyParameterName,
string hostFamilyParameterNameToLink)
{
// Following good SOA practices, verify the incoming
// parameters before attempting to proceed.
ValidateFamilyDocument(hostFamilyDocument); // Throws an exception if is not valid family doc
if (nestedFamilyInstance == null)
throw new ArgumentNullException(
"nestedFamilyInstance");
if (string.IsNullOrEmpty(nestedFamilyParameterName))
throw new ArgumentNullException(
"nestedFamilyParameterName");
if (string.IsNullOrEmpty(hostFamilyParameterNameToLink))
throw new ArgumentNullException(
"hostFamilyParameterNameToLink");
var oNestedFamilyParameter
= GetFamilyParameter(nestedFamilyInstance,
nestedFamilyParameterName);
if (oNestedFamilyParameter == null)
throw new Exception($"Parameter '{nestedFamilyParameterName}' was not found on the nested family '{nestedFamilyInstance.Symbol.Name}'");
var oHostFamilyParameter
= hostFamilyDocument.FamilyManager.get_Parameter(
hostFamilyParameterNameToLink);
if (oHostFamilyParameter == null)
throw new Exception($"Parameter '{hostFamilyParameterNameToLink}' was not found on the host family.");
hostFamilyDocument.FamilyManager
.AssociateElementParameterToFamilyParameter(
oNestedFamilyParameter, oHostFamilyParameter);
}
#endregion // Public Methods
#region Private Helper Methods
/// <summary>
/// Returns whether or not the nameToCheck matches the given filter.
/// This is done with a simple Contains check, so wildcards won't work.
/// </summary>
/// <param name="nameToCheck">The name (e.g. type name or family file name) to check for a match with the filter</param>
/// <param name="filter">The filter to compare to</param>
/// <param name="caseSensitiveComparison">Whether or not the comparison is case-sensitive.</param>
/// <returns></returns>
private static bool FilterMatches(
string nameToCheck,
string filter,
bool caseSensitiveComparison)
{
var bResult = false;
if (string.IsNullOrEmpty(nameToCheck))
// No name given, so the call must fail.
return false;
if (string.IsNullOrEmpty(filter))
// No filter given, so the given name passes the test
return true;
if (!caseSensitiveComparison)
{
// Since the String.Contains function only does case-sensitive checks,
// cheat with our copies of the values which we'll use for the comparison.
nameToCheck = nameToCheck.ToUpper();
filter = filter.ToUpper();
}
bResult = nameToCheck.Contains(filter);
return bResult;
}
/// <summary>
/// This method will validate the provided Revit Document to make sure the reference
/// exists and is for a FAMILY document. It will throw an ArgumentNullException
/// if nothing is sent, and will throw an ArgumentOutOfRangeException if the document
/// provided isn't a family document (e.g. is a project document)
/// </summary>
/// <param name="document">The Revit document being tested</param>
private static void ValidateFamilyDocument(
Document document)
{
if (null == document) throw new ArgumentNullException("document");
if (!document.IsFamilyDocument)
throw new ArgumentOutOfRangeException(
"The document provided is not a Family Document.");
}
#endregion Private Helper Methods
}
[Transaction(TransactionMode.ReadOnly)]
internal class CmdNestedFamilies : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var app = commandData.Application;
var doc = app.ActiveUIDocument.Document;
var familyFilenameFilter = string.Empty;
var typeNameFilter = string.Empty;
var caseSensitive = false;
var nestedFamilies
= NestedFamilyFunctions.GetFilteredNestedFamilyDefinitions(
familyFilenameFilter, doc, caseSensitive);
foreach (var f in nestedFamilies) Debug.WriteLine(f.Name);
var instances
= NestedFamilyFunctions.GetFilteredNestedFamilyInstances(
familyFilenameFilter, typeNameFilter, doc, caseSensitive);
foreach (var fi in instances) Debug.WriteLine(Util.ElementDescription(fi));
return Result.Failed;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Storage;
using Orleans.Streams;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private readonly Logger logger;
private readonly Logger appLogger;
private readonly ClientConfiguration config;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects;
private readonly ProxiedMessageCenter transport;
private bool listenForMessages;
private CancellationTokenSource listeningCts;
private readonly ClientProviderRuntime clientProviderRuntime;
private readonly StatisticsProviderManager statisticsProviderManager;
internal ClientStatisticsManager ClientStatistics;
private readonly GrainId clientId;
private IGrainTypeResolver grainInterfaceMap;
private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
// initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min
private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1);
private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1);
private const string BARS = "----------";
private readonly GrainFactory grainFactory;
public GrainFactory InternalGrainFactory
{
get { return grainFactory; }
}
/// <summary>
/// Response timeout.
/// </summary>
private TimeSpan responseTimeout;
private static readonly Object staticLock = new Object();
Logger IRuntimeClient.AppLogger
{
get { return appLogger; }
}
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public SiloAddress CurrentSilo
{
get { return CurrentActivationAddress.Silo; }
}
public string Identity
{
get { return CurrentActivationAddress.ToString(); }
}
public IActivationData CurrentActivationData
{
get { return null; }
}
public IAddressable CurrentGrain
{
get { return null; }
}
public IStorageProvider CurrentStorageProvider
{
get { throw new InvalidOperationException("Storage provider only available from inside grain"); }
}
internal IList<Uri> Gateways
{
get
{
return transport.GatewayManager.ListProvider.GetGateways().GetResult();
}
}
public IStreamProviderManager CurrentStreamProviderManager { get; private set; }
public IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return clientProviderRuntime; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient(ClientConfiguration cfg, GrainFactory grainFactory, bool secondary = false)
{
this.grainFactory = grainFactory;
this.clientId = GrainId.NewClientId();
if (cfg == null)
{
Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
}
this.config = cfg;
if (!LogManager.IsInitialized) LogManager.Initialize(config);
StatisticsCollector.Initialize(config);
SerializationManager.Initialize(config.UseStandardSerializer, cfg.SerializationProviders, config.UseJsonFallbackSerializer);
logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
appLogger = LogManager.GetLogger("Application", LoggerType.Application);
try
{
LoadAdditionalAssemblies();
PlacementStrategy.Initialize();
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
if (!secondary)
{
UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
// Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
SerializationManager.GetDeserializer(typeof(String));
clientProviderRuntime = new ClientProviderRuntime(grainFactory, null);
statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
{
config.StatisticsProviderName = statsProviderName;
}
responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
BufferPool.InitGlobalBufferPool(config);
var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);
// Client init / sign-on message
logger.Info(ErrorCode.ClientInitializing, string.Format(
"{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
BARS, config.DNSHostName, localAddress, clientId));
string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
BARS, RuntimeVersion.Current, PrintAppDomainDetails());
startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
logger.Info(ErrorCode.ClientStarting, startMsg);
if (TestOnlyThrowExceptionDuringInit)
{
throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
}
config.CheckGatewayProviderSettings();
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config)
.WithTimeout(initTimeout).Result;
transport = new ProxiedMessageCenter(config, localAddress, generation, clientId, gatewayListProvider);
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
private void StreamingInitialize()
{
var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result;
clientProviderRuntime.StreamingInitialize(implicitSubscriberTable);
var streamProviderManager = new Streams.StreamProviderManager();
streamProviderManager
.LoadStreamProviders(
this.config.ProviderConfigurations,
clientProviderRuntime)
.Wait();
CurrentStreamProviderManager = streamProviderManager;
}
private static void LoadAdditionalAssemblies()
{
var logger = LogManager.GetLogger("AssemblyLoader.Client", LoggerType.Runtime);
var directories =
new Dictionary<string, SearchOption>
{
{
Path.GetDirectoryName(typeof(OutsideRuntimeClient).GetTypeInfo().Assembly.Location),
SearchOption.AllDirectories
}
};
var excludeCriteria =
new AssemblyLoaderPathNameCriterion[]
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies,
AssemblyLoaderCriteria.ExcludeSystemBinaries()
};
var loadProvidersCriteria =
new AssemblyLoaderReflectionCriterion[]
{
AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider))
};
AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger);
}
private void UnhandledException(ISchedulingContext context, Exception exception)
{
logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception);
logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client.");
}
public void Start()
{
lock (staticLock)
{
if (RuntimeClient.Current != null)
throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain");
RuntimeClient.Current = this;
}
StartInternal();
logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + clientId);
}
// used for testing to (carefully!) allow two clients in the same process
internal void StartInternal()
{
transport.Start();
LogManager.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started.
CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, clientId);
ClientStatistics = new ClientStatisticsManager(config);
ClientStatistics.Start(config, statisticsProviderManager, transport, clientId)
.WaitWithThrow(initTimeout);
listeningCts = new CancellationTokenSource();
var ct = listeningCts.Token;
listenForMessages = true;
// Keeping this thread handling it very simple for now. Just queue task on thread pool.
Task.Factory.StartNew(() =>
{
try
{
RunClientMessagePump(ct);
}
catch(Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
}
}
);
grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result;
StreamingInitialize();
}
private void RunClientMessagePump(CancellationToken ct)
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartExecution();
}
while (listenForMessages)
{
var message = transport.WaitMessage(Message.Categories.Application, ct);
if (message == null) // if wait was cancelled
break;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartProcessing();
}
#endif
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.DispatchToLocalObject(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message));
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopProcessing();
incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed();
}
#endif
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}
private void DispatchToLocalObject(Message message)
{
LocalObjectData objectData;
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound_2,
String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message));
return;
}
if (localObjects.TryGetValue(observerId, out objectData))
this.InvokeLocalObjectAsync(objectData, message);
else
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message)
{
var obj = (IAddressable)objectData.LocalObject.Target;
if (obj == null)
{
//// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore.
logger.Warn(ErrorCode.Runtime_Error_100162,
String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message));
LocalObjectData ignore;
// Try to remove. If it's not there, we don't care.
localObjects.TryRemove(objectData.ObserverId, out ignore);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start);
if (start)
{
// we use Task.Run() to ensure that the message pump operates asynchronously
// with respect to the current thread. see
// http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74
// at position 54:45.
//
// according to the information posted at:
// http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr
// this idiom is dependent upon the a TaskScheduler not implementing the
// override QueueTask as task inlining (as opposed to queueing). this seems
// implausible to the author, since none of the .NET schedulers do this and
// it is considered bad form (the OrleansTaskScheduler does not do this).
//
// if, for some reason this doesn't hold true, we can guarantee what we
// want by passing a placeholder continuation token into Task.StartNew()
// instead. i.e.:
//
// return Task.StartNew(() => ..., new CancellationToken());
Func<Task> asyncFunc =
async () =>
await this.LocalObjectMessagePumpAsync(objectData);
Task.Run(asyncFunc).Ignore();
}
}
private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData)
{
while (true)
{
try
{
Message message;
lock (objectData.Messages)
{
if (objectData.Messages.Count == 0)
{
objectData.Running = false;
break;
}
message = objectData.Messages.Dequeue();
}
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke))
continue;
RequestContext.Import(message.RequestContextData);
var request = (InvokeMethodRequest)message.BodyObject;
var targetOb = (IAddressable)objectData.LocalObject.Target;
object resultObject = null;
Exception caught = null;
try
{
// exceptions thrown within this scope are not considered to be thrown from user code
// and not from runtime code.
var resultPromise = objectData.Invoker.Invoke(targetOb, request);
if (resultPromise != null) // it will be null for one way messages
{
resultObject = await resultPromise;
}
}
catch (Exception exc)
{
// the exception needs to be reported in the log or propagated back to the caller.
caught = exc;
}
if (caught != null)
this.ReportException(message, caught);
else if (message.Direction != Message.Directions.OneWay)
await this.SendResponseAsync(message, resultObject);
}catch(Exception)
{
// ignore, keep looping.
}
}
}
private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase)
{
if (message.IsExpired)
{
message.DropExpiredMessage(phase);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Task
SendResponseAsync(
Message message,
object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
return TaskDone.Done;
object deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = SerializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
SendResponse(message, Response.ExceptionResponse(exc2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.", exc2);
return TaskDone.Done;
}
// the deep-copy succeeded.
SendResponse(message, new Response(deepCopy));
return TaskDone.Done;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.BodyObject;
switch (message.Direction)
{
default:
throw new InvalidOperationException();
case Message.Directions.OneWay:
{
logger.Error(
ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
String.Format(
"Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
request.MethodId,
request.InterfaceId),
exception);
break;
}
case Message.Directions.Request:
{
Exception deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = (Exception)SerializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
SendResponse(message, Response.ExceptionResponse(ex2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
SendResponse(message, response);
break;
}
}
}
private void SendResponse(Message request, Response response)
{
var message = request.CreateResponseMessage();
message.BodyObject = response;
transport.SendMessage(message);
}
/// <summary>
/// For testing only.
/// </summary>
public void Disconnect()
{
transport.Disconnect();
}
/// <summary>
/// For testing only.
/// </summary>
public void Reconnect()
{
transport.Reconnect();
}
#region Implementation of IRuntimeClient
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")]
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var message = Message.CreateMessage(request, options);
SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments);
}
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
message.TargetGrain = targetGrainId;
if (!String.IsNullOrEmpty(genericArguments))
message.GenericGrainType = genericArguments;
if (targetGrainId.IsSystemTarget)
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = target.SystemTargetSilo;
if (target.SystemTargetSilo != null)
{
message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo);
}
}
// Client sending messages to another client (observer). Yes, we support that.
if (target.IsObserverReference)
{
message.TargetObserverId = target.ObserverId;
}
if (debugContext != null)
{
message.DebugContext = debugContext;
}
if (message.IsExpirableMessage(config))
{
// don't set expiration for system target messages.
message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW;
}
if (!oneWay)
{
var callbackData = new CallbackData(callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id), config);
callbacks.TryAdd(message.Id, callbackData);
callbackData.StartTimer(responseTimeout);
}
if (logger.IsVerbose2) logger.Verbose2("Send {0}", message);
transport.SendMessage(message);
}
private bool TryResendMessage(Message message)
{
if (!message.MayResend(config))
{
return false;
}
if (logger.IsVerbose) logger.Verbose("Resend {0}", message);
message.ResendCount = message.ResendCount + 1;
message.SetMetadata(Message.Metadata.TARGET_HISTORY, message.GetTargetHistory());
if (!message.TargetGrain.IsSystemTarget)
{
message.RemoveHeader(Message.Header.TARGET_ACTIVATION);
message.RemoveHeader(Message.Header.TARGET_SILO);
}
transport.SendMessage(message);
return true;
}
public void ReceiveResponse(Message response)
{
if (logger.IsVerbose2) logger.Verbose2("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest)
return;
CallbackData callbackData;
var found = callbacks.TryGetValue(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContext.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnRegisterCallback(CorrelationId id)
{
CallbackData ignore;
callbacks.TryRemove(id, out ignore);
}
public void Reset(bool cleanup)
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
});
Utils.SafeExecute(() =>
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset(cleanup).WaitWithThrow(resetTimeout);
}
}, logger, "Client.clientProviderRuntime.Reset");
Utils.SafeExecute(() =>
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.PrepareToStop();
}
}, logger, "Client.PrepareToStop-Transport");
listenForMessages = false;
Utils.SafeExecute(() =>
{
if (listeningCts != null)
{
listeningCts.Cancel();
}
}, logger, "Client.Stop-ListeningCTS");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
try
{
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
}
catch (Exception) { }
try
{
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception) { }
try
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}
catch (Exception) { }
try
{
LogManager.UnInitialize();
}
catch (Exception) { }
}
public void SetResponseTimeout(TimeSpan timeout)
{
responseTimeout = timeout;
}
public TimeSpan GetResponseTimeout()
{
return responseTimeout;
}
public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period)
{
throw new InvalidOperationException("RegisterReminder can only be called from inside a grain");
}
public Task UnregisterReminder(IGrainReminder reminder)
{
throw new InvalidOperationException("UnregisterReminder can only be called from inside a grain");
}
public Task<IGrainReminder> GetReminder(string reminderName)
{
throw new InvalidOperationException("GetReminder can only be called from inside a grain");
}
public Task<List<IGrainReminder>> GetReminders()
{
throw new InvalidOperationException("GetReminders can only be called from inside a grain");
}
public SiloStatus GetSiloStatus(SiloAddress silo)
{
throw new InvalidOperationException("GetSiloStatus can only be called on the silo.");
}
public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context, string activityName)
{
await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool
}
public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.");
GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId());
if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
{
throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
}
return gr;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference))
throw new ArgumentException("Argument reference is not a grain reference.");
var reference = (GrainReference) obj;
LocalObjectData ignore;
if (!localObjects.TryRemove(reference.ObserverId, out ignore))
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
public void DeactivateOnIdle(ActivationId id)
{
throw new InvalidOperationException();
}
#endregion
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload,
String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails()));
LogManager.Flush();
}
catch(Exception)
{
// just ignore, make sure not to throw from here.
}
}
private string PrintAppDomainDetails()
{
return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName);
}
private class LocalObjectData
{
internal WeakReference LocalObject { get; private set; }
internal IGrainMethodInvoker Invoker { get; private set; }
internal GuidId ObserverId { get; private set; }
internal Queue<Message> Messages { get; private set; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
LocalObject = new WeakReference(obj);
ObserverId = observerId;
Invoker = invoker;
Messages = new Queue<Message>();
Running = false;
}
}
public void Dispose()
{
if (listeningCts != null)
{
listeningCts.Dispose();
listeningCts = null;
}
GC.SuppressFinalize(this);
}
public IGrainTypeResolver GrainTypeResolver
{
get { return grainInterfaceMap; }
}
public string CaptureRuntimeEnvironment()
{
throw new NotImplementedException();
}
public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null)
{
throw new NotImplementedException();
}
public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo)
{
foreach (var callback in callbacks)
{
if (deadSilo.Equals(callback.Value.Message.TargetSilo))
{
callback.Value.OnTargetSiloFail();
}
}
}
}
}
| |
/*
* CP10081.cs - Turkish (Mac) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "mac-10081.ucm".
namespace I18N.MidEast
{
using System;
using I18N.Common;
public class CP10081 : ByteEncoding
{
public CP10081()
: base(10081, ToChars, "Turkish (Mac)",
"windows-10005", "windows-10081", "windows-10081",
false, false, false, false, 1254)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u00C4', '\u00C5', '\u00C7', '\u00C9',
'\u00D1', '\u00D6', '\u00DC', '\u00E1', '\u00E0', '\u00E2',
'\u00E4', '\u00E3', '\u00E5', '\u00E7', '\u00E9', '\u00E8',
'\u00EA', '\u00EB', '\u00ED', '\u00EC', '\u00EE', '\u00EF',
'\u00F1', '\u00F3', '\u00F2', '\u00F4', '\u00F6', '\u00F5',
'\u00FA', '\u00F9', '\u00FB', '\u00FC', '\u2020', '\u00B0',
'\u00A2', '\u00A3', '\u00A7', '\u2022', '\u00B6', '\u00DF',
'\u00AE', '\u00A9', '\u2122', '\u00B4', '\u00A8', '\u2260',
'\u00C6', '\u00D8', '\u221E', '\u00B1', '\u2264', '\u2265',
'\u00A5', '\u00B5', '\u2202', '\u2211', '\u220F', '\u03C0',
'\u222B', '\u00AA', '\u00BA', '\u2126', '\u00E6', '\u00F8',
'\u00BF', '\u00A1', '\u00AC', '\u221A', '\u0192', '\u2248',
'\u2206', '\u00AB', '\u00BB', '\u2026', '\u00A0', '\u00C0',
'\u00C3', '\u00D5', '\u0152', '\u0153', '\u2013', '\u2014',
'\u201C', '\u201D', '\u2018', '\u2019', '\u00F7', '\u25CA',
'\u00FF', '\u0178', '\u011E', '\u011F', '\u0130', '\u0131',
'\u015E', '\u015F', '\u2021', '\u00B7', '\u201A', '\u201E',
'\u2030', '\u00C2', '\u00CA', '\u00C1', '\u00CB', '\u00C8',
'\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u00D3', '\u00D4',
'\u00F0', '\u00D2', '\u00DA', '\u00DB', '\u00D9', '\u00F5',
'\u02C6', '\u02DC', '\u00AF', '\u02D8', '\u02D9', '\u02DA',
'\u00B8', '\u02DD', '\u02DB', '\u02C7',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A2:
case 0x00A3:
case 0x00A9:
case 0x00B1:
case 0x00B5:
break;
case 0x00A0: ch = 0xCA; break;
case 0x00A1: ch = 0xC1; break;
case 0x00A5: ch = 0xB4; break;
case 0x00A7: ch = 0xA4; break;
case 0x00A8: ch = 0xAC; break;
case 0x00AA: ch = 0xBB; break;
case 0x00AB: ch = 0xC7; break;
case 0x00AC: ch = 0xC2; break;
case 0x00AE: ch = 0xA8; break;
case 0x00AF: ch = 0xF8; break;
case 0x00B0: ch = 0xA1; break;
case 0x00B4: ch = 0xAB; break;
case 0x00B6: ch = 0xA6; break;
case 0x00B7: ch = 0xE1; break;
case 0x00B8: ch = 0xFC; break;
case 0x00BA: ch = 0xBC; break;
case 0x00BB: ch = 0xC8; break;
case 0x00BF: ch = 0xC0; break;
case 0x00C0: ch = 0xCB; break;
case 0x00C1: ch = 0xE7; break;
case 0x00C2: ch = 0xE5; break;
case 0x00C3: ch = 0xCC; break;
case 0x00C4: ch = 0x80; break;
case 0x00C5: ch = 0x81; break;
case 0x00C6: ch = 0xAE; break;
case 0x00C7: ch = 0x82; break;
case 0x00C8: ch = 0xE9; break;
case 0x00C9: ch = 0x83; break;
case 0x00CA: ch = 0xE6; break;
case 0x00CB: ch = 0xE8; break;
case 0x00CC: ch = 0xED; break;
case 0x00CD: ch = 0xEA; break;
case 0x00CE: ch = 0xEB; break;
case 0x00CF: ch = 0xEC; break;
case 0x00D1: ch = 0x84; break;
case 0x00D2: ch = 0xF1; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEF; break;
case 0x00D5: ch = 0xCD; break;
case 0x00D6: ch = 0x85; break;
case 0x00D8: ch = 0xAF; break;
case 0x00D9: ch = 0xF4; break;
case 0x00DA: ch = 0xF2; break;
case 0x00DB: ch = 0xF3; break;
case 0x00DC: ch = 0x86; break;
case 0x00DF: ch = 0xA7; break;
case 0x00E0: ch = 0x88; break;
case 0x00E1: ch = 0x87; break;
case 0x00E2: ch = 0x89; break;
case 0x00E3: ch = 0x8B; break;
case 0x00E4: ch = 0x8A; break;
case 0x00E5: ch = 0x8C; break;
case 0x00E6: ch = 0xBE; break;
case 0x00E7: ch = 0x8D; break;
case 0x00E8: ch = 0x8F; break;
case 0x00E9: ch = 0x8E; break;
case 0x00EA: ch = 0x90; break;
case 0x00EB: ch = 0x91; break;
case 0x00EC: ch = 0x93; break;
case 0x00ED: ch = 0x92; break;
case 0x00EE: ch = 0x94; break;
case 0x00EF: ch = 0x95; break;
case 0x00F1: ch = 0x96; break;
case 0x00F2: ch = 0x98; break;
case 0x00F3: ch = 0x97; break;
case 0x00F4: ch = 0x99; break;
case 0x00F5: ch = 0x9B; break;
case 0x00F6: ch = 0x9A; break;
case 0x00F7: ch = 0xD6; break;
case 0x00F8: ch = 0xBF; break;
case 0x00F9: ch = 0x9D; break;
case 0x00FA: ch = 0x9C; break;
case 0x00FB: ch = 0x9E; break;
case 0x00FC: ch = 0x9F; break;
case 0x00FF: ch = 0xD8; break;
case 0x011E: ch = 0xDA; break;
case 0x011F: ch = 0xDB; break;
case 0x0130: ch = 0xDC; break;
case 0x0131: ch = 0xDD; break;
case 0x0152: ch = 0xCE; break;
case 0x0153: ch = 0xCF; break;
case 0x015E: ch = 0xDE; break;
case 0x015F: ch = 0xDF; break;
case 0x0178: ch = 0xD9; break;
case 0x0192: ch = 0xC4; break;
case 0x02C6: ch = 0xF6; break;
case 0x02C7: ch = 0xFF; break;
case 0x02D8: ch = 0xF9; break;
case 0x02D9: ch = 0xFA; break;
case 0x02DA: ch = 0xFB; break;
case 0x02DB: ch = 0xFE; break;
case 0x02DC: ch = 0xF7; break;
case 0x02DD: ch = 0xFD; break;
case 0x03C0: ch = 0xB9; break;
case 0x2013: ch = 0xD0; break;
case 0x2014: ch = 0xD1; break;
case 0x2018: ch = 0xD4; break;
case 0x2019: ch = 0xD5; break;
case 0x201A: ch = 0xE2; break;
case 0x201C: ch = 0xD2; break;
case 0x201D: ch = 0xD3; break;
case 0x201E: ch = 0xE3; break;
case 0x2020: ch = 0xA0; break;
case 0x2021: ch = 0xE0; break;
case 0x2022: ch = 0xA5; break;
case 0x2026: ch = 0xC9; break;
case 0x2030: ch = 0xE4; break;
case 0x2122: ch = 0xAA; break;
case 0x2126: ch = 0xBD; break;
case 0x2202: ch = 0xB6; break;
case 0x2206: ch = 0xC6; break;
case 0x220F: ch = 0xB8; break;
case 0x2211: ch = 0xB7; break;
case 0x221A: ch = 0xC3; break;
case 0x221E: ch = 0xB0; break;
case 0x222B: ch = 0xBA; break;
case 0x2248: ch = 0xC5; break;
case 0x2260: ch = 0xAD; break;
case 0x2264: ch = 0xB2; break;
case 0x2265: ch = 0xB3; break;
case 0x25CA: ch = 0xD7; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x00A2:
case 0x00A3:
case 0x00A9:
case 0x00B1:
case 0x00B5:
break;
case 0x00A0: ch = 0xCA; break;
case 0x00A1: ch = 0xC1; break;
case 0x00A5: ch = 0xB4; break;
case 0x00A7: ch = 0xA4; break;
case 0x00A8: ch = 0xAC; break;
case 0x00AA: ch = 0xBB; break;
case 0x00AB: ch = 0xC7; break;
case 0x00AC: ch = 0xC2; break;
case 0x00AE: ch = 0xA8; break;
case 0x00AF: ch = 0xF8; break;
case 0x00B0: ch = 0xA1; break;
case 0x00B4: ch = 0xAB; break;
case 0x00B6: ch = 0xA6; break;
case 0x00B7: ch = 0xE1; break;
case 0x00B8: ch = 0xFC; break;
case 0x00BA: ch = 0xBC; break;
case 0x00BB: ch = 0xC8; break;
case 0x00BF: ch = 0xC0; break;
case 0x00C0: ch = 0xCB; break;
case 0x00C1: ch = 0xE7; break;
case 0x00C2: ch = 0xE5; break;
case 0x00C3: ch = 0xCC; break;
case 0x00C4: ch = 0x80; break;
case 0x00C5: ch = 0x81; break;
case 0x00C6: ch = 0xAE; break;
case 0x00C7: ch = 0x82; break;
case 0x00C8: ch = 0xE9; break;
case 0x00C9: ch = 0x83; break;
case 0x00CA: ch = 0xE6; break;
case 0x00CB: ch = 0xE8; break;
case 0x00CC: ch = 0xED; break;
case 0x00CD: ch = 0xEA; break;
case 0x00CE: ch = 0xEB; break;
case 0x00CF: ch = 0xEC; break;
case 0x00D1: ch = 0x84; break;
case 0x00D2: ch = 0xF1; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEF; break;
case 0x00D5: ch = 0xCD; break;
case 0x00D6: ch = 0x85; break;
case 0x00D8: ch = 0xAF; break;
case 0x00D9: ch = 0xF4; break;
case 0x00DA: ch = 0xF2; break;
case 0x00DB: ch = 0xF3; break;
case 0x00DC: ch = 0x86; break;
case 0x00DF: ch = 0xA7; break;
case 0x00E0: ch = 0x88; break;
case 0x00E1: ch = 0x87; break;
case 0x00E2: ch = 0x89; break;
case 0x00E3: ch = 0x8B; break;
case 0x00E4: ch = 0x8A; break;
case 0x00E5: ch = 0x8C; break;
case 0x00E6: ch = 0xBE; break;
case 0x00E7: ch = 0x8D; break;
case 0x00E8: ch = 0x8F; break;
case 0x00E9: ch = 0x8E; break;
case 0x00EA: ch = 0x90; break;
case 0x00EB: ch = 0x91; break;
case 0x00EC: ch = 0x93; break;
case 0x00ED: ch = 0x92; break;
case 0x00EE: ch = 0x94; break;
case 0x00EF: ch = 0x95; break;
case 0x00F1: ch = 0x96; break;
case 0x00F2: ch = 0x98; break;
case 0x00F3: ch = 0x97; break;
case 0x00F4: ch = 0x99; break;
case 0x00F5: ch = 0x9B; break;
case 0x00F6: ch = 0x9A; break;
case 0x00F7: ch = 0xD6; break;
case 0x00F8: ch = 0xBF; break;
case 0x00F9: ch = 0x9D; break;
case 0x00FA: ch = 0x9C; break;
case 0x00FB: ch = 0x9E; break;
case 0x00FC: ch = 0x9F; break;
case 0x00FF: ch = 0xD8; break;
case 0x011E: ch = 0xDA; break;
case 0x011F: ch = 0xDB; break;
case 0x0130: ch = 0xDC; break;
case 0x0131: ch = 0xDD; break;
case 0x0152: ch = 0xCE; break;
case 0x0153: ch = 0xCF; break;
case 0x015E: ch = 0xDE; break;
case 0x015F: ch = 0xDF; break;
case 0x0178: ch = 0xD9; break;
case 0x0192: ch = 0xC4; break;
case 0x02C6: ch = 0xF6; break;
case 0x02C7: ch = 0xFF; break;
case 0x02D8: ch = 0xF9; break;
case 0x02D9: ch = 0xFA; break;
case 0x02DA: ch = 0xFB; break;
case 0x02DB: ch = 0xFE; break;
case 0x02DC: ch = 0xF7; break;
case 0x02DD: ch = 0xFD; break;
case 0x03C0: ch = 0xB9; break;
case 0x2013: ch = 0xD0; break;
case 0x2014: ch = 0xD1; break;
case 0x2018: ch = 0xD4; break;
case 0x2019: ch = 0xD5; break;
case 0x201A: ch = 0xE2; break;
case 0x201C: ch = 0xD2; break;
case 0x201D: ch = 0xD3; break;
case 0x201E: ch = 0xE3; break;
case 0x2020: ch = 0xA0; break;
case 0x2021: ch = 0xE0; break;
case 0x2022: ch = 0xA5; break;
case 0x2026: ch = 0xC9; break;
case 0x2030: ch = 0xE4; break;
case 0x2122: ch = 0xAA; break;
case 0x2126: ch = 0xBD; break;
case 0x2202: ch = 0xB6; break;
case 0x2206: ch = 0xC6; break;
case 0x220F: ch = 0xB8; break;
case 0x2211: ch = 0xB7; break;
case 0x221A: ch = 0xC3; break;
case 0x221E: ch = 0xB0; break;
case 0x222B: ch = 0xBA; break;
case 0x2248: ch = 0xC5; break;
case 0x2260: ch = 0xAD; break;
case 0x2264: ch = 0xB2; break;
case 0x2265: ch = 0xB3; break;
case 0x25CA: ch = 0xD7; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP10081
public class ENCwindows_10081 : CP10081
{
public ENCwindows_10081() : base() {}
}; // class ENCwindows_10081
}; // namespace I18N.MidEast
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace UnityEditor.ShaderGraph.Drawing
{
sealed class IndexSet : ICollection<int>
{
List<uint> m_Masks = new List<uint>();
public IndexSet() {}
public IndexSet(IEnumerable<int> indices)
{
foreach (var index in indices)
Add(index);
}
public IEnumerator<int> GetEnumerator()
{
for (var i = 0; i < m_Masks.Count; i++)
{
var mask = m_Masks[i];
if (mask == 0)
continue;
for (var j = 0; j < 32; j++)
{
if ((mask & (1 << j)) > 0)
yield return i * 32 + j;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void UnionWith(IEnumerable<int> other)
{
var otherSet = other as IndexSet;
if (otherSet != null)
{
UnionWith(otherSet);
}
else
{
foreach (var index in other)
Add(index);
}
}
public void UnionWith(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
m_Masks[i] |= other.m_Masks[i];
for (var i = m_Masks.Count; i < other.m_Masks.Count; i++)
m_Masks.Add(other.m_Masks[i]);
}
public void IntersectWith(IEnumerable<int> other)
{
IntersectWith(other as IndexSet ?? new IndexSet(other));
}
public void IntersectWith(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
m_Masks[i] &= other.m_Masks[i];
}
public void ExceptWith(IEnumerable<int> other)
{
var otherSet = other as IndexSet;
if (otherSet != null)
{
ExceptWith(otherSet);
}
else
{
foreach (var index in other)
Remove(index);
}
}
public void ExceptWith(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
m_Masks[i] &= ~other.m_Masks[i];
}
public void SymmetricExceptWith(IEnumerable<int> other)
{
SymmetricExceptWith(other as IndexSet ?? new IndexSet(other));
}
public void SymmetricExceptWith(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
m_Masks[i] ^= other.m_Masks[i];
}
public bool IsSubsetOf(IEnumerable<int> other)
{
return IsSubsetOf(other as IndexSet ?? new IndexSet(other));
}
public bool IsSubsetOf(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
{
var mask = m_Masks[i];
var otherMask = other.m_Masks[i];
if ((mask & otherMask) != mask)
return false;
}
for (var i = other.m_Masks.Count; i < m_Masks.Count; i++)
{
if (m_Masks[i] > 0)
return false;
}
return true;
}
public bool IsSupersetOf(IEnumerable<int> other)
{
return IsSupersetOf(other as IndexSet ?? new IndexSet(other));
}
public bool IsSupersetOf(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
{
var otherMask = other.m_Masks[i];
var mask = m_Masks[i];
if ((otherMask & mask) != otherMask)
return false;
}
for (var i = m_Masks.Count; i < other.m_Masks.Count; i++)
{
if (other.m_Masks[i] > 0)
return false;
}
return true;
}
public bool IsProperSupersetOf(IEnumerable<int> other)
{
return IsProperSupersetOf(other as IndexSet ?? new IndexSet(other));
}
public bool IsProperSupersetOf(IndexSet other)
{
var isProper = false;
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
{
var mask = m_Masks[i];
var otherMask = other.m_Masks[i];
if ((otherMask & mask) != otherMask)
return false;
if ((~otherMask & mask) > 0)
isProper = true;
}
for (var i = m_Masks.Count; i < other.m_Masks.Count; i++)
{
if (other.m_Masks[i] > 0)
return false;
}
if (!isProper)
{
for (var i = other.m_Masks.Count; i < m_Masks.Count; i++)
{
if (m_Masks[i] > 0)
return true;
}
}
return isProper;
}
public bool IsProperSubsetOf(IEnumerable<int> other)
{
return IsProperSubsetOf(other as IndexSet ?? new IndexSet(other));
}
public bool IsProperSubsetOf(IndexSet other)
{
var isProper = false;
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
{
var mask = m_Masks[i];
var otherMask = other.m_Masks[i];
if ((mask & otherMask) != mask)
return false;
if ((~mask & otherMask) > 0)
isProper = true;
}
for (var i = other.m_Masks.Count; i < m_Masks.Count; i++)
{
if (m_Masks[i] > 0)
return false;
}
if (!isProper)
{
for (var i = m_Masks.Count; i < other.m_Masks.Count; i++)
{
if (other.m_Masks[i] > 0)
return true;
}
}
return isProper;
}
public bool Overlaps(IEnumerable<int> other)
{
var otherSet = other as IndexSet;
if (otherSet != null)
return Overlaps(otherSet);
foreach (var index in other)
{
if (Contains(index))
return true;
}
return false;
}
public bool Overlaps(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
{
if ((m_Masks[i] & other.m_Masks[i]) > 0)
return true;
}
return false;
}
public bool SetEquals(IEnumerable<int> other)
{
var otherSet = other as IndexSet;
if (otherSet != null)
return SetEquals(otherSet);
foreach (var index in other)
{
if (!Contains(index))
return false;
}
return true;
}
public bool SetEquals(IndexSet other)
{
for (var i = 0; i < Math.Min(m_Masks.Count, other.m_Masks.Count); i++)
{
if (m_Masks[i] != other.m_Masks[i])
return false;
}
for (var i = other.m_Masks.Count; i < m_Masks.Count; i++)
{
if (m_Masks[i] > 0)
return false;
}
for (var i = m_Masks.Count; i < other.m_Masks.Count; i++)
{
if (other.m_Masks[i] > 0)
return false;
}
return true;
}
public bool Add(int index)
{
var maskIndex = index >> 5;
var bitIndex = index & 31;
for (var i = m_Masks.Count; i <= maskIndex; i++)
m_Masks.Add(0);
var mask = (uint)1 << bitIndex;
var isNew = (m_Masks[maskIndex] & mask) == 0;
m_Masks[maskIndex] |= mask;
return isNew;
}
void ICollection<int>.Add(int index)
{
Add(index);
}
public void Clear()
{
m_Masks.Clear();
}
public bool Contains(int index)
{
var maskIndex = index >> 5;
var bitIndex = index & 31;
return maskIndex < m_Masks.Count && (m_Masks[maskIndex] & ((uint)1 << bitIndex)) > 0;
}
public void CopyTo(int[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public bool Remove(int index)
{
var maskIndex = index >> 5;
var bitIndex = index & 31;
if (maskIndex >= m_Masks.Count)
return false;
var mask = (uint)1 << bitIndex;
var exists = (m_Masks[maskIndex] & mask) > 0;
m_Masks[maskIndex] &= ~mask;
return exists;
}
public int Count
{
get
{
var count = 0;
foreach (var mask in m_Masks)
{
for (var j = 0; j < 32; j++)
{
if ((mask & (1 << j)) > 0)
count++;
}
}
return count;
}
}
public bool IsReadOnly
{
get { return false; }
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="ByteStream.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Stream interface for manipulating data within a stream.
//
// History:
// 02/8/2005: twillie: Initial implementation.
//
//-----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes; // for IStream
using System.Windows;
using MS.Win32; // for NativeMethods
using System.Security; // for marking critical methods
using System.Security.Permissions; // for elevations
namespace MS.Internal.IO.Packaging
{
/// <summary>
/// Class for managing an COM IStream interface.
/// </summary>
internal sealed class ByteStream : Stream
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Constructs a ByteStream class from a supplied unmanaged stream with the specified access.
/// </summary>
/// <param name="underlyingStream"></param>
/// <param name="openAccess"></param>
/// <SecurityNote>
/// Critical - We are creating an instance of SecurityCriticalDataForSet with the supplied stream.
/// The caller of this constructor should be critical and trusted since we accept a stream
/// of data from them. The data is only critical for set since it was a stream the caller
/// originally had in the first place so they could get it again if they wanted it.
/// </SecurityNote>
[SecurityCritical]
internal ByteStream(object underlyingStream, FileAccess openAccess)
{
SecuritySuppressedIStream stream = underlyingStream as SecuritySuppressedIStream;
Debug.Assert(stream != null);
_securitySuppressedIStream = new SecurityCriticalDataForSet<SecuritySuppressedIStream>(stream);
_access = openAccess;
// we only work for reading.
Debug.Assert(_access == FileAccess.Read);
}
#endregion Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return (!StreamDisposed &&
(FileAccess.Read == (_access & FileAccess.Read) ||
FileAccess.ReadWrite == (_access & FileAccess.ReadWrite)));
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return (!StreamDisposed);
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return false;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
/// <SecurityNote>
/// Critical - The stream object is marked with SUC and SecurityCritical.
/// TreatAsSafe - The caller already has access to the stream. Also, in order to
/// have created this class the caller would have had to have had
/// permission to create the unmanaged code stream already.
/// </SecurityNote>
public override long Length
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
CheckDisposedStatus();
if (!_isLengthInitialized)
{
System.Runtime.InteropServices.ComTypes.STATSTG streamStat;
// call Stat to get length back. STATFLAG_NONAME means string buffer
// is not populated.
_securitySuppressedIStream.Value.Stat(out streamStat, NativeMethods.STATFLAG_NONAME);
_isLengthInitialized = true;
_length = streamStat.cbSize;
}
Debug.Assert(_length > 0);
return _length;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
/// <SecurityNote>
/// Critical - The stream object is marked with SUC and SecurityCritical.
/// TreatAsSafe - The caller already has access to the stream. Also, in order to
/// have created this class the caller would have had to have had
/// permission to create the unmanaged code stream already.
/// </SecurityNote>
public override long Position
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
CheckDisposedStatus();
long seekPos = 0;
_securitySuppressedIStream.Value.Seek(0,
NativeMethods.STREAM_SEEK_CUR,
out seekPos);
return seekPos;
}
[SecurityCritical, SecurityTreatAsSafe]
set
{
CheckDisposedStatus();
if (!CanSeek)
{
throw new NotSupportedException(SR.Get(SRID.SetPositionNotSupported));
}
long seekPos = 0;
_securitySuppressedIStream.Value.Seek(value,
NativeMethods.STREAM_SEEK_SET,
out seekPos);
if (value != seekPos)
{
throw new IOException(SR.Get(SRID.SeekFailed));
}
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
public override void Flush()
{
// deliberate overidding noop
// do not want to do anything on a read-only stream
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <remarks>
/// ByteStream relies on underlying COM interface to
/// validate offsets.
/// </remarks>
/// <param name="offset">Offset byte count</param>
/// <param name="origin">Offset origin</param>
/// <returns>The new position within the current stream.</returns>
/// <SecurityNote>
/// Critical - The stream object is marked with SUC and SecurityCritical.
/// TreatAsSafe - The caller already has access to the stream. Also, in order to
/// have created this class the caller would have had to have had
/// permission to create the unmanaged code stream already.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposedStatus();
if (!CanSeek)
{
throw new NotSupportedException(SR.Get(SRID.SeekNotSupported));
}
long seekPos = 0;
int translatedSeekOrigin = 0;
switch (origin)
{
case SeekOrigin.Begin:
translatedSeekOrigin = NativeMethods.STREAM_SEEK_SET;
if (0 > offset)
{
throw new ArgumentOutOfRangeException("offset",
SR.Get(SRID.SeekNegative));
}
break;
case SeekOrigin.Current:
translatedSeekOrigin = NativeMethods.STREAM_SEEK_CUR;
break;
case SeekOrigin.End:
translatedSeekOrigin = NativeMethods.STREAM_SEEK_END;
break;
default:
throw new System.ComponentModel.InvalidEnumArgumentException("origin",
(int)origin,
typeof(SeekOrigin));
}
_securitySuppressedIStream.Value.Seek(offset, translatedSeekOrigin, out seekPos);
return seekPos;
}
/// <summary>
/// Sets the length of the current stream.
///
/// Not Supported in this implementation.
/// </summary>
/// <param name="newLength">New length</param>
public override void SetLength(long newLength)
{
throw new NotSupportedException(SR.Get(SRID.SetLengthNotSupported));
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the
/// position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">Read data buffer</param>
/// <param name="offset">Buffer start position</param>
/// <param name="count">Number of bytes to read</param>
/// <returns>Number of bytes actually read</returns>
/// <SecurityNote>
/// Critical - The stream object is marked with SUC and SecurityCritical.
/// TreatAsSafe - The caller already has access to the stream. Also, in order to
/// have created this class the caller would have had to have had
/// permission to create the unmanaged code stream already.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposedStatus();
if (!CanRead)
{
throw new NotSupportedException(SR.Get(SRID.ReadNotSupported));
}
int read = 0;
// optimization: if we are being asked to read zero bytes, be done.
if (count == 0)
{
return read;
}
// count has to be positive number
if (0 > count)
{
throw new ArgumentOutOfRangeException("count",
SR.Get(SRID.ReadCountNegative));
}
// offset has to be a positive number
if (0 > offset)
{
throw new ArgumentOutOfRangeException("offset",
SR.Get(SRID.BufferOffsetNegative));
}
// make sure that we have a buffer that matches number of bytes we need to read
// since all values are > 0, there is no chance of overflow
if (!((buffer.Length > 0) && ((buffer.Length - offset) >= count)))
{
throw new ArgumentException(SR.Get(SRID.BufferTooSmall), "buffer");
}
// offset == 0 is the normal case
if (0 == offset)
{
_securitySuppressedIStream.Value.Read(buffer, count, out read);
}
// offset involved. Must be positive
else if (0 < offset)
{
// Read into local array and then copy it into the given buffer at
// the specified offset.
byte[] localBuffer = new byte[count];
_securitySuppressedIStream.Value.Read(localBuffer, count, out read);
if (read > 0)
{
Array.Copy(localBuffer, 0, buffer, offset, read);
}
}
// Negative offsets are not allowed and coverd above.
return read;
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the
/// current position within this stream by the number of bytes written.
///
/// Not Supported in this implementation.
/// </summary>
/// <param name="buffer">Data buffer</param>
/// <param name="offset">Buffer write start position</param>
/// <param name="count">Number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException(SR.Get(SRID.WriteNotSupported));
}
/// <summary>
/// Closes the current stream and releases any resources (such as
/// sockets and file handles) associated with the current stream.
/// </summary>
public override void Close()
{
_disposed = true;
}
#endregion Public Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <summary>
/// Check whether this Stream object is still valid. If not, thrown an
/// ObjectDisposedException.
/// </summary>
internal void CheckDisposedStatus()
{
if (StreamDisposed)
throw new ObjectDisposedException(null, SR.Get(SRID.StreamObjectDisposed));
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Check whether this Stream object is still valid.
/// </summary>
private bool StreamDisposed
{
get
{
return _disposed;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// This class does not control the life cycle of _securitySupressedIStream
// thus it should not dispose it when this class gets disposed
// the client code of this class should be the one that dispose _securitySupressedIStream
/// <SecurityNote>
/// Critical : Field for critical type SecuritySuppressedIStream
/// </SecurityNote>
[SecurityCritical]
SecurityCriticalDataForSet<SecuritySuppressedIStream> _securitySuppressedIStream;
FileAccess _access;
long _length = 0;
bool _isLengthInitialized = false;
bool _disposed = false;
#endregion Private Fields
//------------------------------------------------------
//
// Private Unmanaged Interfaces
//
//------------------------------------------------------
#region Private Unmanaged Interface imports
// ****CAUTION****: Be careful using this interface, because it suppresses
// the check for unmanaged code security permission. It is recommended
// that all instances of this interface also have "SecuritySuppressed" in
// its name to make it clear that it is a dangerous interface. Also, it
// is expected that each use of this interface be reviewed for security
// soundness.
[Guid("0000000c-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
[System.Security.SuppressUnmanagedCodeSecurity]
[SecurityCritical(SecurityCriticalScope.Everything)]
public interface SecuritySuppressedIStream
{
// ISequentialStream portion
void Read([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] Byte[] pv, int cb, out int pcbRead);
void Write([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] Byte[] pv, int cb, out int pcbWritten);
// IStream portion
void Seek(long dlibMove, int dwOrigin, out long plibNewPosition);
void SetSize(long libNewSize);
void CopyTo(SecuritySuppressedIStream pstm, long cb, out long pcbRead, out long pcbWritten);
void Commit(int grfCommitFlags);
void Revert();
void LockRegion(long libOffset, long cb, int dwLockType);
void UnlockRegion(long libOffset, long cb, int dwLockType);
void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, int grfStatFlag);
void Clone(out SecuritySuppressedIStream ppstm);
}
#endregion Private Unmanaged Interface imports
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
public abstract class ScopeStatement : Statement {
private bool _importStar; // from module import *
private bool _unqualifiedExec; // exec "code"
private bool _nestedFreeVariables; // nested function with free variable
private bool _locals; // The scope needs locals dictionary
// due to "exec" or call to dir, locals, eval, vars...
private bool _hasLateboundVarSets; // calls code which can assign to variables
private bool _containsExceptionHandling; // true if this block contains a try/with statement
private bool _forceCompile; // true if this scope should always be compiled
private FunctionCode _funcCode; // the function code object created for this scope
private Dictionary<string, PythonVariable> _variables; // mapping of string to variables
private ClosureInfo[] _closureVariables; // closed over variables, bool indicates if we accessed it in this scope.
private List<PythonVariable> _freeVars; // list of variables accessed from outer scopes
private List<string> _globalVars; // global variables accessed from this scope
private List<string> _cellVars; // variables accessed from nested scopes
private Dictionary<string, PythonReference> _references; // names of all variables referenced, null after binding completes
internal Dictionary<PythonVariable, MSAst.Expression> _variableMapping = new Dictionary<PythonVariable, MSAst.Expression>();
private MSAst.ParameterExpression _localParentTuple; // parent's tuple local saved locally
private readonly DelayedFunctionCode _funcCodeExpr = new DelayedFunctionCode(); // expression that refers to the function code for this scope
internal static MSAst.ParameterExpression LocalCodeContextVariable = Ast.Parameter(typeof(CodeContext), "$localContext");
private static MSAst.ParameterExpression _catchException = Ast.Parameter(typeof(Exception), "$updException");
internal const string NameForExec = "module: <exec>";
internal bool ContainsImportStar {
get { return _importStar; }
set { _importStar = value; }
}
internal bool ContainsExceptionHandling {
get {
return _containsExceptionHandling;
}
set {
_containsExceptionHandling = value;
}
}
internal bool ContainsUnqualifiedExec {
get { return _unqualifiedExec; }
set { _unqualifiedExec = value; }
}
internal virtual bool IsGeneratorMethod {
get {
return false;
}
}
/// <summary>
/// The variable used to hold out parents closure tuple in our local scope.
/// </summary>
internal MSAst.ParameterExpression LocalParentTuple {
get {
return _localParentTuple;
}
}
/// <summary>
/// Gets the expression associated with the local CodeContext. If the function
/// doesn't have a local CodeContext then this is the global context.
/// </summary>
internal virtual MSAst.Expression LocalContext {
get {
return LocalCodeContextVariable;
}
}
/// <summary>
/// True if this scope accesses a variable from an outer scope.
/// </summary>
internal bool IsClosure {
get { return FreeVariables != null && FreeVariables.Count > 0; }
}
/// <summary>
/// True if an inner scope is accessing a variable defined in this scope.
/// </summary>
internal bool ContainsNestedFreeVariables {
get { return _nestedFreeVariables; }
set { _nestedFreeVariables = value; }
}
/// <summary>
/// True if we are forcing the creation of a dictionary for storing locals.
///
/// This occurs for calls to locals(), dir(), vars(), unqualified exec, and
/// from ... import *.
/// </summary>
internal bool NeedsLocalsDictionary {
get { return _locals; }
set { _locals = value; }
}
public virtual string Name {
get {
return "<unknown>";
}
}
internal virtual string Filename {
get {
return GlobalParent.SourceUnit.Path ?? "<string>";
}
}
/// <summary>
/// True if variables can be set in a late bound fashion that we don't
/// know about at code gen time - for example via from foo import *.
///
/// This is tracked independently of the ContainsUnqualifiedExec/NeedsLocalsDictionary
/// </summary>
internal virtual bool HasLateBoundVariableSets {
get {
return _hasLateboundVarSets;
}
set {
_hasLateboundVarSets = value;
}
}
internal Dictionary<string, PythonVariable> Variables {
get { return _variables; }
}
internal virtual bool IsGlobal {
get { return false; }
}
internal bool NeedsLocalContext {
get {
return NeedsLocalsDictionary || ContainsNestedFreeVariables;
}
}
internal virtual string[] ParameterNames {
get {
return ArrayUtils.EmptyStrings;
}
}
internal virtual int ArgCount {
get {
return 0;
}
}
internal virtual FunctionAttributes Flags {
get {
return FunctionAttributes.None;
}
}
internal abstract Microsoft.Scripting.Ast.LightLambdaExpression GetLambda();
/// <summary>
/// Gets or creates the FunctionCode object for this FunctionDefinition.
/// </summary>
internal FunctionCode GetOrMakeFunctionCode() {
if (_funcCode == null) {
Interlocked.CompareExchange(ref _funcCode, new FunctionCode(GlobalParent.PyContext, OriginalDelegate, this, ScopeDocumentation, null, true), null);
}
return _funcCode;
}
internal virtual string ScopeDocumentation {
get {
return null;
}
}
internal virtual Delegate OriginalDelegate {
get {
return null;
}
}
internal virtual IList<string> GetVarNames() {
List<string> res = new List<string>();
AppendVariables(res);
return res;
}
internal void AddFreeVariable(PythonVariable variable, bool accessedInScope) {
if (_freeVars == null) {
_freeVars = new List<PythonVariable>();
}
if(!_freeVars.Contains(variable)) {
_freeVars.Add(variable);
}
}
internal bool ShouldInterpret {
get {
if (_forceCompile) {
return false;
} else if (GlobalParent.CompilationMode == CompilationMode.Lookup) {
return true;
}
CompilerContext context = GlobalParent.CompilerContext;
return ((PythonContext)context.SourceUnit.LanguageContext).ShouldInterpret((PythonCompilerOptions)context.Options, context.SourceUnit);
}
set {
_forceCompile = !value;
}
}
internal string AddReferencedGlobal(string name) {
if (_globalVars == null) {
_globalVars = new List<string>();
}
if (!_globalVars.Contains(name)) {
_globalVars.Add(name);
}
return name;
}
internal void AddCellVariable(PythonVariable variable) {
if (_cellVars == null) {
_cellVars = new List<string>();
}
if (!_cellVars.Contains(variable.Name)) {
_cellVars.Add(variable.Name);
}
}
internal List<string> AppendVariables(List<string> res) {
if (Variables != null) {
foreach (var variable in Variables) {
if (variable.Value.Kind != VariableKind.Local) {
continue;
}
if (CellVariables == null || !CellVariables.Contains(variable.Key)) {
res.Add(variable.Key);
}
}
}
return res;
}
/// <summary>
/// Variables that are bound in an outer scope - but not a global scope
/// </summary>
internal IList<PythonVariable> FreeVariables {
get {
return _freeVars;
}
}
/// <summary>
/// Variables that are bound to the global scope
/// </summary>
internal IList<string> GlobalVariables {
get {
return _globalVars;
}
}
/// <summary>
/// Variables that are referred to from a nested scope and need to be
/// promoted to cells.
/// </summary>
internal IList<string> CellVariables {
get {
return _cellVars;
}
}
internal Type GetClosureTupleType() {
if (TupleCells > 0) {
Type[] args = new Type[TupleCells];
for (int i = 0; i < TupleCells; i++) {
args[i] = typeof(ClosureCell);
}
return MutableTuple.MakeTupleType(args);
}
return null;
}
internal virtual int TupleCells {
get {
if (_closureVariables == null) {
return 0;
}
return _closureVariables.Length;
}
}
internal abstract bool ExposesLocalVariable(PythonVariable variable);
internal virtual MSAst.Expression GetParentClosureTuple() {
// PythonAst will never call this.
throw new NotSupportedException();
}
private bool TryGetAnyVariable(string name, out PythonVariable variable) {
if (_variables != null) {
return _variables.TryGetValue(name, out variable);
} else {
variable = null;
return false;
}
}
internal bool TryGetVariable(string name, out PythonVariable variable) {
if (TryGetAnyVariable(name, out variable)) {
return true;
} else {
variable = null;
return false;
}
}
internal virtual bool TryBindOuter(ScopeStatement from, PythonReference reference, out PythonVariable variable) {
// Hide scope contents by default (only functions expose their locals)
variable = null;
return false;
}
internal abstract PythonVariable BindReference(PythonNameBinder binder, PythonReference reference);
internal virtual void Bind(PythonNameBinder binder) {
if (_references != null) {
foreach (var reference in _references.Values) {
PythonVariable variable;
reference.PythonVariable = variable = BindReference(binder, reference);
// Accessing outer scope variable which is being deleted?
if (variable != null) {
if (variable.Deleted && variable.Scope != this && !variable.Scope.IsGlobal) {
// report syntax error
binder.ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"can not delete variable '{0}' referenced in nested scope",
reference.Name
),
this);
}
}
}
}
}
internal virtual void FinishBind(PythonNameBinder binder) {
List<ClosureInfo> closureVariables = null;
if (FreeVariables != null && FreeVariables.Count > 0) {
_localParentTuple = Ast.Parameter(Parent.GetClosureTupleType(), "$tuple");
foreach (var variable in _freeVars) {
var parentClosure = Parent._closureVariables;
Debug.Assert(parentClosure != null);
for (int i = 0; i < parentClosure.Length; i++) {
if (parentClosure[i].Variable == variable) {
_variableMapping[variable] = new ClosureExpression(variable, Ast.Property(_localParentTuple, String.Format("Item{0:D3}", i)), null);
break;
}
}
Debug.Assert(_variableMapping.ContainsKey(variable));
if (closureVariables == null) {
closureVariables = new List<ClosureInfo>();
}
closureVariables.Add(new ClosureInfo(variable, !(this is ClassDefinition)));
}
}
if (Variables != null) {
foreach (PythonVariable variable in Variables.Values) {
if (!HasClosureVariable(closureVariables, variable) &&
!variable.IsGlobal && (variable.AccessedInNestedScope || ExposesLocalVariable(variable))) {
if (closureVariables == null) {
closureVariables = new List<ClosureInfo>();
}
closureVariables.Add(new ClosureInfo(variable, true));
}
if (variable.Kind == VariableKind.Local) {
Debug.Assert(variable.Scope == this);
if (variable.AccessedInNestedScope || ExposesLocalVariable(variable)) {
_variableMapping[variable] = new ClosureExpression(variable, Ast.Parameter(typeof(ClosureCell), variable.Name), null);
} else {
_variableMapping[variable] = Ast.Parameter(typeof(object), variable.Name);
}
}
}
}
if (closureVariables != null) {
_closureVariables = closureVariables.ToArray();
}
// no longer needed
_references = null;
}
private static bool HasClosureVariable(List<ClosureInfo> closureVariables, PythonVariable variable) {
if (closureVariables == null) {
return false;
}
for (int i = 0; i < closureVariables.Count; i++) {
if (closureVariables[i].Variable == variable) {
return true;
}
}
return false;
}
private void EnsureVariables() {
if (_variables == null) {
_variables = new Dictionary<string, PythonVariable>(StringComparer.Ordinal);
}
}
internal void AddGlobalVariable(PythonVariable variable) {
EnsureVariables();
_variables[variable.Name] = variable;
}
internal PythonReference Reference(string name) {
if (_references == null) {
_references = new Dictionary<string, PythonReference>(StringComparer.Ordinal);
}
PythonReference reference;
if (!_references.TryGetValue(name, out reference)) {
_references[name] = reference = new PythonReference(name);
}
return reference;
}
internal bool IsReferenced(string name) {
PythonReference reference;
return _references != null && _references.TryGetValue(name, out reference);
}
internal PythonVariable/*!*/ CreateVariable(string name, VariableKind kind) {
EnsureVariables();
Debug.Assert(!_variables.ContainsKey(name));
PythonVariable variable;
_variables[name] = variable = new PythonVariable(name, kind, this);
return variable;
}
internal PythonVariable/*!*/ EnsureVariable(string name) {
PythonVariable variable;
if (!TryGetVariable(name, out variable)) {
return CreateVariable(name, VariableKind.Local);
}
return variable;
}
internal PythonVariable DefineParameter(string name) {
return CreateVariable(name, VariableKind.Parameter);
}
internal PythonContext PyContext {
get {
return (PythonContext)GlobalParent.CompilerContext.SourceUnit.LanguageContext;
}
}
#region Debug Info Tracking
private MSAst.SymbolDocumentInfo Document {
get {
return GlobalParent.Document;
}
}
internal MSAst.Expression/*!*/ AddDebugInfo(MSAst.Expression/*!*/ expression, SourceLocation start, SourceLocation end) {
if (PyContext.PythonOptions.GCStress != null) {
expression = Ast.Block(
Ast.Call(
typeof(GC).GetMethod("Collect", new[] { typeof(int) }),
Ast.Constant(PyContext.PythonOptions.GCStress.Value)
),
expression
);
}
return AstUtils.AddDebugInfo(expression, Document, start, end);
}
internal MSAst.Expression/*!*/ AddDebugInfo(MSAst.Expression/*!*/ expression, SourceSpan location) {
return AddDebugInfo(expression, location.Start, location.End);
}
internal MSAst.Expression/*!*/ AddDebugInfoAndVoid(MSAst.Expression/*!*/ expression, SourceSpan location) {
if (expression.Type != typeof(void)) {
expression = AstUtils.Void(expression);
}
return AddDebugInfo(expression, location);
}
#endregion
#region Runtime Line Number Tracing
/// <summary>
/// Gets the expression for updating the dynamic stack trace at runtime when an
/// exception is thrown.
/// </summary>
internal MSAst.Expression GetUpdateTrackbackExpression(MSAst.ParameterExpression exception) {
if (!_containsExceptionHandling) {
Debug.Assert(Name != null);
Debug.Assert(exception.Type == typeof(Exception));
return UpdateStackTrace(exception);
}
return GetSaveLineNumberExpression(exception, true);
}
private MSAst.Expression UpdateStackTrace(MSAst.ParameterExpression exception) {
return Ast.Call(
AstMethods.UpdateStackTrace,
exception,
LocalContext,
_funcCodeExpr,
LineNumberExpression
);
}
/// <summary>
/// Gets the expression for the actual updating of the line number for stack traces to be available
/// </summary>
internal MSAst.Expression GetSaveLineNumberExpression(MSAst.ParameterExpression exception, bool preventAdditionalAdds) {
Debug.Assert(exception.Type == typeof(Exception));
return Ast.Block(
AstUtils.If(
Ast.Not(
LineNumberUpdated
),
UpdateStackTrace(exception)
),
Ast.Assign(
LineNumberUpdated,
AstUtils.Constant(preventAdditionalAdds)
),
AstUtils.Empty()
);
}
/// <summary>
/// Wraps the body of a statement which should result in a frame being available during
/// exception handling. This ensures the line number is updated as the stack is unwound.
/// </summary>
internal MSAst.Expression/*!*/ WrapScopeStatements(MSAst.Expression/*!*/ body, bool canThrow) {
if (canThrow) {
body = Ast.Block(
new[] { LineNumberExpression, LineNumberUpdated },
Ast.TryCatch(
body,
Ast.Catch(
_catchException,
Ast.Block(
GetUpdateTrackbackExpression(_catchException),
Ast.Rethrow(body.Type)
)
)
)
);
}
return body;
}
#endregion
/// <summary>
/// Provides a place holder for the expression which represents
/// a FunctionCode. For functions/classes this gets updated after
/// the AST has been generated because the FunctionCode needs to
/// know about the tree which gets generated. For modules we
/// immediately have the value because it always comes in as a parameter.
/// </summary>
class DelayedFunctionCode : MSAst.Expression {
private MSAst.Expression _funcCode;
public override bool CanReduce {
get {
return true;
}
}
public MSAst.Expression Code {
get {
return _funcCode;
}
set {
_funcCode = value;
}
}
public override Type Type {
get {
return typeof(FunctionCode);
}
}
protected override MSAst.Expression VisitChildren(MSAst.ExpressionVisitor visitor) {
if (_funcCode != null) {
MSAst.Expression funcCode = visitor.Visit(_funcCode);
if (funcCode != _funcCode) {
DelayedFunctionCode res = new DelayedFunctionCode();
res._funcCode = funcCode;
return res;
}
}
return this;
}
public override MSAst.Expression Reduce() {
Debug.Assert(_funcCode != null);
return _funcCode;
}
public override MSAst.ExpressionType NodeType {
get {
return MSAst.ExpressionType.Extension;
}
}
}
internal MSAst.Expression FuncCodeExpr {
get {
return _funcCodeExpr.Code;
}
set {
_funcCodeExpr.Code = value;
}
}
internal MSAst.MethodCallExpression CreateLocalContext(MSAst.Expression parentContext) {
var closureVariables = _closureVariables;
if (_closureVariables == null) {
closureVariables = new ClosureInfo[0];
}
return Ast.Call(
AstMethods.CreateLocalContext,
parentContext,
MutableTuple.Create(ArrayUtils.ConvertAll(closureVariables, x => GetClosureCell(x))),
Ast.Constant(ArrayUtils.ConvertAll(closureVariables, x => x.AccessedInScope ? x.Variable.Name : null))
);
}
private MSAst.Expression GetClosureCell(ClosureInfo variable) {
return ((ClosureExpression)GetVariableExpression(variable.Variable)).ClosureCell;
}
internal virtual MSAst.Expression GetVariableExpression(PythonVariable variable) {
if (variable.IsGlobal) {
return GlobalParent.ModuleVariables[variable];
}
Debug.Assert(_variableMapping.ContainsKey(variable));
return _variableMapping[variable];
}
internal void CreateVariables(ReadOnlyCollectionBuilder<MSAst.ParameterExpression> locals, List<MSAst.Expression> init) {
if (Variables != null) {
foreach (PythonVariable variable in Variables.Values) {
if(variable.Kind != VariableKind.Global) {
ClosureExpression closure = GetVariableExpression(variable) as ClosureExpression;
if (closure != null) {
init.Add(closure.Create());
locals.Add((MSAst.ParameterExpression)closure.ClosureCell);
} else if (variable.Kind == VariableKind.Local) {
locals.Add((MSAst.ParameterExpression)GetVariableExpression(variable));
if (variable.ReadBeforeInitialized) {
init.Add(
AssignValue(
GetVariableExpression(variable),
MSAst.Expression.Field(null, typeof(Uninitialized).GetField("Instance"))
)
);
}
}
}
}
}
if (IsClosure) {
Type tupleType = Parent.GetClosureTupleType();
Debug.Assert(tupleType != null);
init.Add(
MSAst.Expression.Assign(
LocalParentTuple,
MSAst.Expression.Convert(
GetParentClosureTuple(),
tupleType
)
)
);
locals.Add(LocalParentTuple);
}
}
internal MSAst.Expression AddDecorators(MSAst.Expression ret, IList<Expression> decorators) {
// add decorators
if (decorators != null) {
for (int i = decorators.Count - 1; i >= 0; i--) {
Expression decorator = decorators[i];
ret = Parent.Invoke(
new CallSignature(1),
Parent.LocalContext,
decorator,
ret
);
}
}
return ret;
}
internal MSAst.Expression/*!*/ Invoke(CallSignature signature, params MSAst.Expression/*!*/[]/*!*/ args) {
PythonInvokeBinder invoke = PyContext.Invoke(signature);
switch (args.Length) {
case 1: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0]);
case 2: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0], args[1]);
case 3: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0], args[1], args[2]);
case 4: return GlobalParent.CompilationMode.Dynamic(invoke, typeof(object), args[0], args[1], args[2], args[3]);
default:
return GlobalParent.CompilationMode.Dynamic(
invoke,
typeof(object),
args
);
}
}
internal ScopeStatement CopyForRewrite() {
return (ScopeStatement)MemberwiseClone();
}
internal virtual void RewriteBody(MSAst.ExpressionVisitor visitor) {
_funcCode = null;
}
struct ClosureInfo {
public PythonVariable Variable;
public bool AccessedInScope;
public ClosureInfo(PythonVariable variable, bool accessedInScope) {
Variable = variable;
AccessedInScope = accessedInScope;
}
}
internal virtual bool PrintExpressions {
get {
return false;
}
}
#region Profiling Support
internal virtual string ProfilerName {
get {
return Name;
}
}
/// <summary>
/// Reducible node so that re-writing for profiling does not occur until
/// after the script code has been completed and is ready to be compiled.
///
/// Without this extra node profiling would force reduction of the node
/// and we wouldn't have setup our constant access correctly yet.
/// </summary>
class DelayedProfiling : MSAst.Expression {
private readonly ScopeStatement _ast;
private readonly MSAst.Expression _body;
private readonly MSAst.ParameterExpression _tick;
public DelayedProfiling(ScopeStatement ast, MSAst.Expression body, MSAst.ParameterExpression tick) {
_ast = ast;
_body = body;
_tick = tick;
}
public override bool CanReduce {
get {
return true;
}
}
public override Type Type {
get {
return _body.Type;
}
}
protected override MSAst.Expression VisitChildren(MSAst.ExpressionVisitor visitor) {
return visitor.Visit(_body);
}
public override MSAst.Expression Reduce() {
string profilerName = _ast.ProfilerName;
bool unique = (profilerName == NameForExec);
return Ast.Block(
new[] { _tick },
_ast.GlobalParent._profiler.AddProfiling(_body, _tick, profilerName, unique)
);
}
public override MSAst.ExpressionType NodeType {
get {
return MSAst.ExpressionType.Extension;
}
}
}
internal MSAst.Expression AddProfiling(MSAst.Expression/*!*/ body) {
if (GlobalParent._profiler != null) {
MSAst.ParameterExpression tick = Ast.Variable(typeof(long), "$tick");
return new DelayedProfiling(this, body, tick);
}
return body;
}
#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.Xml;
using System.Globalization;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlWriterDelegator
#else
internal class XmlWriterDelegator
#endif
{
protected XmlWriter writer;
protected XmlDictionaryWriter dictionaryWriter;
internal int depth;
private int _prefixes;
public XmlWriterDelegator(XmlWriter writer)
{
XmlObjectSerializer.CheckNull(writer, "writer");
this.writer = writer;
this.dictionaryWriter = writer as XmlDictionaryWriter;
}
internal XmlWriter Writer
{
get { return writer; }
}
internal void Flush()
{
writer.Flush();
}
internal string LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
private void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
#if USE_REFEMIT
public void WriteEndElement()
#else
internal void WriteEndElement()
#endif
{
writer.WriteEndElement();
depth--;
}
internal void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
internal void WriteRaw(string data)
{
writer.WriteRaw(data);
}
internal void WriteXmlnsAttribute(XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
if (ns != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
}
else
WriteXmlnsAttribute(ns.Value);
}
internal void WriteXmlnsAttribute(string ns)
{
if (ns != null)
{
if (ns.Length == 0)
writer.WriteAttributeString("xmlns", String.Empty, null, ns);
else
{
if (dictionaryWriter != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
else
{
string prefix = writer.LookupPrefix(ns);
if (prefix == null)
{
prefix = String.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes);
_prefixes++;
writer.WriteAttributeString("xmlns", prefix, null, ns);
}
}
}
}
}
internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
dictionaryWriter.WriteXmlnsAttribute(prefix, ns);
}
else
{
writer.WriteAttributeString("xmlns", prefix, null, ns.Value);
}
}
private void WriteStartAttribute(string prefix, string localName, string ns)
{
writer.WriteStartAttribute(prefix, localName, ns);
}
private void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri);
else
writer.WriteStartAttribute(prefix,
(localName == null ? null : localName.Value),
(namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteAttributeString(string prefix, string localName, string ns, string value)
{
WriteStartAttribute(prefix, localName, ns);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
private void WriteAttributeStringValue(string value)
{
writer.WriteValue(value);
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
private void WriteAttributeStringValue(XmlDictionaryString value)
{
if (dictionaryWriter == null)
writer.WriteString(value.Value);
else
dictionaryWriter.WriteString(value);
}
internal void WriteAttributeInt(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, int value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeIntValue(value);
WriteEndAttribute();
}
private void WriteAttributeIntValue(int value)
{
writer.WriteValue(value);
}
internal void WriteAttributeBool(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, bool value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeBoolValue(value);
WriteEndAttribute();
}
private void WriteAttributeBoolValue(bool value)
{
writer.WriteValue(value);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
private void WriteAttributeQualifiedNameValue(string name, string ns)
{
writer.WriteQualifiedName(name, ns);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
private void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(name.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(name, ns);
}
internal void WriteStartElement(string localName, string ns)
{
WriteStartElement(null, localName, ns);
}
internal virtual void WriteStartElement(string prefix, string localName, string ns)
{
writer.WriteStartElement(prefix, localName, ns);
depth++;
_prefixes = 1;
}
#if USE_REFEMIT
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
#else
internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
#endif
{
WriteStartElement(null, localName, namespaceUri);
}
internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri);
else
writer.WriteStartElement(prefix, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
depth++;
_prefixes = 1;
}
internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(null, localName, namespaceUri);
else
writer.WriteStartElement(null, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteEndElementPrimitive()
{
writer.WriteEndElement();
}
internal WriteState WriteState
{
get { return writer.WriteState; }
}
internal string XmlLang
{
get { return writer.XmlLang; }
}
internal XmlSpace XmlSpace
{
get { return writer.XmlSpace; }
}
#if USE_REFEMIT
public void WriteNamespaceDecl(XmlDictionaryString ns)
#else
internal void WriteNamespaceDecl(XmlDictionaryString ns)
#endif
{
WriteXmlnsAttribute(ns);
}
private Exception CreateInvalidPrimitiveTypeException(Type type)
{
return new InvalidDataContractException(string.Format(SRSerialization.InvalidPrimitiveType, DataContract.GetClrTypeFullName(type)));
}
internal void WriteAnyType(object value)
{
WriteAnyType(value, value.GetType());
}
internal void WriteAnyType(object value, Type valueType)
{
bool handled = true;
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
WriteBoolean((bool)value);
break;
case TypeCode.Char:
WriteChar((char)value);
break;
case TypeCode.Byte:
WriteUnsignedByte((byte)value);
break;
case TypeCode.Int16:
WriteShort((short)value);
break;
case TypeCode.Int32:
WriteInt((int)value);
break;
case TypeCode.Int64:
WriteLong((long)value);
break;
case TypeCode.Single:
WriteFloat((float)value);
break;
case TypeCode.Double:
WriteDouble((double)value);
break;
case TypeCode.Decimal:
WriteDecimal((decimal)value);
break;
case TypeCode.DateTime:
WriteDateTime((DateTime)value);
break;
case TypeCode.String:
WriteString((string)value);
break;
case TypeCode.SByte:
WriteSignedByte((sbyte)value);
break;
case TypeCode.UInt16:
WriteUnsignedShort((ushort)value);
break;
case TypeCode.UInt32:
WriteUnsignedInt((uint)value);
break;
case TypeCode.UInt64:
WriteUnsignedLong((ulong)value);
break;
case TypeCode.Empty:
case TypeCode.Object:
default:
if (valueType == Globals.TypeOfByteArray)
WriteBase64((byte[])value);
else if (valueType == Globals.TypeOfObject)
{
//Write Nothing
}
else if (valueType == Globals.TypeOfTimeSpan)
WriteTimeSpan((TimeSpan)value);
else if (valueType == Globals.TypeOfGuid)
WriteGuid((Guid)value);
else if (valueType == Globals.TypeOfUri)
WriteUri((Uri)value);
else if (valueType == Globals.TypeOfXmlQualifiedName)
WriteQName((XmlQualifiedName)value);
else
handled = false;
break;
}
if (!handled)
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
}
internal void WriteString(string value)
{
writer.WriteValue(value);
}
internal virtual void WriteBoolean(bool value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteBoolean(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDateTime(DateTime value)
{
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
#if USE_REFEMIT
public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDateTime(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDecimal(decimal value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDecimal(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDouble(double value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDouble(value);
WriteEndElementPrimitive();
}
internal virtual void WriteInt(int value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteLong(long value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteFloat(float value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteFloat(value);
WriteEndElementPrimitive();
}
internal virtual void WriteBase64(byte[] bytes)
{
if (bytes == null)
return;
writer.WriteBase64(bytes, 0, bytes.Length);
}
internal virtual void WriteShort(short value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedByte(byte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteSignedByte(sbyte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteSignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedInt(uint value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedLong(ulong value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedShort(ushort value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteChar(char value)
{
writer.WriteValue((int)value);
}
#if USE_REFEMIT
public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteChar(value);
WriteEndElementPrimitive();
}
internal void WriteTimeSpan(TimeSpan value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
#if USE_REFEMIT
public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteTimeSpan(value);
WriteEndElementPrimitive();
}
internal void WriteGuid(Guid value)
{
writer.WriteRaw(value.ToString());
}
#if USE_REFEMIT
public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteGuid(value);
WriteEndElementPrimitive();
}
internal void WriteUri(Uri value)
{
writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped));
}
internal virtual void WriteQName(XmlQualifiedName value)
{
if (value != XmlQualifiedName.Empty)
{
WriteXmlnsAttribute(value.Namespace);
WriteQualifiedName(value.Name, value.Namespace);
}
}
internal void WriteQualifiedName(string localName, string ns)
{
writer.WriteQualifiedName(localName, ns);
}
internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(localName.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(localName, ns);
}
#if USE_REFEMIT
public void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteBoolean(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDateTime(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDecimal(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteInt(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteLong(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteFloat(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDouble(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
using System.Threading;
namespace NLog.UnitTests.Contexts
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
public class MappedDiagnosticsLogicalContextTests
{
public MappedDiagnosticsLogicalContextTests()
{
MappedDiagnosticsLogicalContext.Clear();
}
[Fact]
public void given_item_exists_when_getting_item_should_return_item_for_objecttype_2()
{
string key = "testKey1";
object value = 5;
MappedDiagnosticsLogicalContext.Set(key, value);
string expected = "5";
string actual = MappedDiagnosticsLogicalContext.Get(key);
Assert.Equal(expected, actual);
}
[Fact]
public void given_item_exists_when_getting_item_should_return_item_for_objecttype()
{
string key = "testKey2";
object value = DateTime.Now;
MappedDiagnosticsLogicalContext.Set(key, value);
object actual = MappedDiagnosticsLogicalContext.GetObject(key);
Assert.Equal(value, actual);
}
[Fact]
public void given_no_item_exists_when_getting_item_should_return_null()
{
Assert.Null(MappedDiagnosticsLogicalContext.GetObject("itemThatShouldNotExist"));
}
[Fact]
public void given_no_item_exists_when_getting_item_should_return_empty_string()
{
Assert.Empty(MappedDiagnosticsLogicalContext.Get("itemThatShouldNotExist"));
}
[Fact]
public void given_item_exists_when_getting_item_should_return_item()
{
const string key = "Key";
const string item = "Item";
MappedDiagnosticsLogicalContext.Set(key, item);
Assert.Equal(item, MappedDiagnosticsLogicalContext.Get(key));
}
[Fact]
public void given_item_does_not_exist_when_setting_item_should_contain_item()
{
const string key = "Key";
const string item = "Item";
MappedDiagnosticsLogicalContext.Set(key, item);
Assert.True(MappedDiagnosticsLogicalContext.Contains(key));
}
[Fact]
public void given_item_exists_when_setting_item_should_not_throw()
{
const string key = "Key";
const string item = "Item";
MappedDiagnosticsLogicalContext.Set(key, item);
var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Set(key, item));
Assert.Null(exRecorded);
}
[Fact]
public void given_item_exists_when_setting_item_should_update_item()
{
const string key = "Key";
const string item = "Item";
const string newItem = "NewItem";
MappedDiagnosticsLogicalContext.Set(key, item);
MappedDiagnosticsLogicalContext.Set(key, newItem);
Assert.Equal(newItem, MappedDiagnosticsLogicalContext.Get(key));
}
[Fact]
public void given_no_item_exists_when_getting_items_should_return_empty_collection()
{
Assert.Equal(0,MappedDiagnosticsLogicalContext.GetNames().Count);
}
[Fact]
public void given_item_exists_when_getting_items_should_return_that_item()
{
const string key = "Key";
MappedDiagnosticsLogicalContext.Set(key, "Item");
Assert.Equal(1, MappedDiagnosticsLogicalContext.GetNames().Count);
Assert.True(MappedDiagnosticsLogicalContext.GetNames().Contains("Key"));
}
[Fact]
public void given_item_exists_after_removing_item_when_getting_items_should_not_contain_item()
{
const string keyThatRemains1 = "Key1";
const string keyThatRemains2 = "Key2";
const string keyThatIsRemoved = "KeyR";
MappedDiagnosticsLogicalContext.Set(keyThatRemains1, "7");
MappedDiagnosticsLogicalContext.Set(keyThatIsRemoved, 7);
MappedDiagnosticsLogicalContext.Set(keyThatRemains2, 8);
MappedDiagnosticsLogicalContext.Remove(keyThatIsRemoved);
Assert.Equal(2, MappedDiagnosticsLogicalContext.GetNames().Count);
Assert.False(MappedDiagnosticsLogicalContext.GetNames().Contains(keyThatIsRemoved));
}
[Fact]
public void given_item_does_not_exist_when_checking_if_context_contains_should_return_false()
{
Assert.False(MappedDiagnosticsLogicalContext.Contains("keyForItemThatDoesNotExist"));
}
[Fact]
public void given_item_exists_when_checking_if_context_contains_should_return_true()
{
const string key = "Key";
MappedDiagnosticsLogicalContext.Set(key, "Item");
Assert.True(MappedDiagnosticsLogicalContext.Contains(key));
}
[Fact]
public void given_item_exists_when_removing_item_should_not_contain_item()
{
const string keyForItemThatShouldExist = "Key";
const string itemThatShouldExist = "Item";
MappedDiagnosticsLogicalContext.Set(keyForItemThatShouldExist, itemThatShouldExist);
MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist);
Assert.False(MappedDiagnosticsLogicalContext.Contains(keyForItemThatShouldExist));
}
[Fact]
public void given_item_does_not_exist_when_removing_item_should_not_throw()
{
const string keyForItemThatShouldExist = "Key";
var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Remove(keyForItemThatShouldExist));
Assert.Null(exRecorded);
}
[Fact]
public void given_item_does_not_exist_when_clearing_should_not_throw()
{
var exRecorded = Record.Exception(() => MappedDiagnosticsLogicalContext.Clear());
Assert.Null(exRecorded);
}
[Fact]
public void given_item_exists_when_clearing_should_not_contain_item()
{
const string key = "Key";
MappedDiagnosticsLogicalContext.Set(key, "Item");
MappedDiagnosticsLogicalContext.Clear();
Assert.False(MappedDiagnosticsLogicalContext.Contains(key));
}
[Fact]
public void given_multiple_threads_running_asynchronously_when_setting_and_getting_values_should_return_thread_specific_values()
{
const string key = "Key";
const string valueForLogicalThread1 = "ValueForTask1";
const string valueForLogicalThread2 = "ValueForTask2";
const string valueForLogicalThread3 = "ValueForTask3";
MappedDiagnosticsLogicalContext.Clear(true);
var task1 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread1);
return MappedDiagnosticsLogicalContext.Get(key);
});
var task2 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread2);
return MappedDiagnosticsLogicalContext.Get(key);
});
var task3 = Task.Factory.StartNew(() => {
MappedDiagnosticsLogicalContext.Set(key, valueForLogicalThread3);
return MappedDiagnosticsLogicalContext.Get(key);
});
Task.WaitAll();
Assert.Equal(task1.Result, valueForLogicalThread1);
Assert.Equal(task2.Result, valueForLogicalThread2);
Assert.Equal(task3.Result, valueForLogicalThread3);
}
[Fact]
public void parent_thread_assigns_different_values_to_childs()
{
const string parentKey = "ParentKey";
const string parentValueForLogicalThread1 = "Parent1";
const string parentValueForLogicalThread2 = "Parent2";
const string childKey = "ChildKey";
const string valueForChildThread1 = "Child1";
const string valueForChildThread2 = "Child2";
MappedDiagnosticsLogicalContext.Clear(true);
var exitAllTasks = new ManualResetEvent(false);
MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread1);
var task1 = Task.Factory.StartNew(() =>
{
MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread1);
exitAllTasks.WaitOne();
return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey);
});
MappedDiagnosticsLogicalContext.Set(parentKey, parentValueForLogicalThread2);
var task2 = Task.Factory.StartNew(() =>
{
MappedDiagnosticsLogicalContext.Set(childKey, valueForChildThread2);
exitAllTasks.WaitOne();
return MappedDiagnosticsLogicalContext.Get(parentKey) + "," + MappedDiagnosticsLogicalContext.Get(childKey);
});
exitAllTasks.Set();
Task.WaitAll();
Assert.Equal(task1.Result, parentValueForLogicalThread1 + "," + valueForChildThread1);
Assert.Equal(task2.Result, parentValueForLogicalThread2 + "," + valueForChildThread2);
}
[Fact]
public void timer_cannot_inherit_mappedcontext()
{
object getObject = null;
string getValue = null;
var mre = new ManualResetEvent(false);
Timer thread = new Timer((s) =>
{
try
{
getObject = MappedDiagnosticsLogicalContext.GetObject("DoNotExist");
getValue = MappedDiagnosticsLogicalContext.Get("DoNotExistEither");
}
finally
{
mre.Set();
}
});
thread.Change(0, Timeout.Infinite);
mre.WaitOne();
Assert.Null(getObject);
Assert.Empty(getValue);
}
[Fact]
public void disposable_removes_item()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string itemRemovedKey = "itemRemovedKey";
MappedDiagnosticsLogicalContext.Clear();
MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsLogicalContext.SetScoped(itemRemovedKey, "itemRemoved"))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void dispose_is_idempotent()
{
const string itemKey = "itemKey";
MappedDiagnosticsLogicalContext.Clear();
IDisposable disposable = MappedDiagnosticsLogicalContext.SetScoped(itemKey, "item1");
disposable.Dispose();
Assert.False(MappedDiagnosticsLogicalContext.Contains(itemKey));
//This item shouldn't be removed since it is not the disposable one
MappedDiagnosticsLogicalContext.Set(itemKey, "item2");
disposable.Dispose();
Assert.True(MappedDiagnosticsLogicalContext.Contains(itemKey));
}
#if NET4_5
[Fact]
public void disposable_multiple_items()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string item1Key = "item1Key";
const string item2Key = "item2Key";
const string item3Key = "item3Key";
const string item4Key = "item4Key";
MappedDiagnosticsLogicalContext.Clear();
MappedDiagnosticsLogicalContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") }))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") }))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey, item1Key, item2Key, item3Key, item4Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void disposable_fast_clear_multiple_items()
{
const string item1Key = "item1Key";
const string item2Key = "item2Key";
const string item3Key = "item3Key";
const string item4Key = "item4Key";
MappedDiagnosticsLogicalContext.Clear();
using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2") }))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new string[] { });
using (MappedDiagnosticsLogicalContext.SetScoped(new[] { new KeyValuePair<string, object>(item1Key, "1"), new KeyValuePair<string, object>(item2Key, "2"), new KeyValuePair<string, object>(item3Key, "3"), new KeyValuePair<string, object>(item4Key, "4") }))
{
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new[] { item1Key, item2Key, item3Key, item4Key });
}
Assert.Equal(MappedDiagnosticsLogicalContext.GetNames(), new string[] { });
}
#endif
}
}
| |
namespace java.nio.channels
{
[global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.DatagramChannel_))]
public abstract partial class DatagramChannel : java.nio.channels.spi.AbstractSelectableChannel, ByteChannel, ScatteringByteChannel, GatheringByteChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static DatagramChannel()
{
InitJNI();
}
protected DatagramChannel(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _write14387;
public virtual long write(java.nio.ByteBuffer[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel._write14387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel.staticClass, global::java.nio.channels.DatagramChannel._write14387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _write14388;
public abstract int write(java.nio.ByteBuffer arg0);
internal static global::MonoJavaBridge.MethodId _write14389;
public abstract long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2);
internal static global::MonoJavaBridge.MethodId _send14390;
public abstract int send(java.nio.ByteBuffer arg0, java.net.SocketAddress arg1);
internal static global::MonoJavaBridge.MethodId _read14391;
public abstract long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2);
internal static global::MonoJavaBridge.MethodId _read14392;
public virtual long read(java.nio.ByteBuffer[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel._read14392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel.staticClass, global::java.nio.channels.DatagramChannel._read14392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _read14393;
public abstract int read(java.nio.ByteBuffer arg0);
internal static global::MonoJavaBridge.MethodId _open14394;
public static global::java.nio.channels.DatagramChannel open()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.channels.DatagramChannel.staticClass, global::java.nio.channels.DatagramChannel._open14394)) as java.nio.channels.DatagramChannel;
}
internal static global::MonoJavaBridge.MethodId _connect14395;
public abstract global::java.nio.channels.DatagramChannel connect(java.net.SocketAddress arg0);
internal static global::MonoJavaBridge.MethodId _socket14396;
public abstract global::java.net.DatagramSocket socket();
internal static global::MonoJavaBridge.MethodId _disconnect14397;
public abstract global::java.nio.channels.DatagramChannel disconnect();
internal static global::MonoJavaBridge.MethodId _isConnected14398;
public abstract bool isConnected();
internal static global::MonoJavaBridge.MethodId _receive14399;
public abstract global::java.net.SocketAddress receive(java.nio.ByteBuffer arg0);
internal static global::MonoJavaBridge.MethodId _validOps14400;
public sealed override int validOps()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel._validOps14400);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel.staticClass, global::java.nio.channels.DatagramChannel._validOps14400);
}
internal static global::MonoJavaBridge.MethodId _DatagramChannel14401;
protected DatagramChannel(java.nio.channels.spi.SelectorProvider arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.DatagramChannel.staticClass, global::java.nio.channels.DatagramChannel._DatagramChannel14401, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.DatagramChannel.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/DatagramChannel"));
global::java.nio.channels.DatagramChannel._write14387 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "write", "([Ljava/nio/ByteBuffer;)J");
global::java.nio.channels.DatagramChannel._write14388 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "write", "(Ljava/nio/ByteBuffer;)I");
global::java.nio.channels.DatagramChannel._write14389 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "write", "([Ljava/nio/ByteBuffer;II)J");
global::java.nio.channels.DatagramChannel._send14390 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "send", "(Ljava/nio/ByteBuffer;Ljava/net/SocketAddress;)I");
global::java.nio.channels.DatagramChannel._read14391 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "read", "([Ljava/nio/ByteBuffer;II)J");
global::java.nio.channels.DatagramChannel._read14392 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "read", "([Ljava/nio/ByteBuffer;)J");
global::java.nio.channels.DatagramChannel._read14393 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "read", "(Ljava/nio/ByteBuffer;)I");
global::java.nio.channels.DatagramChannel._open14394 = @__env.GetStaticMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "open", "()Ljava/nio/channels/DatagramChannel;");
global::java.nio.channels.DatagramChannel._connect14395 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "connect", "(Ljava/net/SocketAddress;)Ljava/nio/channels/DatagramChannel;");
global::java.nio.channels.DatagramChannel._socket14396 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "socket", "()Ljava/net/DatagramSocket;");
global::java.nio.channels.DatagramChannel._disconnect14397 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "disconnect", "()Ljava/nio/channels/DatagramChannel;");
global::java.nio.channels.DatagramChannel._isConnected14398 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "isConnected", "()Z");
global::java.nio.channels.DatagramChannel._receive14399 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "receive", "(Ljava/nio/ByteBuffer;)Ljava/net/SocketAddress;");
global::java.nio.channels.DatagramChannel._validOps14400 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "validOps", "()I");
global::java.nio.channels.DatagramChannel._DatagramChannel14401 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel.staticClass, "<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.DatagramChannel))]
public sealed partial class DatagramChannel_ : java.nio.channels.DatagramChannel
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static DatagramChannel_()
{
InitJNI();
}
internal DatagramChannel_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _write14402;
public override int write(java.nio.ByteBuffer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._write14402, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._write14402, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _write14403;
public override long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._write14403, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._write14403, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _send14404;
public override int send(java.nio.ByteBuffer arg0, java.net.SocketAddress arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._send14404, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._send14404, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _read14405;
public override long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._read14405, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._read14405, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _read14406;
public override int read(java.nio.ByteBuffer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._read14406, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._read14406, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _connect14407;
public override global::java.nio.channels.DatagramChannel connect(java.net.SocketAddress arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._connect14407, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.channels.DatagramChannel;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._connect14407, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.channels.DatagramChannel;
}
internal static global::MonoJavaBridge.MethodId _socket14408;
public override global::java.net.DatagramSocket socket()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._socket14408)) as java.net.DatagramSocket;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._socket14408)) as java.net.DatagramSocket;
}
internal static global::MonoJavaBridge.MethodId _disconnect14409;
public override global::java.nio.channels.DatagramChannel disconnect()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._disconnect14409)) as java.nio.channels.DatagramChannel;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._disconnect14409)) as java.nio.channels.DatagramChannel;
}
internal static global::MonoJavaBridge.MethodId _isConnected14410;
public override bool isConnected()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._isConnected14410);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._isConnected14410);
}
internal static global::MonoJavaBridge.MethodId _receive14411;
public override global::java.net.SocketAddress receive(java.nio.ByteBuffer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._receive14411, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.SocketAddress;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._receive14411, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.net.SocketAddress;
}
internal static global::MonoJavaBridge.MethodId _implCloseSelectableChannel14412;
protected override void implCloseSelectableChannel()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._implCloseSelectableChannel14412);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._implCloseSelectableChannel14412);
}
internal static global::MonoJavaBridge.MethodId _implConfigureBlocking14413;
protected override void implConfigureBlocking(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_._implConfigureBlocking14413, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.nio.channels.DatagramChannel_.staticClass, global::java.nio.channels.DatagramChannel_._implConfigureBlocking14413, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.nio.channels.DatagramChannel_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/DatagramChannel"));
global::java.nio.channels.DatagramChannel_._write14402 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "write", "(Ljava/nio/ByteBuffer;)I");
global::java.nio.channels.DatagramChannel_._write14403 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "write", "([Ljava/nio/ByteBuffer;II)J");
global::java.nio.channels.DatagramChannel_._send14404 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "send", "(Ljava/nio/ByteBuffer;Ljava/net/SocketAddress;)I");
global::java.nio.channels.DatagramChannel_._read14405 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "read", "([Ljava/nio/ByteBuffer;II)J");
global::java.nio.channels.DatagramChannel_._read14406 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "read", "(Ljava/nio/ByteBuffer;)I");
global::java.nio.channels.DatagramChannel_._connect14407 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "connect", "(Ljava/net/SocketAddress;)Ljava/nio/channels/DatagramChannel;");
global::java.nio.channels.DatagramChannel_._socket14408 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "socket", "()Ljava/net/DatagramSocket;");
global::java.nio.channels.DatagramChannel_._disconnect14409 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "disconnect", "()Ljava/nio/channels/DatagramChannel;");
global::java.nio.channels.DatagramChannel_._isConnected14410 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "isConnected", "()Z");
global::java.nio.channels.DatagramChannel_._receive14411 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "receive", "(Ljava/nio/ByteBuffer;)Ljava/net/SocketAddress;");
global::java.nio.channels.DatagramChannel_._implCloseSelectableChannel14412 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "implCloseSelectableChannel", "()V");
global::java.nio.channels.DatagramChannel_._implConfigureBlocking14413 = @__env.GetMethodIDNoThrow(global::java.nio.channels.DatagramChannel_.staticClass, "implConfigureBlocking", "(Z)V");
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using Commons;
using static ATL.AudioData.FileStructureHelper;
using static ATL.AudioData.IO.MetaDataIO;
using static ATL.ChannelsArrangements;
namespace ATL.AudioData.IO
{
/// <summary>
/// Class for Free Lossless Audio Codec files manipulation (extension : .FLAC)
/// </summary>
class FLAC : IMetaDataIO, IAudioDataIO
{
private const byte META_STREAMINFO = 0;
private const byte META_PADDING = 1;
private const byte META_APPLICATION = 2;
private const byte META_SEEKTABLE = 3;
private const byte META_VORBIS_COMMENT = 4;
private const byte META_CUESHEET = 5;
private const byte META_PICTURE = 6;
private const string FLAC_ID = "fLaC";
private const string ZONE_VORBISTAG = "VORBISTAG";
private const string ZONE_PICTURE = "PICTURE";
private class FlacHeader
{
public string StreamMarker;
public byte[] MetaDataBlockHeader = new byte[4];
public byte[] Info = new byte[18];
// 16-bytes MD5 Sum only applies to audio data
public void Reset()
{
StreamMarker = "";
Array.Clear(MetaDataBlockHeader, 0, 4);
Array.Clear(Info, 0, 18);
}
public bool IsValid()
{
return StreamMarker.Equals(FLAC_ID);
}
public FlacHeader()
{
Reset();
}
}
private readonly string filePath;
private AudioDataManager.SizeInfo sizeInfo;
private VorbisTag vorbisTag;
private FlacHeader header;
IList<FileStructureHelper.Zone> zones; // That's one hint of why interactions with VorbisTag need to be redesigned...
// Internal metrics
private int paddingIndex;
private bool paddingLast;
private uint padding;
private long audioOffset;
private long firstBlockPosition;
// Physical info
private int sampleRate;
private byte bitsPerSample;
private long samples;
private ChannelsArrangement channelsArrangement;
/* Unused for now
public long AudioOffset //offset of audio data
{
get { return audioOffset; }
}
public byte BitsPerSample // Bits per sample
{
get { return bitsPerSample; }
}
public long Samples // Number of samples
{
get { return samples; }
}
public double Ratio // Compression ratio (%)
{
get { return getCompressionRatio(); }
}
*/
// ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES
// IAudioDataIO
public int SampleRate // Sample rate (hz)
{
get { return sampleRate; }
}
public bool IsVBR
{
get { return false; }
}
public bool Exists
{
get { return vorbisTag.Exists; }
}
public string FileName
{
get { return filePath; }
}
public double BitRate
{
get { return Math.Round(((double)(sizeInfo.FileSize - audioOffset)) * 8 / Duration); }
}
public double Duration
{
get { return getDuration(); }
}
public ChannelsArrangement ChannelsArrangement
{
get { return channelsArrangement; }
}
public int CodecFamily
{
get { return AudioDataIOFactory.CF_LOSSLESS; }
}
#region IMetaDataReader
public string Title
{
get
{
return ((IMetaDataIO)vorbisTag).Title;
}
}
public string Artist
{
get
{
return ((IMetaDataIO)vorbisTag).Artist;
}
}
public string Composer
{
get
{
return ((IMetaDataIO)vorbisTag).Composer;
}
}
public string Comment
{
get
{
return ((IMetaDataIO)vorbisTag).Comment;
}
}
public string Genre
{
get
{
return ((IMetaDataIO)vorbisTag).Genre;
}
}
public ushort Track
{
get { return ((IMetaDataIO)vorbisTag).Track; }
}
public ushort TrackTotal
{
get { return ((IMetaDataIO)vorbisTag).TrackTotal; }
}
public ushort Disc
{
get { return ((IMetaDataIO)vorbisTag).Disc; }
}
public ushort DiscTotal
{
get { return ((IMetaDataIO)vorbisTag).DiscTotal; }
}
public string Year
{
get
{
return ((IMetaDataIO)vorbisTag).Year;
}
}
public string Album
{
get
{
return ((IMetaDataIO)vorbisTag).Album;
}
}
public ushort Rating
{
get
{
return ((IMetaDataIO)vorbisTag).Rating;
}
}
public float Popularity
{
get
{
return ((IMetaDataIO)vorbisTag).Popularity;
}
}
public string Copyright
{
get
{
return ((IMetaDataIO)vorbisTag).Copyright;
}
}
public string OriginalArtist
{
get
{
return ((IMetaDataIO)vorbisTag).OriginalArtist;
}
}
public string OriginalAlbum
{
get
{
return ((IMetaDataIO)vorbisTag).OriginalAlbum;
}
}
public string GeneralDescription
{
get
{
return ((IMetaDataIO)vorbisTag).GeneralDescription;
}
}
public string Publisher
{
get
{
return ((IMetaDataIO)vorbisTag).Publisher;
}
}
public string AlbumArtist
{
get
{
return ((IMetaDataIO)vorbisTag).AlbumArtist;
}
}
public string Conductor
{
get
{
return ((IMetaDataIO)vorbisTag).Conductor;
}
}
public IList<PictureInfo> PictureTokens
{
get
{
return ((IMetaDataIO)vorbisTag).PictureTokens;
}
}
public int Size
{
get
{
return ((IMetaDataIO)vorbisTag).Size;
}
}
public IDictionary<string, string> AdditionalFields
{
get
{
return ((IMetaDataIO)vorbisTag).AdditionalFields;
}
}
public string ChaptersTableDescription
{
get
{
return ((IMetaDataIO)vorbisTag).ChaptersTableDescription;
}
}
public IList<ChapterInfo> Chapters
{
get
{
return ((IMetaDataIO)vorbisTag).Chapters;
}
}
public IList<PictureInfo> EmbeddedPictures
{
get
{
return ((IMetaDataIO)vorbisTag).EmbeddedPictures;
}
}
#endregion
public bool IsMetaSupported(int metaDataType)
{
return (metaDataType == MetaDataIOFactory.TAG_NATIVE || metaDataType == MetaDataIOFactory.TAG_ID3V2); // Native is for VorbisTag
}
// ---------- CONSTRUCTORS & INITIALIZERS
protected void resetData()
{
// Audio data
padding = 0;
paddingLast = false;
sampleRate = 0;
bitsPerSample = 0;
samples = 0;
paddingIndex = 0;
audioOffset = 0;
}
public FLAC(string path)
{
filePath = path;
header = new FlacHeader();
resetData();
}
// ---------- SUPPORT METHODS
// Check for right FLAC file data
private bool isValid()
{
return ((header.IsValid()) &&
(channelsArrangement.NbChannels > 0) &&
(sampleRate > 0) &&
(bitsPerSample > 0) &&
(samples > 0));
}
private void readHeader(BinaryReader source)
{
source.BaseStream.Seek(sizeInfo.ID3v2Size, SeekOrigin.Begin);
// Read header data
header.Reset();
header.StreamMarker = Utils.Latin1Encoding.GetString(source.ReadBytes(4));
header.MetaDataBlockHeader = source.ReadBytes(4);
header.Info = source.ReadBytes(18);
source.BaseStream.Seek(16, SeekOrigin.Current); // MD5 sum for audio data
}
private double getDuration()
{
if ((isValid()) && (sampleRate > 0))
{
return (double)samples * 1000.0 / sampleRate;
}
else
{
return 0;
}
}
/* Unused for now
// Get compression ratio
private double getCompressionRatio()
{
if (isValid())
{
return (double)sizeInfo.FileSize / (samples * channels * bitsPerSample / 8.0) * 100;
}
else
{
return 0;
}
}
*/
public bool Read(BinaryReader source, AudioDataManager.SizeInfo sizeInfo, ReadTagParams readTagParams)
{
this.sizeInfo = sizeInfo;
return Read(source, readTagParams);
}
public bool Read(BinaryReader source, ReadTagParams readTagParams)
{
bool result = false;
if (readTagParams.ReadTag && null == vorbisTag) vorbisTag = new VorbisTag(false, false, false);
byte[] aMetaDataBlockHeader;
long position;
uint blockLength;
int blockType;
int blockIndex;
bool isLast;
bool bPaddingFound = false;
readHeader(source);
// Process data if loaded and header valid
if (header.IsValid())
{
int channels = (header.Info[12] >> 1) & 0x7;
switch (channels)
{
case 0b0000: channelsArrangement = MONO; break;
case 0b0001: channelsArrangement = STEREO; break;
case 0b0010: channelsArrangement = ISO_3_0_0; break;
case 0b0011: channelsArrangement = QUAD; break;
case 0b0100: channelsArrangement = ISO_3_2_0; break;
case 0b0101: channelsArrangement = ISO_3_2_1; break;
case 0b0110: channelsArrangement = LRCLFECrLssRss; break;
case 0b0111: channelsArrangement = LRCLFELrRrLssRss; break;
case 0b1000: channelsArrangement = JOINT_STEREO_LEFT_SIDE; break;
case 0b1001: channelsArrangement = JOINT_STEREO_RIGHT_SIDE; break;
case 0b1010: channelsArrangement = JOINT_STEREO_MID_SIDE; break;
default: channelsArrangement = UNKNOWN; break;
}
sampleRate = (header.Info[10] << 12 | header.Info[11] << 4 | header.Info[12] >> 4);
bitsPerSample = (byte)(((header.Info[12] & 1) << 4) | (header.Info[13] >> 4) + 1);
samples = (header.Info[14] << 24 | header.Info[15] << 16 | header.Info[16] << 8 | header.Info[17]);
if (0 == (header.MetaDataBlockHeader[1] & 0x80)) // metadata block exists
{
blockIndex = 0;
vorbisTag.Clear();
if (readTagParams.PrepareForWriting)
{
if (null == zones) zones = new List<Zone>(); else zones.Clear();
firstBlockPosition = source.BaseStream.Position;
}
do // read more metadata blocks if available
{
aMetaDataBlockHeader = source.ReadBytes(4);
isLast = ((aMetaDataBlockHeader[0] & 0x80) > 0); // last flag ( first bit == 1 )
blockIndex++;
blockLength = StreamUtils.DecodeBEUInt24(aMetaDataBlockHeader, 1);
blockType = (aMetaDataBlockHeader[0] & 0x7F); // decode metablock type
position = source.BaseStream.Position;
if (blockType == META_VORBIS_COMMENT) // Vorbis metadata
{
if (readTagParams.PrepareForWriting) zones.Add(new Zone(ZONE_VORBISTAG, position - 4, (int)blockLength + 4, new byte[0], (byte)(isLast ? 1 : 0)));
vorbisTag.Read(source, readTagParams);
}
else if ((blockType == META_PADDING) && (!bPaddingFound)) // Padding block
{
padding = blockLength; // if we find more skip & put them in metablock array
paddingLast = ((aMetaDataBlockHeader[0] & 0x80) != 0);
paddingIndex = blockIndex;
bPaddingFound = true;
source.BaseStream.Seek(padding, SeekOrigin.Current); // advance into file till next block or audio data start
}
else if (blockType == META_PICTURE)
{
if (readTagParams.PrepareForWriting) zones.Add(new Zone(ZONE_PICTURE, position - 4, (int)blockLength + 4, new byte[0], (byte)(isLast ? 1 : 0)));
vorbisTag.ReadPicture(source.BaseStream, readTagParams);
}
// TODO : support for CUESHEET block
if (blockType < 7)
{
source.BaseStream.Seek(position + blockLength, SeekOrigin.Begin);
}
else
{
// Abnormal header : incorrect size and/or misplaced last-metadata-block flag
break;
}
}
while (!isLast);
if (readTagParams.PrepareForWriting)
{
bool vorbisTagFound = false;
bool pictureFound = false;
foreach (Zone zone in zones)
{
if (zone.Name.Equals(ZONE_PICTURE)) pictureFound = true;
else if (zone.Name.Equals(ZONE_VORBISTAG)) vorbisTagFound = true;
}
if (!vorbisTagFound) zones.Add(new Zone(ZONE_VORBISTAG, firstBlockPosition, 0, new byte[0]));
if (!pictureFound) zones.Add(new Zone(ZONE_PICTURE, firstBlockPosition, 0, new byte[0]));
}
}
}
if (isValid())
{
audioOffset = source.BaseStream.Position; // we need that to rebuild the file if nedeed
result = true;
}
return result;
}
// NB1 : previously scattered picture blocks become contiguous after rewriting
// NB2 : This only works if writeVorbisTag is called _before_ writePictures, since tagData fusion is done by vorbisTag.Write
public bool Write(BinaryReader r, BinaryWriter w, TagData tag)
{
bool result = true;
int oldTagSize, writtenFields;
long newTagSize;
bool pictureBlockFound = false;
long cumulativeDelta = 0;
// Read all the fields in the existing tag (including unsupported fields)
ReadTagParams readTagParams = new ReadTagParams(true, true);
readTagParams.PrepareForWriting = true;
Read(r, readTagParams);
// Prepare picture data with freshly read vorbisTag
TagData dataToWrite = new TagData();
dataToWrite.Pictures = vorbisTag.EmbeddedPictures;
dataToWrite.IntegrateValues(tag); // Merge existing information + new tag information
// Rewrite vorbis tag zone
foreach (Zone zone in zones)
{
oldTagSize = zone.Size;
// Write new tag to a MemoryStream
using (MemoryStream s = new MemoryStream(zone.Size))
using (BinaryWriter msw = new BinaryWriter(s, Settings.DefaultTextEncoding))
{
if (zone.Name.Equals(ZONE_VORBISTAG)) writtenFields = writeVorbisTag(msw, tag, 1 == zone.Flag);
else if (zone.Name.Equals(ZONE_PICTURE))
{
// All pictures are written at the position of the 1st picture block
// TODO: optimize - when there are more than 1 pictures, a simple neutral update of the file extends the 1st zone to the size of all picture and shrinks all other zones
// => a LOT of unnecessary byte moving
if (!pictureBlockFound)
{
pictureBlockFound = true;
writtenFields = writePictures(msw, dataToWrite.Pictures, 1 == zone.Flag);
}
else
{
writtenFields = 0; // Other picture blocks are erased
}
}
else
{
writtenFields = 0;
}
if (0 == writtenFields) s.SetLength(0); // No core signature for metadata in FLAC structure
newTagSize = s.Length;
// -- Adjust tag slot to new size in file --
long tagBeginOffset = zone.Offset + cumulativeDelta;
long tagEndOffset = tagBeginOffset + zone.Size;
// TODO optimization : this is the physical file we're editing !
// => there are as many resizing operations as there are zones in the file ?!
if (newTagSize > zone.Size) // Need to build a larger file
{
StreamUtils.LengthenStream(w.BaseStream, tagEndOffset, (uint)(newTagSize - zone.Size));
}
else if (newTagSize < zone.Size) // Need to reduce file size
{
StreamUtils.ShortenStream(w.BaseStream, tagEndOffset, (uint)(zone.Size - newTagSize));
}
// Copy tag contents to the new slot
r.BaseStream.Seek(tagBeginOffset, SeekOrigin.Begin);
s.Seek(0, SeekOrigin.Begin);
if (newTagSize > zone.CoreSignature.Length)
{
StreamUtils.CopyStream(s, w.BaseStream);
}
else
{
if (zone.CoreSignature.Length > 0) msw.Write(zone.CoreSignature);
}
cumulativeDelta += newTagSize - oldTagSize;
}
} // Loop through zones
return result;
}
private int writeVorbisTag(BinaryWriter w, TagData tag, bool isLast)
{
int result;
long sizePos, dataPos, finalPos;
byte blockType = META_VORBIS_COMMENT;
if (isLast) blockType = (byte)(blockType & 0x80);
w.Write(blockType);
sizePos = w.BaseStream.Position;
w.Write(new byte[] { 0, 0, 0 }); // Placeholder for 24-bit integer that will be rewritten at the end of the method
dataPos = w.BaseStream.Position;
result = vorbisTag.Write(w.BaseStream, tag);
finalPos = w.BaseStream.Position;
w.BaseStream.Seek(sizePos, SeekOrigin.Begin);
w.Write(StreamUtils.EncodeBEUInt24((uint)(finalPos - dataPos)));
w.BaseStream.Seek(finalPos, SeekOrigin.Begin);
return result;
}
private int writePictures(BinaryWriter w, IList<PictureInfo> pictures, bool isLast)
{
int result = 0;
long sizePos, dataPos, finalPos;
byte blockType;
foreach (PictureInfo picture in pictures)
{
// Picture has either to be supported, or to come from the right tag standard
bool doWritePicture = !picture.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported);
if (!doWritePicture) doWritePicture = (MetaDataIOFactory.TAG_NATIVE == picture.TagType);
// It also has not to be marked for deletion
doWritePicture = doWritePicture && (!picture.MarkedForDeletion);
if (doWritePicture)
{
blockType = META_PICTURE;
if (isLast) blockType = (byte)(blockType & 0x80);
w.Write(blockType);
sizePos = w.BaseStream.Position;
w.Write(new byte[] { 0, 0, 0 }); // Placeholder for 24-bit integer that will be rewritten at the end of the method
dataPos = w.BaseStream.Position;
vorbisTag.WritePicture(w, picture.PictureData, picture.NativeFormat, ImageUtils.GetMimeTypeFromImageFormat(picture.NativeFormat), picture.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) ? picture.NativePicCode : ID3v2.EncodeID3v2PictureType(picture.PicType), picture.Description);
finalPos = w.BaseStream.Position;
w.BaseStream.Seek(sizePos, SeekOrigin.Begin);
w.Write(StreamUtils.EncodeBEUInt24((uint)(finalPos - dataPos)));
w.BaseStream.Seek(finalPos, SeekOrigin.Begin);
result++;
}
}
return result;
}
public bool Remove(BinaryWriter w)
{
bool result = true;
long cumulativeDelta = 0;
foreach (Zone zone in zones)
{
if (zone.Offset > -1 && zone.Size > zone.CoreSignature.Length)
{
StreamUtils.ShortenStream(w.BaseStream, zone.Offset + zone.Size - cumulativeDelta, (uint)(zone.Size - zone.CoreSignature.Length));
vorbisTag.Clear();
cumulativeDelta += zone.Size - zone.CoreSignature.Length;
}
}
return result;
}
public void SetEmbedder(IMetaDataEmbedder embedder)
{
throw new NotImplementedException();
}
public void Clear()
{
vorbisTag.Clear();
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace DeployCustomThemeWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
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;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Linq.Expressions;
using System.Linq;
using System.Diagnostics;
using Microsoft.Research.DryadLinq;
#pragma warning disable 1591
namespace Microsoft.Research.DryadLinq.Internal
{
public static class DryadLinqSampler
{
internal const double SAMPLE_RATE = 0.001;
private const int MAX_SECOND_PHASE_SAMPLES = 1024*1024;
[Resource(IsStateful=false)]
public static IEnumerable<K> Phase1Sampling<T, K>(IEnumerable<T> source,
Func<T, K> keySelector,
VertexEnv denv)
{
// note: vertexID is constant for each repetition of a specific vertex (eg in fail-and-retry scenarios)
// this is very good as it ensure the sampling is idempotent w.r.t. retries.
long vertexID = DryadLinqNative.GetVertexId(denv.NativeHandle);
int seed = unchecked((int)(vertexID));
long nEmitted = 0;
Random rdm = new Random(seed);
List<K> allSoFar = new List<K>();
List<K> samples = new List<K>();
// try to collect 10 samples, but keep all the records just in case
IEnumerator<T> sourceEnumerator = source.GetEnumerator();
while (sourceEnumerator.MoveNext())
{
T elem = sourceEnumerator.Current;
K key = keySelector(elem);
allSoFar.Add(key);
if (rdm.NextDouble() < SAMPLE_RATE)
{
samples.Add(key);
if (samples.Count >= 10)
break;
}
}
if (samples.Count >= 10)
{
// we have lots of samples.. emit them and continue sampling
allSoFar = null; // not needed.
foreach (K key in samples)
{
yield return key;
nEmitted++;
}
while (sourceEnumerator.MoveNext())
{
T elem = sourceEnumerator.Current;
if (rdm.NextDouble() < SAMPLE_RATE)
{
yield return keySelector(elem);
nEmitted++;
}
}
}
else
{
// sampling didn't produce much, so emit all the records instead.
DryadLinqLog.AddInfo("Sampling produced only {0} records. Emitting all records instead.", samples.Count());
Debug.Assert(sourceEnumerator.MoveNext() == false, "The source enumerator wasn't finished");
samples = null; // the samples list is not needed.
foreach (K key in allSoFar)
{
yield return key;
nEmitted++;
}
}
DryadLinqLog.AddInfo("Stage1 sampling: num keys emitted = {0}", nEmitted);
}
//------------------------------------
//Range-sampler
// 1. Secondary sampling
// 2. sort, and select separator values.
//This method is only used for dynamic inputs. Not required in RTM
//public static IEnumerable<K> RangeSampler_Dynamic<T, K>(IEnumerable<T> source,
// Func<T, K> keySelector,
// IComparer<K> comparer,
// bool isDescending,
// VertexEnv denv)
//{
// if (denv.NumberOfArguments < 2)
// {
// throw new DryadLinqException(SR.Sampler_NotEnoughArgumentsForVertex);
// }
// Int32 pcount = Int32.Parse(denv.GetArgument(denv.NumberOfArguments-1));
// return RangeSamplerCore(source, keySelector, comparer, isDescending, pcount);
//}
// used for static plan (ie pcount is determined on client-side and baked into vertex code)
public static IEnumerable<K>
RangeSampler_Static<K>(IEnumerable<K> firstPhaseSamples,
IComparer<K> comparer,
bool isDescending,
int pcount)
{
return RangeSamplerCore(firstPhaseSamples, comparer, isDescending, pcount);
}
public static IEnumerable<K>
RangeSamplerCore<K>(IEnumerable<K> firstPhaseSamples,
IComparer<K> comparer,
bool isDescending,
int pcount)
{
//Reservoir sampling to produce at most MAX_SECOND_PHASE_SAMPLES records.
K[] samples = new K[MAX_SECOND_PHASE_SAMPLES];
int inputCount = 0;
int reservoirCount = 0;
// fixed-seed is ok here as second-phase-sampler is a singleton vertex. Idempotency is important.
Random r = new Random(314159);
foreach (K key in firstPhaseSamples) // this completely enumerates each source in turn.
{
if (inputCount < MAX_SECOND_PHASE_SAMPLES)
{
samples[reservoirCount] = key;
inputCount++;
reservoirCount++;
}
else
{
int idx = r.Next(inputCount); // ie a number between 0..inputCount-1 inclusive.
if (idx < MAX_SECOND_PHASE_SAMPLES)
{
samples[idx] = key;
}
inputCount++;
}
}
// Sort and Emit the keys
Array.Sort(samples, 0, reservoirCount, comparer);
DryadLinqLog.AddVerbose("Range-partition separator keys: ");
DryadLinqLog.AddVerbose("samples: {0}", reservoirCount);
DryadLinqLog.AddVerbose("pCount: {0}", pcount);
if (reservoirCount == 0)
{
DryadLinqLog.AddVerbose(" case: cnt==0. No separators produced.");
yield break;
}
if (reservoirCount < pcount)
{
//DryadLinqLog.AddVerbose(" case: cnt < pcount");
if (isDescending)
{
//DryadLinqLog.AddVerbose(" case: isDescending=true");
for (int i = reservoirCount - 1; i >= 0; i--)
{
//DryadLinqLog.AddVerbose(" [{0}]", samples[i]);
yield return samples[i];
}
K first = samples[0];
for (int i = reservoirCount; i < pcount - 1; i++)
{
//DryadLinqLog.AddVerbose(" [{0}]", first);
yield return first;
}
}
else
{
//DryadLinqLog.AddVerbose(" case: isDescending=false");
for (int i = 0; i < reservoirCount; i++)
{
//DryadLinqLog.AddVerbose(" [{0}]", samples[i]);
yield return samples[i];
}
K last = samples[reservoirCount - 1];
for (int i = reservoirCount; i < pcount - 1; i++)
{
//DryadLinqLog.AddVerbose(" [{0}]", last);
yield return last;
}
}
}
else
{
//DryadLinqLog.AddVerbose(" case: cnt >= pcount");
int intv = reservoirCount / pcount;
if (isDescending)
{
//DryadLinqLog.AddVerbose(" case: isDescending=true");
int idx = reservoirCount - intv;
for (int i = 0; i < pcount-1; i++)
{
//DryadLinqLog.AddVerbose(" [{0}]", samples[idx]);
yield return samples[idx];
idx -= intv;
}
}
else
{
//DryadLinqLog.AddVerbose(" case: isDescending=false");
int idx = intv;
for (int i = 0; i < pcount-1; i++)
{
//DryadLinqLog.AddVerbose(" [{0}]", samples[idx]);
yield return samples[idx];
idx += intv;
}
}
}
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.SimulationManagement
{
/// <summary>
/// Enumeration values for ActionId (simman.actionrequest.actionid, Action ID,
/// section 7.4)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public enum ActionId : uint
{
/// <summary>
/// Other.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Other.")]
Other = 0,
/// <summary>
/// Local storage of the requested information.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Local storage of the requested information.")]
LocalStorageOfTheRequestedInformation = 1,
/// <summary>
/// Inform SM of event ran out of ammunition.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Inform SM of event ran out of ammunition.")]
InformSMOfEventRanOutOfAmmunition = 2,
/// <summary>
/// Inform SM of event killed in action.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Inform SM of event killed in action.")]
InformSMOfEventKilledInAction = 3,
/// <summary>
/// Inform SM of event damage.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Inform SM of event damage.")]
InformSMOfEventDamage = 4,
/// <summary>
/// Inform SM of event mobility disabled.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Inform SM of event mobility disabled.")]
InformSMOfEventMobilityDisabled = 5,
/// <summary>
/// Inform SM of event fire disabled.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Inform SM of event fire disabled.")]
InformSMOfEventFireDisabled = 6,
/// <summary>
/// Inform SM of event ran out of fuel.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Inform SM of event ran out of fuel.")]
InformSMOfEventRanOutOfFuel = 7,
/// <summary>
/// Recall checkpoint data.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Recall checkpoint data.")]
RecallCheckpointData = 8,
/// <summary>
/// Recall initial parameters.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Recall initial parameters.")]
RecallInitialParameters = 9,
/// <summary>
/// Initiate tether-lead.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initiate tether-lead.")]
InitiateTetherLead = 10,
/// <summary>
/// Initiate tether-follow.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initiate tether-follow.")]
InitiateTetherFollow = 11,
/// <summary>
/// Unthether.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Unthether.")]
Unthether = 12,
/// <summary>
/// Initiate service station resupply.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initiate service station resupply.")]
InitiateServiceStationResupply = 13,
/// <summary>
/// Initiate tailgate resupply.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initiate tailgate resupply.")]
InitiateTailgateResupply = 14,
/// <summary>
/// Initiate hitch lead.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initiate hitch lead.")]
InitiateHitchLead = 15,
/// <summary>
/// Initiate hitch follow.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initiate hitch follow.")]
InitiateHitchFollow = 16,
/// <summary>
/// Unhitch.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Unhitch.")]
Unhitch = 17,
/// <summary>
/// Mount.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Mount.")]
Mount = 18,
/// <summary>
/// Dismount.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Dismount.")]
Dismount = 19,
/// <summary>
/// Start DRC (Daily Readiness Check).
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Start DRC (Daily Readiness Check).")]
StartDRCDailyReadinessCheck = 20,
/// <summary>
/// Stop DRC.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Stop DRC.")]
StopDRC = 21,
/// <summary>
/// Data Query.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Data Query.")]
DataQuery = 22,
/// <summary>
/// Status Request.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Status Request.")]
StatusRequest = 23,
/// <summary>
/// Send Object State Data.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Send Object State Data.")]
SendObjectStateData = 24,
/// <summary>
/// Reconstitute.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Reconstitute.")]
Reconstitute = 25,
/// <summary>
/// Lock Site Configuration.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Lock Site Configuration.")]
LockSiteConfiguration = 26,
/// <summary>
/// Unlock Site Configuration.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Unlock Site Configuration.")]
UnlockSiteConfiguration = 27,
/// <summary>
/// Update Site Configuration.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Update Site Configuration.")]
UpdateSiteConfiguration = 28,
/// <summary>
/// Query Site Configuration.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Query Site Configuration.")]
QuerySiteConfiguration = 29,
/// <summary>
/// Tethering Information.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Tethering Information.")]
TetheringInformation = 30,
/// <summary>
/// Mount Intent.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Mount Intent.")]
MountIntent = 31,
/// <summary>
/// Accept Subscription.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Accept Subscription.")]
AcceptSubscription = 33,
/// <summary>
/// Unsubscribe.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Unsubscribe.")]
Unsubscribe = 34,
/// <summary>
/// Teleport entity.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Teleport entity.")]
TeleportEntity = 35,
/// <summary>
/// Change aggregate state.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Change aggregate state.")]
ChangeAggregateState = 36,
/// <summary>
/// Request Start PDU.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Request Start PDU.")]
RequestStartPDU = 37,
/// <summary>
/// Wakeup get ready for initialization.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Wakeup get ready for initialization.")]
WakeupGetReadyForInitialization = 38,
/// <summary>
/// Initialize internal parameters.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Initialize internal parameters.")]
InitializeInternalParameters = 39,
/// <summary>
/// Send plan data.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Send plan data.")]
SendPlanData = 40,
/// <summary>
/// Synchronize internal clocks.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Synchronize internal clocks.")]
SynchronizeInternalClocks = 41,
/// <summary>
/// Run.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Run.")]
Run = 42,
/// <summary>
/// Save internal parameters.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Save internal parameters.")]
SaveInternalParameters = 43,
/// <summary>
/// Simulate malfunction.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Simulate malfunction.")]
SimulateMalfunction = 44,
/// <summary>
/// Join exercise.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Join exercise.")]
JoinExercise = 45,
/// <summary>
/// Resign exercise.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Resign exercise.")]
ResignExercise = 46,
/// <summary>
/// Time advance.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Time advance.")]
TimeAdvance = 47,
/// <summary>
/// TACCSF LOS Request-Type 1.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("TACCSF LOS Request-Type 1.")]
TACCSFLOSRequestType1 = 100,
/// <summary>
/// TACCSF LOS Request-Type 2.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("TACCSF LOS Request-Type 2.")]
TACCSFLOSRequestType2 = 101
}
}
| |
//#define ASTAR_FAST_NO_EXCEPTIONS //Needs to be enabled for the iPhone build setting Fast But No Exceptions to work.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//using Pathfinding;
using Pathfinding.Util;
namespace Pathfinding {
[System.Serializable]
/** Stores the navigation graphs for the A* Pathfinding System.
* \ingroup relevant
*
* An instance of this class is assigned to AstarPath.astarData, from it you can access all graphs loaded through the #graphs variable.\n
* This class also handles a lot of the high level serialization.
*/
public class AstarData {
/** Shortcut to AstarPath.active */
public AstarPath active {
get {
return AstarPath.active;
}
}
#region Fields
[System.NonSerialized]
public NavMeshGraph navmesh; /**< Shortcut to the first NavMeshGraph. Updated at scanning time. This is the only reference to NavMeshGraph in the core pathfinding scripts */
[System.NonSerialized]
public GridGraph gridGraph; /**< Shortcut to the first GridGraph. Updated at scanning time. This is the only reference to GridGraph in the core pathfinding scripts */
[System.NonSerialized]
public PointGraph pointGraph; /**< Shortcut to the first PointGraph. Updated at scanning time. This is the only reference to PointGraph in the core pathfinding scripts */
/** All supported graph types. Populated through reflection search */
public System.Type[] graphTypes = null;
#if ASTAR_FAST_NO_EXCEPTIONS
/** Graph types to use when building with Fast But No Exceptions for iPhone.
* If you add any custom graph types, you need to add them to this hard-coded list.
*/
public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
typeof(GridGraph),
typeof(PointGraph),
typeof(NavMeshGraph)
};
#endif
[System.NonSerialized]
/** All graphs this instance holds.
* This will be filled only after deserialization has completed.
* May contain null entries if graph have been removed.
*/
public NavGraph[] graphs = new NavGraph[0];
/** Links placed by the user in the scene view. */
[System.NonSerialized]
public UserConnection[] userConnections = new UserConnection[0];
//Serialization Settings
/** Has the data been reverted by an undo operation.
* Used by the editor's undo logic to check if the AstarData has been reverted by an undo operation and should be deserialized */
public bool hasBeenReverted = false;
[SerializeField]
/** Serialized data for all graphs and settings.
*/
private byte[] data;
public uint dataChecksum;
/** Backup data if deserialization failed.
*/
public byte[] data_backup;
/** Serialized data for cached startup */
public byte[] data_cachedStartup;
public byte[] revertData;
/** Should graph-data be cached.
* Caching the startup means saving the whole graphs, not only the settings to an internal array (#data_cachedStartup) which can
* be loaded faster than scanning all graphs at startup. This is setup from the editor.
*/
[SerializeField]
public bool cacheStartup = false;
public bool compress = false;
//End Serialization Settings
#endregion
public byte[] GetData () {
return data;
}
public void SetData (byte[] data, uint checksum) {
this.data = data;
dataChecksum = checksum;
}
/** Loads the graphs from memory, will load cached graphs if any exists */
public void Awake () {
/* Set up default values, to not throw null reference errors */
userConnections = new UserConnection[0];
graphs = new NavGraph[0];
/* End default values */
if (cacheStartup && data_cachedStartup != null) {
LoadFromCache ();
} else {
DeserializeGraphs ();
}
}
/** Updates shortcuts to the first graph of different types.
* Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
* But these references ease the use of the system, so I decided to keep them. It is the only reference to specific graph types in the pathfinding core.\n
*/
public void UpdateShortcuts () {
navmesh = (NavMeshGraph)FindGraphOfType (typeof(NavMeshGraph));
gridGraph = (GridGraph)FindGraphOfType (typeof(GridGraph));
pointGraph = (PointGraph)FindGraphOfType (typeof(PointGraph));
}
public void LoadFromCache () {
AstarPath.active.BlockUntilPathQueueBlocked();
if (data_cachedStartup != null && data_cachedStartup.Length > 0) {
//AstarSerializer serializer = new AstarSerializer (active);
//DeserializeGraphs (serializer,data_cachedStartup);
DeserializeGraphs (data_cachedStartup);
GraphModifier.TriggerEvent (GraphModifier.EventType.PostCacheLoad);
} else {
Debug.LogError ("Can't load from cache since the cache is empty");
}
}
public void SaveCacheData (Pathfinding.Serialization.SerializeSettings settings) {
data_cachedStartup = SerializeGraphs (settings);
cacheStartup = true;
}
#region Serialization
/** Serializes all graphs settings to a byte array.
* \see DeserializeGraphs(byte[])
*/
public byte[] SerializeGraphs () {
return SerializeGraphs (Pathfinding.Serialization.SerializeSettings.Settings);
}
/** Main serializer function. */
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings) {
uint checksum;
return SerializeGraphs (settings, out checksum);
}
/** Main serializer function.
* Serializes all graphs to a byte array
* A similar function exists in the AstarEditor.cs script to save additional info */
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
AstarPath.active.BlockUntilPathQueueBlocked();
Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(this, settings);
sr.OpenSerialize();
SerializeGraphsPart (sr);
byte[] bytes = sr.CloseSerialize();
checksum = sr.GetChecksum ();
return bytes;
}
/** Serializes common info to the serializer.
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void SerializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) {
sr.SerializeGraphs(graphs);
sr.SerializeUserConnections (userConnections);
sr.SerializeNodes();
sr.SerializeExtraInfo();
}
/** Deserializes graphs from #data */
public void DeserializeGraphs () {
if (data != null) {
DeserializeGraphs (data);
}
}
/** Destroys all graphs and sets graphs to null */
void ClearGraphs () {
if ( graphs == null ) return;
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null) graphs[i].OnDestroy ();
}
graphs = null;
UpdateShortcuts ();
}
public void OnDestroy () {
ClearGraphs ();
}
/** Deserializes graphs from the specified byte array.
* If an error ocurred, it will try to deserialize using the old deserializer.
* A warning will be logged if all deserializers failed.
*/
public void DeserializeGraphs (byte[] bytes) {
AstarPath.active.BlockUntilPathQueueBlocked();
try {
if (bytes != null) {
Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(this);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPart (sr);
sr.CloseDeserialize();
} else {
Debug.Log ("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
}
} else {
throw new System.ArgumentNullException ("Bytes should not be null when passed to DeserializeGraphs");
}
active.VerifyIntegrity ();
} catch (System.Exception e) {
Debug.LogWarning ("Caught exception while deserializing data.\n"+e);
data_backup = bytes;
}
}
/** Deserializes graphs from the specified byte array additively.
* If an error ocurred, it will try to deserialize using the old deserializer.
* A warning will be logged if all deserializers failed.
* This function will add loaded graphs to the current ones
*/
public void DeserializeGraphsAdditive (byte[] bytes) {
AstarPath.active.BlockUntilPathQueueBlocked();
try {
if (bytes != null) {
Pathfinding.Serialization.AstarSerializer sr = new Pathfinding.Serialization.AstarSerializer(this);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPartAdditive (sr);
sr.CloseDeserialize();
} else {
Debug.Log ("Invalid data file (cannot read zip).");
}
} else {
throw new System.ArgumentNullException ("Bytes should not be null when passed to DeserializeGraphs");
}
active.VerifyIntegrity ();
} catch (System.Exception e) {
Debug.LogWarning ("Caught exception while deserializing data.\n"+e);
}
}
/** Deserializes common info.
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void DeserializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) {
ClearGraphs ();
graphs = sr.DeserializeGraphs ();
if ( graphs != null ) for ( int i = 0; i<graphs.Length;i++ ) if ( graphs[i] != null ) graphs[i].graphIndex = (uint)i;
userConnections = sr.DeserializeUserConnections();
//sr.DeserializeNodes();
sr.DeserializeExtraInfo();
sr.PostDeserialization();
}
/** Deserializes common info additively
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void DeserializeGraphsPartAdditive (Pathfinding.Serialization.AstarSerializer sr) {
if (graphs == null) graphs = new NavGraph[0];
if (userConnections == null) userConnections = new UserConnection[0];
List<NavGraph> gr = new List<NavGraph>(graphs);
gr.AddRange (sr.DeserializeGraphs ());
graphs = gr.ToArray();
if ( graphs != null ) for ( int i = 0; i<graphs.Length;i++ ) if ( graphs[i] != null ) graphs[i].graphIndex = (uint)i;
List<UserConnection> conns = new List<UserConnection>(userConnections);
conns.AddRange (sr.DeserializeUserConnections());
userConnections = conns.ToArray ();
sr.DeserializeNodes();
//Assign correct graph indices. Issue #21
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) continue;
graphs[i].GetNodes (delegate (GraphNode node) {
//GraphNode[] nodes = graphs[i].nodes;
node.GraphIndex = (uint)i;
return true;
});
}
sr.DeserializeExtraInfo();
sr.PostDeserialization();
for (int i=0;i<graphs.Length;i++) {
for (int j=i+1;j<graphs.Length;j++) {
if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
Debug.LogWarning ("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
graphs[i].guid = Pathfinding.Util.Guid.NewGuid ();
break;
}
}
}
}
#endregion
/** Find all graph types supported in this build.
* Using reflection, the assembly is searched for types which inherit from NavGraph. */
public void FindGraphTypes () {
#if !ASTAR_FAST_NO_EXCEPTIONS
System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly (typeof(AstarPath));
System.Type[] types = asm.GetTypes ();
List<System.Type> graphList = new List<System.Type> ();
foreach (System.Type type in types) {
System.Type baseType = type.BaseType;
while (baseType != null) {
if (baseType == typeof(NavGraph)) {
graphList.Add (type);
break;
}
baseType = baseType.BaseType;
}
}
graphTypes = graphList.ToArray ();
#else
graphTypes = DefaultGraphTypes;
#endif
}
#region GraphCreation
/** \returns A System.Type which matches the specified \a type string. If no mathing graph type was found, null is returned */
public System.Type GetGraphType (string type) {
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i].Name == type) {
return graphTypes[i];
}
}
return null;
}
/** Creates a new instance of a graph of type \a type. If no matching graph type was found, an error is logged and null is returned
* \returns The created graph
* \see CreateGraph(System.Type) */
public NavGraph CreateGraph (string type) {
Debug.Log ("Creating Graph of type '"+type+"'");
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i].Name == type) {
return CreateGraph (graphTypes[i]);
}
}
Debug.LogError ("Graph type ("+type+") wasn't found");
return null;
}
/** Creates a new graph instance of type \a type
* \see CreateGraph(string) */
public NavGraph CreateGraph (System.Type type) {
NavGraph g = System.Activator.CreateInstance (type) as NavGraph;
g.active = active;
return g;
}
/** Adds a graph of type \a type to the #graphs array */
public NavGraph AddGraph (string type) {
NavGraph graph = null;
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i].Name == type) {
graph = CreateGraph (graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError ("No NavGraph of type '"+type+"' could be found");
return null;
}
AddGraph (graph);
return graph;
}
/** Adds a graph of type \a type to the #graphs array */
public NavGraph AddGraph (System.Type type) {
NavGraph graph = null;
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i] == type) {
graph = CreateGraph (graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError ("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
return null;
}
AddGraph (graph);
return graph;
}
/** Adds the specified graph to the #graphs array */
public void AddGraph (NavGraph graph) {
// Make sure to not interfere with pathfinding
AstarPath.active.BlockUntilPathQueueBlocked();
//Try to fill in an empty position
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) {
graphs[i] = graph;
return;
}
}
if (graphs != null && graphs.Length >= GraphNode.MaxGraphCount-1) {
throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphCount +
" graphs. Some compiler directives can change this limit, e.g ASTAR_MORE_AREAS, look under the " +
"'Optimizations' tab in the A* Inspector");
}
//Add a new entry to the list
List<NavGraph> ls = new List<NavGraph> (graphs);
ls.Add (graph);
graphs = ls.ToArray ();
UpdateShortcuts ();
graph.active = active;
graph.Awake ();
graph.graphIndex = (uint)(graphs.Length-1);
}
/** Removes the specified graph from the #graphs array and Destroys it in a safe manner.
* To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
* of actually removing it from the array.
* The empty position will be reused if a new graph is added.
*
* \returns True if the graph was sucessfully removed (i.e it did exist in the #graphs array). False otherwise.
*
* \see NavGraph.SafeOnDestroy
*
* \version Changed in 3.2.5 to call SafeOnDestroy before removing
* and nulling it in the array instead of removing the element completely in the #graphs array.
*
*/
public bool RemoveGraph (NavGraph graph) {
//Safe OnDestroy is called since there is a risk that the pathfinding is searching through the graph right now,
//and if we don't wait until the search has completed we could end up with evil NullReferenceExceptions
graph.SafeOnDestroy ();
int i=0;
for (;i<graphs.Length;i++) if (graphs[i] == graph) break;
if (i == graphs.Length) {
return false;
}
graphs[i] = null;
UpdateShortcuts ();
return true;
}
#endregion
#region GraphUtility
/** Returns the graph which contains the specified node. The graph must be in the #graphs array.
* \returns Returns the graph which contains the node. Null if the graph wasn't found */
public static NavGraph GetGraph (GraphNode node) {
if (node == null) return null;
AstarPath script = AstarPath.active;
if (script == null) return null;
AstarData data = script.astarData;
if (data == null) return null;
if (data.graphs == null) return null;
uint graphIndex = node.GraphIndex;
if (graphIndex >= data.graphs.Length) {
return null;
}
return data.graphs[(int)graphIndex];
}
/** Returns the node at \a graphs[graphIndex].nodes[nodeIndex]. All kinds of error checking is done to make sure no exceptions are thrown. */
public GraphNode GetNode (int graphIndex, int nodeIndex) {
return GetNode (graphIndex,nodeIndex, graphs);
}
/** Returns the node at \a graphs[graphIndex].nodes[nodeIndex]. The graphIndex refers to the specified graphs array.\n
* All kinds of error checking is done to make sure no exceptions are thrown */
public GraphNode GetNode (int graphIndex, int nodeIndex, NavGraph[] graphs) {
throw new System.NotImplementedException ();
/*
if (graphs == null) {
return null;
}
if (graphIndex < 0 || graphIndex >= graphs.Length) {
Debug.LogError ("Graph index is out of range"+graphIndex+ " [0-"+(graphs.Length-1)+"]");
return null;
}
NavGraph graph = graphs[graphIndex];
if (graph.nodes == null) {
return null;
}
if (nodeIndex < 0 || nodeIndex >= graph.nodes.Length) {
Debug.LogError ("Node index is out of range : "+nodeIndex+ " [0-"+(graph.nodes.Length-1)+"]"+" (graph "+graphIndex+")");
return null;
}
return graph.nodes[nodeIndex];*/
}
/** Returns the first graph of type \a type found in the #graphs array. Returns null if none was found */
public NavGraph FindGraphOfType (System.Type type) {
if ( graphs != null ) {
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null && graphs[i].GetType () == type) {
return graphs[i];
}
}
}
return null;
}
/** Loop through this function to get all graphs of type 'type'
* \code foreach (GridGraph graph in AstarPath.astarData.FindGraphsOfType (typeof(GridGraph))) {
* //Do something with the graph
* } \endcode
* \see AstarPath.RegisterSafeNodeUpdate */
public IEnumerable FindGraphsOfType (System.Type type) {
if (graphs == null) { yield break; }
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null && graphs[i].GetType () == type) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IUpdatableGraph graph in AstarPath.astarData.GetUpdateableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see AstarPath.RegisterSafeNodeUpdate
* \see Pathfinding.IUpdatableGraph */
public IEnumerable GetUpdateableGraphs () {
if (graphs == null) { yield break; }
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null && graphs[i] is IUpdatableGraph) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IRaycastableGraph graph in AstarPath.astarData.GetRaycastableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see Pathfinding.IRaycastableGraph*/
public IEnumerable GetRaycastableGraphs () {
if (graphs == null) { yield break; }
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null && graphs[i] is IRaycastableGraph) {
yield return graphs[i];
}
}
}
/** Gets the index of the NavGraph in the #graphs array */
public int GetGraphIndex (NavGraph graph) {
if (graph == null) throw new System.ArgumentNullException ("graph");
if ( graphs != null ) {
for (int i=0;i<graphs.Length;i++) {
if (graph == graphs[i]) {
return i;
}
}
}
Debug.LogError ("Graph doesn't exist");
return -1;
}
/** Tries to find a graph with the specified GUID in the #graphs array.
* If a graph is found it returns its index, otherwise it returns -1
* \see GuidToGraph */
public int GuidToIndex (Guid guid) {
if (graphs == null) {
return -1;
//CollectGraphs ();
}
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) {
continue;
}
if (graphs[i].guid == guid) {
return i;
}
}
return -1;
}
/** Tries to find a graph with the specified GUID in the #graphs array. Returns null if none is found
* \see GuidToIndex */
public NavGraph GuidToGraph (Guid guid) {
if (graphs == null) {
return null;
//CollectGraphs ();
}
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) {
continue;
}
if (graphs[i].guid == guid) {
return graphs[i];
}
}
return null;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Monitor.Fluent
{
using Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.ActionDefinition;
using Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.Definition;
using Microsoft.Azure.Management.Monitor.Fluent.ActionGroup.Update;
using Microsoft.Azure.Management.Monitor.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
/// <summary>
/// Implementation for ActionGroup.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm1vbml0b3IuaW1wbGVtZW50YXRpb24uQWN0aW9uR3JvdXBJbXBs
internal partial class ActionGroupImpl :
GroupableResource<
IActionGroup,
ActionGroupResourceInner,
ActionGroupImpl,
IMonitorManager,
ActionGroup.Definition.IBlank,
ActionGroup.Definition.IWithCreate,
ActionGroup.Definition.IWithCreate,
ActionGroup.Update.IUpdate>,
IActionGroup,
IDefinition,
IActionDefinition<ActionGroup.Definition.IWithCreate>,
IActionDefinition<ActionGroup.Update.IUpdate>,
IUpdate,
IWithActionUpdateDefinition
{
private string actionReceiverPrefix;
private Dictionary<string, Models.AzureAppPushReceiver> appActionReceivers;
private static readonly string appActionSuffix = "_-AzureAppAction-";
private IDictionary<string, Models.EmailReceiver> emailReceivers;
private static readonly string emailSuffix = "_-EmailAction-";
private Dictionary<string, Models.AzureFunctionReceiver> functionReceivers;
private static readonly string functionSuffix = " (F)";
private Dictionary<string, Models.ItsmReceiver> itsmReceivers;
private static readonly string itsmSuffix = " (ITSM)";
private Dictionary<string, Models.LogicAppReceiver> logicReceivers;
private static readonly string logicSuffix = " (LA)";
private Dictionary<string, Models.AutomationRunbookReceiver> runBookReceivers;
private static readonly string runBookSuffix = " (RB)";
private Dictionary<string, Models.SmsReceiver> smsReceivers;
private static readonly string smsSuffix = "_-SMSAction-";
private Dictionary<string, Models.VoiceReceiver> voiceReceivers;
private static readonly string voiceSuffix = "_-VoiceAction-";
private Dictionary<string, Models.WebhookReceiver> webhookReceivers;
private static readonly string webhookSuffix = " (WH)";
///GENMHASH:41BEC53C7D3065426CE12D60045E5A76:62D1D1E233FE3541B287099A447FD5C1
internal ActionGroupImpl(string name, ActionGroupResourceInner innerModel, IMonitorManager monitorManager)
: base(name, innerModel, monitorManager)
{
this.actionReceiverPrefix = "";
this.emailReceivers = new Dictionary<string, Models.EmailReceiver>();
this.smsReceivers = new Dictionary<string, Models.SmsReceiver>();
this.appActionReceivers = new Dictionary<string, Models.AzureAppPushReceiver>();
this.voiceReceivers = new Dictionary<string, Models.VoiceReceiver>();
this.runBookReceivers = new Dictionary<string, Models.AutomationRunbookReceiver>();
this.logicReceivers = new Dictionary<string, Models.LogicAppReceiver>();
this.functionReceivers = new Dictionary<string, Models.AzureFunctionReceiver>();
this.webhookReceivers = new Dictionary<string, Models.WebhookReceiver>();
this.itsmReceivers = new Dictionary<string, Models.ItsmReceiver>();
if (this.IsInCreateMode)
{
this.Inner.Enabled = true;
this.Inner.GroupShortName = this.Name.Substring(0, (this.Name.Length > 12) ? 12 : this.Name.Length);
}
else
{
this.WithExistingResourceGroup(ResourceUtils.GroupFromResourceId(this.Id));
}
}
///GENMHASH:9E5F28984A8DFC9234E431D86BD1C98B:446E17035C92AA884C492FD3B42DF222
private void PopulateReceivers()
{
if (this.emailReceivers.Values.Any())
{
if (this.Inner.EmailReceivers == null)
{
this.Inner.EmailReceivers = new List<EmailReceiver>();
}
else
{
this.Inner.EmailReceivers.Clear();
}
((List<EmailReceiver>)this.Inner.EmailReceivers).AddRange(this.emailReceivers.Values);
}
else
{
this.Inner.EmailReceivers = null;
}
if (this.smsReceivers.Values.Any())
{
if (this.Inner.SmsReceivers == null)
{
this.Inner.SmsReceivers = new List<SmsReceiver>();
}
else
{
this.Inner.SmsReceivers.Clear();
}
((List<SmsReceiver>)this.Inner.SmsReceivers).AddRange(this.smsReceivers.Values);
}
else
{
this.Inner.SmsReceivers = null;
}
if (this.appActionReceivers.Values.Any())
{
if (this.Inner.AzureAppPushReceivers == null)
{
this.Inner.AzureAppPushReceivers = new List<AzureAppPushReceiver>();
}
else
{
this.Inner.AzureAppPushReceivers.Clear();
}
((List<AzureAppPushReceiver>)this.Inner.AzureAppPushReceivers).AddRange(this.appActionReceivers.Values);
}
else
{
this.Inner.AzureAppPushReceivers = null;
}
if (this.voiceReceivers.Values.Any())
{
if (this.Inner.VoiceReceivers == null)
{
this.Inner.VoiceReceivers = new List<VoiceReceiver>();
}
else
{
this.Inner.VoiceReceivers.Clear();
}
((List<VoiceReceiver>)this.Inner.VoiceReceivers).AddRange(this.voiceReceivers.Values);
}
else
{
this.Inner.VoiceReceivers = null;
}
if (this.runBookReceivers.Values.Any())
{
if (this.Inner.AutomationRunbookReceivers == null)
{
this.Inner.AutomationRunbookReceivers = new List<AutomationRunbookReceiver>();
}
else
{
this.Inner.AutomationRunbookReceivers.Clear();
}
((List<AutomationRunbookReceiver>)this.Inner.AutomationRunbookReceivers).AddRange(this.runBookReceivers.Values);
}
else
{
this.Inner.AutomationRunbookReceivers = null;
}
if (this.logicReceivers.Values.Any())
{
if (this.Inner.LogicAppReceivers == null)
{
this.Inner.LogicAppReceivers = new List<LogicAppReceiver>();
}
else
{
this.Inner.LogicAppReceivers.Clear();
}
((List<LogicAppReceiver>)this.Inner.LogicAppReceivers).AddRange(this.logicReceivers.Values);
}
else
{
this.Inner.LogicAppReceivers = null;
}
if (this.functionReceivers.Values.Any())
{
if (this.Inner.AzureFunctionReceivers == null)
{
this.Inner.AzureFunctionReceivers = new List<AzureFunctionReceiver>();
}
else
{
this.Inner.AzureFunctionReceivers.Clear();
}
((List<AzureFunctionReceiver>)this.Inner.AzureFunctionReceivers).AddRange(this.functionReceivers.Values);
}
else
{
this.Inner.AzureFunctionReceivers = null;
}
if (this.webhookReceivers.Values.Any())
{
if (this.Inner.WebhookReceivers == null)
{
this.Inner.WebhookReceivers = new List<WebhookReceiver>();
}
else
{
this.Inner.WebhookReceivers.Clear();
}
((List<WebhookReceiver>)this.Inner.WebhookReceivers).AddRange(this.webhookReceivers.Values);
}
else
{
this.Inner.WebhookReceivers = null;
}
if (this.itsmReceivers.Values.Any())
{
if (this.Inner.ItsmReceivers == null)
{
this.Inner.ItsmReceivers = new List<ItsmReceiver>();
}
else
{
this.Inner.ItsmReceivers.Clear();
}
((List<ItsmReceiver>)this.Inner.ItsmReceivers).AddRange(this.itsmReceivers.Values);
}
else
{
this.Inner.ItsmReceivers = null;
}
}
///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:11B66B97304A7DE4AC2AA17C7BBBF58D
protected async override Task<Models.ActionGroupResourceInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await this.Manager.Inner.ActionGroups.GetAsync(this.ResourceGroupName, this.Name, cancellationToken);
}
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:2E02F656F74847E8C999282F87DB8F0C
public ActionGroupImpl Attach()
{
this.actionReceiverPrefix = "";
PopulateReceivers();
this.emailReceivers.Clear();
this.smsReceivers.Clear();
this.appActionReceivers.Clear();
this.voiceReceivers.Clear();
this.runBookReceivers.Clear();
this.logicReceivers.Clear();
this.functionReceivers.Clear();
this.webhookReceivers.Clear();
this.itsmReceivers.Clear();
return this;
}
///GENMHASH:4554BAEED7C5456CD1392AC46A0B427A:7E3390262271B97BF99FF716DE6906CB
public IReadOnlyList<Models.AutomationRunbookReceiver> AutomationRunbookReceivers()
{
return this.Inner.AutomationRunbookReceivers.ToList();
}
///GENMHASH:F13477E0BE1CCD7BAB34590248147ECB:27202ABC1F2C4E8A5A7A5A906C995A45
public IReadOnlyList<Models.AzureFunctionReceiver> AzureFunctionReceivers()
{
return this.Inner.AzureFunctionReceivers.ToList();
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:E9540F4E2DD531C67CBC49D5ECC9158E
public async override Task<Microsoft.Azure.Management.Monitor.Fluent.IActionGroup> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
this.Inner.Location = "global";
this.SetInner(await this.Manager.Inner.ActionGroups.CreateOrUpdateAsync(this.ResourceGroupName, this.Name, this.Inner, cancellationToken));
return this;
}
///GENMHASH:2D5550FE29FD7200AB73B6351C2A661F:7692C7C7A43C2D3C31B341647F5EF686
public ActionGroupImpl DefineReceiver(string actionNamePrefix)
{
return this.UpdateReceiver(actionNamePrefix);
}
///GENMHASH:9C68A5DA80262C0E546F50E0A2C847B2:50461EBCEEC10788CCE50D23AA972083
public IReadOnlyList<Models.EmailReceiver> EmailReceivers()
{
return this.Inner.EmailReceivers.ToList();
}
///GENMHASH:7276AF4A233B2F0954BFD4C0ECF6D58B:C504382627430A3EBC6E30E4A95CDAA7
public IReadOnlyList<Models.ItsmReceiver> ItsmReceivers()
{
return this.Inner.ItsmReceivers.ToList();
}
///GENMHASH:5F82E93293F5ABE15BC634DD253CAC89:2CAE2F5BEC1E5646870E0372A9D6A879
public IReadOnlyList<Models.LogicAppReceiver> LogicAppReceivers()
{
return this.Inner.LogicAppReceivers.ToList();
}
///GENMHASH:FD5D5A8D6904B467321E345BE1FA424E:E2EB59B5370CEE812A6D8ECA69BFB7D1
public ActionGroupImpl Parent()
{
return this.Attach();
}
///GENMHASH:1DDC53CFDF25A285EC0454044DCD1675:701818A6DF18068BF950BC2079562345
public IReadOnlyList<Models.AzureAppPushReceiver> PushNotificationReceivers()
{
return this.Inner.AzureAppPushReceivers.ToList();
}
///GENMHASH:50EA7681E35A3BDC55F7BBB87F8D9E44:2D4F3E96DFE47F8BC60B3BF071B7170D
public string ShortName()
{
return this.Inner.GroupShortName;
}
///GENMHASH:E9156B2826244EC8242E603AFC88AF52:229D31FAC7AA64177AAC909D4DBD860D
public IReadOnlyList<Models.SmsReceiver> SmsReceivers()
{
return this.Inner.SmsReceivers.ToList();
}
///GENMHASH:F159BED05CA2232DA272DCE38261C1CD:84823286A60ABC06EFCDEBD1EEFAC7CC
public ActionGroupImpl UpdateReceiver(string actionNamePrefix)
{
this.actionReceiverPrefix = actionNamePrefix;
this.emailReceivers.Clear();
this.smsReceivers.Clear();
this.appActionReceivers.Clear();
this.voiceReceivers.Clear();
this.runBookReceivers.Clear();
this.logicReceivers.Clear();
this.functionReceivers.Clear();
this.webhookReceivers.Clear();
this.itsmReceivers.Clear();
if (this.Inner.EmailReceivers != null)
{
foreach (var er in this.Inner.EmailReceivers)
{
this.emailReceivers[er.Name] = er;
}
}
if (this.Inner.SmsReceivers != null)
{
foreach (var sr in this.Inner.SmsReceivers)
{
this.smsReceivers[sr.Name] = sr;
}
}
if (this.Inner.AzureAppPushReceivers != null)
{
foreach (var ar in this.Inner.AzureAppPushReceivers)
{
this.appActionReceivers[ar.Name] = ar;
}
}
if (this.Inner.VoiceReceivers != null)
{
foreach (var vr in this.Inner.VoiceReceivers)
{
this.voiceReceivers[vr.Name] = vr;
}
}
if (this.Inner.AutomationRunbookReceivers != null)
{
foreach (var ar in this.Inner.AutomationRunbookReceivers)
{
this.runBookReceivers[ar.Name] = ar;
}
}
if (this.Inner.LogicAppReceivers != null)
{
foreach (var lr in this.Inner.LogicAppReceivers)
{
this.logicReceivers[lr.Name] = lr;
}
}
if (this.Inner.AzureFunctionReceivers != null)
{
foreach (var fr in this.Inner.AzureFunctionReceivers)
{
this.functionReceivers[fr.Name] = fr;
}
}
if (this.Inner.WebhookReceivers != null)
{
foreach (var wr in this.Inner.WebhookReceivers)
{
this.webhookReceivers[wr.Name] = wr;
}
}
if (this.Inner.ItsmReceivers != null)
{
foreach (var ir in this.Inner.ItsmReceivers)
{
this.itsmReceivers[ir.Name] = ir;
}
}
return this;
}
///GENMHASH:8EE174E1385FB0B32D41564037542BAB:A5878FD314DAE783FB5E0D95F85AA44C
public IReadOnlyList<Models.VoiceReceiver> VoiceReceivers()
{
return this.Inner.VoiceReceivers.ToList();
}
///GENMHASH:6263B9BD1D789A296A068E90CB6A5341:1DF7A6F0713C42E86553F8ECABA9163B
public IReadOnlyList<Models.WebhookReceiver> WebhookReceivers()
{
return this.Inner.WebhookReceivers.ToList();
}
///GENMHASH:4CDF7BECCD0844E46C921F74A59882A2:AE1E8ADC0D1A19DBCA7A107CCDE71569
public ActionGroupImpl WithAutomationRunbook(string automationAccountId, string runbookName, string webhookResourceId, bool isGlobalRunbook)
{
this.WithoutAutomationRunbook();
var compositeKey = this.actionReceiverPrefix + runBookSuffix;
var arr = new AutomationRunbookReceiver
{
Name = compositeKey,
AutomationAccountId = automationAccountId,
RunbookName = runbookName,
WebhookResourceId = webhookResourceId,
IsGlobalRunbook = isGlobalRunbook
};
this.runBookReceivers[compositeKey] = arr;
return this;
}
///GENMHASH:29EAC07C793D2A0E5EB067301A745E12:1239BA4DDECAC5CB19A72AFF5EF502B0
public ActionGroupImpl WithAzureFunction(string functionAppResourceId, string functionName, string httpTriggerUrl)
{
this.WithoutAzureFunction();
var compositeKey = this.actionReceiverPrefix + functionSuffix;
var afr = new AzureFunctionReceiver
{
Name = compositeKey,
FunctionAppResourceId = functionAppResourceId,
FunctionName = functionName,
HttpTriggerUrl = httpTriggerUrl
};
this.functionReceivers[compositeKey] = afr;
return this;
}
///GENMHASH:9CE8C2CD9B4FF3636CD0315913CD5E9D:0B9ABFC681832754AEA179BB66B99F05
public ActionGroupImpl WithEmail(string emailAddress)
{
this.WithoutEmail();
var compositeKey = this.actionReceiverPrefix + emailSuffix;
var er = new EmailReceiver
{
Name = compositeKey,
EmailAddress = emailAddress
};
this.emailReceivers[compositeKey] = er;
return this;
}
///GENMHASH:98D697808674D2777184202E66C380B4:276AB46D78E1C91A065B8814F6C2E177
public ActionGroupImpl WithItsm(string workspaceId, string connectionId, string ticketConfiguration, string region)
{
this.WithoutItsm();
var compositeKey = this.actionReceiverPrefix + itsmSuffix;
var ir = new ItsmReceiver
{
Name = compositeKey,
WorkspaceId = workspaceId,
ConnectionId = connectionId,
Region = region,
TicketConfiguration = ticketConfiguration
};
this.itsmReceivers[compositeKey] = ir;
return this;
}
///GENMHASH:8725DC52ABD03FF631A8419911616ECF:0B992D320C1057B364C3C054EFD0BA8F
public ActionGroupImpl WithLogicApp(string logicAppResourceId, string callbackUrl)
{
this.WithoutLogicApp();
var compositeKey = this.actionReceiverPrefix + logicSuffix;
var lr = new LogicAppReceiver
{
Name = compositeKey,
ResourceId = logicAppResourceId,
CallbackUrl = callbackUrl
};
this.logicReceivers[compositeKey] = lr;
return this;
}
///GENMHASH:99FCD0B812DFC65C409CC3AF22C21EF9:92CF190BD934B53CB15E021DC6619207
public ActionGroupImpl WithoutAutomationRunbook()
{
var compositeKey = this.actionReceiverPrefix + runBookSuffix;
if (this.runBookReceivers.ContainsKey(compositeKey))
{
this.runBookReceivers.Remove(compositeKey);
}
if (this.runBookReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.runBookReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:A4A60D3F15D17DFC190AA6A7DE0A9FC9:20ECB8BB00FE58830FFCD466DA0B77AA
public ActionGroupImpl WithoutAzureFunction()
{
var compositeKey = this.actionReceiverPrefix + logicSuffix;
if (this.functionReceivers.ContainsKey(compositeKey))
{
this.functionReceivers.Remove(compositeKey);
}
if (this.functionReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.functionReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:99CB3039D2358FF53225541164664E2C:66EE3C59C0828BE7D728B62D8B9A635D
public ActionGroupImpl WithoutEmail()
{
var compositeKey = this.actionReceiverPrefix + emailSuffix;
if (this.emailReceivers.ContainsKey(compositeKey))
{
this.emailReceivers.Remove(compositeKey);
}
if (this.emailReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.emailReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:079C08836F7EB8DE5A8595E23651E5B7:3423BB0F36103DF1666285AFFC65BD72
public ActionGroupImpl WithoutItsm()
{
var compositeKey = this.actionReceiverPrefix + itsmSuffix;
if (this.itsmReceivers.ContainsKey(compositeKey))
{
this.itsmReceivers.Remove(compositeKey);
}
if (this.itsmReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.itsmReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:14A2A053D79FB066AD542EFEE40F95CC:F39B7CFC2407B4FEDFAEFA553A1DBAE6
public ActionGroupImpl WithoutLogicApp()
{
var compositeKey = this.actionReceiverPrefix + logicSuffix;
if (this.logicReceivers.ContainsKey(compositeKey))
{
this.logicReceivers.Remove(compositeKey);
}
if (this.logicReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.logicReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:6EC8E9CF1C683C3A8D6B7DDF62FBA07A:7E6C5850D68A45EAB5905869CA3556A8
public ActionGroupImpl WithoutPushNotification()
{
var compositeKey = this.actionReceiverPrefix + appActionSuffix;
if (this.appActionReceivers.ContainsKey(compositeKey))
{
this.appActionReceivers.Remove(compositeKey);
}
if (this.appActionReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.appActionReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:6E2B27425509BA79FDED7388129810A7:5C8848803185D3CBDDFB76762D97E840
public ActionGroupImpl WithoutReceiver(string actionNamePrefix)
{
this.UpdateReceiver(actionNamePrefix);
this.WithoutEmail();
this.WithoutSms();
this.WithoutPushNotification();
this.WithoutVoice();
this.WithoutAutomationRunbook();
this.WithoutLogicApp();
this.WithoutAzureFunction();
this.WithoutWebhook();
this.WithoutItsm();
return this.Parent();
}
///GENMHASH:12CF8A1863C1E0A33100D5123E12554B:66FDA4CEA2F950F926E760061D588669
public ActionGroupImpl WithoutSms()
{
var compositeKey = this.actionReceiverPrefix + smsSuffix;
if (this.smsReceivers.ContainsKey(compositeKey))
{
this.smsReceivers.Remove(compositeKey);
}
if (this.smsReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.smsReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:649BCAE049ABF1D55129AB34FDAF9551:1196CD0E7A3BAC49F4F489DAECE2AA25
public ActionGroupImpl WithoutVoice()
{
var compositeKey = this.actionReceiverPrefix + voiceSuffix;
if (this.voiceReceivers.ContainsKey(compositeKey))
{
this.voiceReceivers.Remove(compositeKey);
}
if (this.voiceReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.voiceReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:B067B8E42D8768ED80A83D5D675D056A:5E8FEBF3231D188D0F5B771A45663427
public ActionGroupImpl WithoutWebhook()
{
var compositeKey = this.actionReceiverPrefix + webhookSuffix;
if (this.webhookReceivers.ContainsKey(compositeKey))
{
this.webhookReceivers.Remove(compositeKey);
}
if (this.webhookReceivers.ContainsKey(this.actionReceiverPrefix))
{
this.webhookReceivers.Remove(actionReceiverPrefix);
}
return this;
}
///GENMHASH:7931352AF6E66532AD6ACE6AC8206A20:7C2BE31C7D877C66ABED0845AC3403DF
public ActionGroupImpl WithPushNotification(string emailAddress)
{
this.WithoutPushNotification();
var compositeKey = this.actionReceiverPrefix + appActionSuffix;
var ar = new AzureAppPushReceiver
{
Name = compositeKey,
EmailAddress = emailAddress
};
this.appActionReceivers[compositeKey] = ar;
return this;
}
///GENMHASH:E15A0C7634ADA2C9A92740002891993B:BE7DA6BC0C09A661C34F2BFFA2DF061D
public ActionGroupImpl WithShortName(string shortName)
{
this.Inner.GroupShortName = shortName;
return this;
}
///GENMHASH:B1C01D344AC2E2E2A88189E7C986CA10:51672C6C6F0ABF78362B77B2C4D0C68E
public ActionGroupImpl WithSms(string countryCode, string phoneNumber)
{
this.WithoutSms();
var compositeKey = this.actionReceiverPrefix + smsSuffix;
var sr = new SmsReceiver
{
Name = compositeKey,
CountryCode = countryCode,
PhoneNumber = phoneNumber
};
this.smsReceivers[compositeKey] = sr;
return this;
}
///GENMHASH:28EA8740CFC6755BFA8A1D7E7EC01656:E04F70E660B16F519FBABB6207B6EA67
public ActionGroupImpl WithVoice(string countryCode, string phoneNumber)
{
this.WithoutVoice();
var compositeKey = this.actionReceiverPrefix + voiceSuffix;
var vr = new VoiceReceiver
{
Name = compositeKey,
CountryCode = countryCode,
PhoneNumber = phoneNumber
};
this.voiceReceivers[compositeKey] = vr;
return this;
}
///GENMHASH:C34DF80D865E0754A608505E39967191:5CD8BED7C3EE09742CEC0037A2B5A61B
public ActionGroupImpl WithWebhook(string serviceUri)
{
this.WithoutWebhook();
var compositeKey = this.actionReceiverPrefix + webhookSuffix;
var wr = new WebhookReceiver
{
Name = compositeKey,
ServiceUri = serviceUri
};
this.webhookReceivers[compositeKey] = wr;
return this;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestDurationTestService : ServiceClient<AutoRestDurationTestService>, IAutoRestDurationTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IDurationOperations.
/// </summary>
public virtual IDurationOperations Duration { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestService(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestService(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestService(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Duration = new DurationOperations(this);
BaseUri = new System.Uri("https://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.xml._Fast
{
public class NodeAccess : global::haxe.lang.DynamicObject
{
public NodeAccess(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
}
}
#line default
}
public NodeAccess(global::Xml x)
{
unchecked
{
#line 28 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
global::haxe.xml._Fast.NodeAccess.__hx_ctor_haxe_xml__Fast_NodeAccess(this, x);
}
#line default
}
public static void __hx_ctor_haxe_xml__Fast_NodeAccess(global::haxe.xml._Fast.NodeAccess __temp_me50, global::Xml x)
{
unchecked
{
#line 29 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
__temp_me50.__x = x;
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.NodeAccess(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.NodeAccess(((global::Xml) (arr[0]) ));
}
#line default
}
public global::Xml __x;
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.__x = ((global::Xml) (@value) );
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
default:
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.__x;
}
default:
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("__x");
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
#line 24 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.xml._Fast
{
public class AttribAccess : global::haxe.lang.DynamicObject
{
public AttribAccess(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
}
}
#line default
}
public AttribAccess(global::Xml x)
{
unchecked
{
#line 47 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
global::haxe.xml._Fast.AttribAccess.__hx_ctor_haxe_xml__Fast_AttribAccess(this, x);
}
#line default
}
public static void __hx_ctor_haxe_xml__Fast_AttribAccess(global::haxe.xml._Fast.AttribAccess __temp_me51, global::Xml x)
{
unchecked
{
#line 48 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
__temp_me51.__x = x;
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.AttribAccess(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.AttribAccess(((global::Xml) (arr[0]) ));
}
#line default
}
public global::Xml __x;
public virtual string resolve(string name)
{
unchecked
{
#line 52 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
if (( this.__x.nodeType == global::Xml.Document ))
{
throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat("Cannot access document attribute ", name));
}
string v = this.__x.@get(name);
if (string.Equals(v, default(string)))
{
throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(this.__x._get_nodeName(), " is missing attribute "), name));
}
return v;
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.__x = ((global::Xml) (@value) );
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
default:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 1734349548:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("resolve"), ((int) (1734349548) ))) );
}
case 4745560:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.__x;
}
default:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 1734349548:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.resolve(global::haxe.lang.Runtime.toString(dynargs[0]));
}
default:
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("__x");
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
#line 43 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.xml._Fast
{
public class HasAttribAccess : global::haxe.lang.DynamicObject
{
public HasAttribAccess(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
}
}
#line default
}
public HasAttribAccess(global::Xml x)
{
unchecked
{
#line 66 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
global::haxe.xml._Fast.HasAttribAccess.__hx_ctor_haxe_xml__Fast_HasAttribAccess(this, x);
}
#line default
}
public static void __hx_ctor_haxe_xml__Fast_HasAttribAccess(global::haxe.xml._Fast.HasAttribAccess __temp_me52, global::Xml x)
{
unchecked
{
#line 67 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
__temp_me52.__x = x;
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.HasAttribAccess(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.HasAttribAccess(((global::Xml) (arr[0]) ));
}
#line default
}
public global::Xml __x;
public virtual bool resolve(string name)
{
unchecked
{
#line 71 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
if (( this.__x.nodeType == global::Xml.Document ))
{
throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat("Cannot access document attribute ", name));
}
return this.__x.exists(name);
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.__x = ((global::Xml) (@value) );
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
default:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 1734349548:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("resolve"), ((int) (1734349548) ))) );
}
case 4745560:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.__x;
}
default:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 1734349548:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.resolve(global::haxe.lang.Runtime.toString(dynargs[0]));
}
default:
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("__x");
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
#line 62 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.xml._Fast
{
public class HasNodeAccess : global::haxe.lang.DynamicObject
{
public HasNodeAccess(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
}
}
#line default
}
public HasNodeAccess(global::Xml x)
{
unchecked
{
#line 82 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
global::haxe.xml._Fast.HasNodeAccess.__hx_ctor_haxe_xml__Fast_HasNodeAccess(this, x);
}
#line default
}
public static void __hx_ctor_haxe_xml__Fast_HasNodeAccess(global::haxe.xml._Fast.HasNodeAccess __temp_me53, global::Xml x)
{
unchecked
{
#line 83 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
__temp_me53.__x = x;
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.HasNodeAccess(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.HasNodeAccess(((global::Xml) (arr[0]) ));
}
#line default
}
public global::Xml __x;
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.__x = ((global::Xml) (@value) );
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
default:
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.__x;
}
default:
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("__x");
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
#line 78 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.xml._Fast
{
public class NodeListAccess : global::haxe.lang.DynamicObject
{
public NodeListAccess(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
}
}
#line default
}
public NodeListAccess(global::Xml x)
{
unchecked
{
#line 96 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
global::haxe.xml._Fast.NodeListAccess.__hx_ctor_haxe_xml__Fast_NodeListAccess(this, x);
}
#line default
}
public static void __hx_ctor_haxe_xml__Fast_NodeListAccess(global::haxe.xml._Fast.NodeListAccess __temp_me54, global::Xml x)
{
unchecked
{
#line 97 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
__temp_me54.__x = x;
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.NodeListAccess(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml._Fast.NodeListAccess(((global::Xml) (arr[0]) ));
}
#line default
}
public global::Xml __x;
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.__x = ((global::Xml) (@value) );
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
default:
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 4745560:
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.__x;
}
default:
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("__x");
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
#line 92 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.xml
{
public class Fast : global::haxe.lang.HxObject
{
public Fast(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
}
}
#line default
}
public Fast(global::Xml x)
{
unchecked
{
#line 122 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
global::haxe.xml.Fast.__hx_ctor_haxe_xml_Fast(this, x);
}
#line default
}
public static void __hx_ctor_haxe_xml_Fast(global::haxe.xml.Fast __temp_me55, global::Xml x)
{
unchecked
{
#line 123 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
if (( ( x.nodeType != global::Xml.Document ) && ( x.nodeType != global::Xml.Element ) ))
{
throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat("Invalid nodeType ", global::Std.@string(x.nodeType)));
}
__temp_me55.x = x;
__temp_me55.node = new global::haxe.xml._Fast.NodeAccess(((global::Xml) (x) ));
__temp_me55.nodes = new global::haxe.xml._Fast.NodeListAccess(((global::Xml) (x) ));
__temp_me55.att = new global::haxe.xml._Fast.AttribAccess(((global::Xml) (x) ));
__temp_me55.has = new global::haxe.xml._Fast.HasAttribAccess(((global::Xml) (x) ));
__temp_me55.hasNode = new global::haxe.xml._Fast.HasNodeAccess(((global::Xml) (x) ));
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml.Fast(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return new global::haxe.xml.Fast(((global::Xml) (arr[0]) ));
}
#line default
}
public global::Xml x;
public global::haxe.xml._Fast.NodeAccess node;
public global::haxe.xml._Fast.NodeListAccess nodes;
public global::haxe.xml._Fast.AttribAccess att;
public global::haxe.xml._Fast.HasAttribAccess has;
public global::haxe.xml._Fast.HasNodeAccess hasNode;
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 407775868:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.hasNode = ((global::haxe.xml._Fast.HasNodeAccess) (@value) );
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
case 5193562:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.has = ((global::haxe.xml._Fast.HasAttribAccess) (@value) );
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
case 4849697:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.att = ((global::haxe.xml._Fast.AttribAccess) (@value) );
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
case 532592689:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.nodes = ((global::haxe.xml._Fast.NodeListAccess) (@value) );
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
case 1225394690:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.node = ((global::haxe.xml._Fast.NodeAccess) (@value) );
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
case 120:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
this.x = ((global::Xml) (@value) );
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return @value;
}
default:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
switch (hash)
{
case 407775868:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.hasNode;
}
case 5193562:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.has;
}
case 4849697:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.att;
}
case 532592689:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.nodes;
}
case 1225394690:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.node;
}
case 120:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return this.x;
}
default:
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("hasNode");
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("has");
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("att");
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("nodes");
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("node");
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
baseArr.push("x");
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
{
#line 109 "C:\\HaxeToolkit\\haxe\\std/haxe/xml/Fast.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
}
| |
///------------------------------------------------------------------------------
// <copyright file="SafeNativeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System;
using System.Security;
using System.Security.Permissions;
using System.Collections;
using System.IO;
using System.Text;
using System.Drawing;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;
using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject;
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods {
[DllImport("shlwapi.dll")]
[ResourceExposure(ResourceScope.None)]
public static extern int SHAutoComplete(HandleRef hwndEdit, int flags);
/*
#if DEBUG
[DllImport(ExternDll.Shell32, EntryPoint="SHGetFileInfo")]
private static extern IntPtr IntSHGetFileInfo([MarshalAs(UnmanagedType.LPWStr)]string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags);
public static IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags) {
IntPtr newHandle = IntSHGetFileInfo(pszPath, dwFileAttributes, info, cbFileInfo, flags);
validImageListHandles.Add(newHandle);
return newHandle;
}
#else
[DllImport(ExternDll.Shell32, CharSet=CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, int dwFileAttributes, NativeMethods.SHFILEINFO info, int cbFileInfo, int flags);
#endif
*/
[DllImport(ExternDll.User32)]
[ResourceExposure(ResourceScope.None)]
public static extern int OemKeyScan(short wAsciiVal);
[DllImport(ExternDll.Gdi32)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetSystemPaletteEntries(HandleRef hdc, int iStartIndex, int nEntries, byte[] lppe);
[DllImport(ExternDll.Gdi32)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetDIBits(HandleRef hdc, HandleRef hbm, int uStartScan, int cScanLines, byte[] lpvBits, ref NativeMethods.BITMAPINFO_FLAT bmi, int uUsage);
[DllImport(ExternDll.Gdi32)]
[ResourceExposure(ResourceScope.None)]
public static extern int StretchDIBits(HandleRef hdc, int XDest, int YDest, int nDestWidth, int nDestHeight, int XSrc, int YSrc, int nSrcWidth, int nSrcHeight, byte[] lpBits, ref NativeMethods.BITMAPINFO_FLAT lpBitsInfo, int iUsage, int dwRop);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateCompatibleBitmap", CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr IntCreateCompatibleBitmap(HandleRef hDC, int width, int height);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr CreateCompatibleBitmap(HandleRef hDC, int width, int height) {
return System.Internal.HandleCollector.Add(IntCreateCompatibleBitmap(hDC, width, height), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetScrollInfo(HandleRef hWnd, int fnBar, [In, Out] NativeMethods.SCROLLINFO si);
[DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsAccelerator(HandleRef hAccel, int cAccelEntries, [In] ref NativeMethods.MSG lpMsg, short[] lpwCmd);
[DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ChooseFont([In, Out] NativeMethods.CHOOSEFONT cf);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetBitmapBits(HandleRef hbmp, int cbBuffer, byte[] lpvBits);
[DllImport(ExternDll.Comdlg32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int CommDlgExtendedError();
[DllImport(ExternDll.Oleaut32, ExactSpelling=true, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
public static extern void SysFreeString(HandleRef bstr);
[DllImport(ExternDll.Oleaut32, PreserveSig=false)]
[ResourceExposure(ResourceScope.None)]
public static extern void OleCreatePropertyFrame(HandleRef hwndOwner, int x, int y, [MarshalAs(UnmanagedType.LPWStr)]string caption, int objects, [MarshalAs(UnmanagedType.Interface)] ref object pobjs, int pages, HandleRef pClsid, int locale, int reserved1, IntPtr reserved2);
[DllImport(ExternDll.Oleaut32, PreserveSig=false)]
[ResourceExposure(ResourceScope.None)]
public static extern void OleCreatePropertyFrame(HandleRef hwndOwner, int x, int y, [MarshalAs(UnmanagedType.LPWStr)]string caption, int objects, [MarshalAs(UnmanagedType.Interface)] ref object pobjs, int pages, Guid[] pClsid, int locale, int reserved1, IntPtr reserved2);
[DllImport(ExternDll.Oleaut32, PreserveSig=false)]
[ResourceExposure(ResourceScope.None)]
public static extern void OleCreatePropertyFrame(HandleRef hwndOwner, int x, int y, [MarshalAs(UnmanagedType.LPWStr)]string caption, int objects, HandleRef lplpobjs, int pages, HandleRef pClsid, int locale, int reserved1, IntPtr reserved2);
[DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, int dwData);
[DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, string dwData);
[DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, [MarshalAs(UnmanagedType.LPStruct)]NativeMethods.HH_POPUP dwData);
[DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, [MarshalAs(UnmanagedType.LPStruct)]NativeMethods.HH_FTS_QUERY dwData);
[DllImport(ExternDll.Hhctrl, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int HtmlHelp(HandleRef hwndCaller, [MarshalAs(UnmanagedType.LPTStr)]string pszFile, int uCommand, [MarshalAs(UnmanagedType.LPStruct)]NativeMethods.HH_AKLINK dwData);
[DllImport(ExternDll.Oleaut32)]
[ResourceExposure(ResourceScope.None)]
public static extern void VariantInit(HandleRef pObject);
[ DllImport(ExternDll.Oleaut32, PreserveSig=false)]
[ResourceExposure(ResourceScope.None)]
public static extern void VariantClear(HandleRef pObject);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool LineTo(HandleRef hdc, int x, int y);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool MoveToEx(HandleRef hdc, int x, int y, NativeMethods.POINT pt);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool Rectangle(
HandleRef hdc, int left, int top, int right, int bottom);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool PatBlt(HandleRef hdc, int left, int top, int width, int height, int rop);
[DllImport(ExternDll.Kernel32, EntryPoint="GetThreadLocale", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern int GetThreadLCID();
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetMessagePos();
[DllImport(ExternDll.User32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int RegisterClipboardFormat(string format);
[DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetClipboardFormatName(int format, StringBuilder lpString, int cchMax);
[DllImport(ExternDll.Comdlg32, SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ChooseColor([In, Out] NativeMethods.CHOOSECOLOR cc);
[DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int RegisterWindowMessage(string msg);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="DeleteObject", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ExternalDeleteObject(HandleRef hObject);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="DeleteObject", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool IntDeleteObject(HandleRef hObject);
public static bool DeleteObject(HandleRef hObject) {
System.Internal.HandleCollector.Remove((IntPtr)hObject, NativeMethods.CommonHandles.GDI);
return IntDeleteObject(hObject);
}
[DllImport(ExternDll.Oleaut32, EntryPoint="OleCreateFontIndirect", ExactSpelling=true, PreserveSig=false)]
[ResourceExposure(ResourceScope.Process)]
public static extern SafeNativeMethods.IFontDisp OleCreateIFontDispIndirect(NativeMethods.FONTDESC fd, ref Guid iid);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateSolidBrush", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr IntCreateSolidBrush(int crColor);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr CreateSolidBrush(int crColor) {
return System.Internal.HandleCollector.Add(IntCreateSolidBrush(crColor), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool SetWindowExtEx(HandleRef hDC, int x, int y, [In, Out] NativeMethods.SIZE size);
[DllImport(ExternDll.Kernel32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId,
int dwLanguageId, StringBuilder lpBuffer, int nSize, HandleRef arguments);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern void InitCommonControls();
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool InitCommonControlsEx(NativeMethods.INITCOMMONCONTROLSEX icc);
#if DEBUG
private static System.Collections.ArrayList validImageListHandles = ArrayList.Synchronized(new System.Collections.ArrayList());
#endif
//
#if DEBUG
[DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Create")]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr IntImageList_Create(int cx, int cy, int flags, int cInitial, int cGrow);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr ImageList_Create(int cx, int cy, int flags, int cInitial, int cGrow) {
IntPtr newHandle = IntImageList_Create(cx, cy, flags, cInitial, cGrow);
validImageListHandles.Add(newHandle);
return newHandle;
}
#else
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr ImageList_Create(int cx, int cy, int flags, int cInitial, int cGrow);
#endif
#if DEBUG
[DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Destroy")]
[ResourceExposure(ResourceScope.None)]
private static extern bool IntImageList_Destroy(HandleRef himl);
public static bool ImageList_Destroy(HandleRef himl) {
System.Diagnostics.Debug.Assert(validImageListHandles.Contains(himl.Handle), "Invalid ImageList handle");
validImageListHandles.Remove(himl.Handle);
return IntImageList_Destroy(himl);
}
#else
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_Destroy(HandleRef himl);
#endif
// unfortunately, the neat wrapper to Assert for DEBUG assumes that this was created by
// our version of ImageList_Create, which is not always the case for the TreeView's internal
// native state image list. Use separate EntryPoint thunk to skip this check:
[DllImport(ExternDll.Comctl32, EntryPoint = "ImageList_Destroy")]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_Destroy_Native(HandleRef himl);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern int ImageList_GetImageCount(HandleRef himl);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern int ImageList_Add(HandleRef himl, HandleRef hbmImage, HandleRef hbmMask);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern int ImageList_ReplaceIcon(HandleRef himl, int index, HandleRef hicon);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern int ImageList_SetBkColor(HandleRef himl, int clrBk);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_Draw(HandleRef himl, int i, HandleRef hdcDst, int x, int y, int fStyle);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_Replace(HandleRef himl, int i, HandleRef hbmImage, HandleRef hbmMask);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_DrawEx(HandleRef himl, int i, HandleRef hdcDst, int x, int y, int dx, int dy, int rgbBk, int rgbFg, int fStyle);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_GetIconSize(HandleRef himl, out int x, out int y);
#if DEBUG
[DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Duplicate")]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr IntImageList_Duplicate(HandleRef himl);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr ImageList_Duplicate(HandleRef himl) {
IntPtr newHandle = IntImageList_Duplicate(himl);
validImageListHandles.Add(newHandle);
return newHandle;
}
#else
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr ImageList_Duplicate(HandleRef himl);
#endif
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_Remove(HandleRef himl, int i);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_GetImageInfo(HandleRef himl, int i, NativeMethods.IMAGEINFO pImageInfo);
#if DEBUG
[DllImport(ExternDll.Comctl32, EntryPoint="ImageList_Read")]
[ResourceExposure(ResourceScope.None)]
private static extern IntPtr IntImageList_Read(UnsafeNativeMethods.IStream pstm);
public static IntPtr ImageList_Read(UnsafeNativeMethods.IStream pstm) {
IntPtr newHandle = IntImageList_Read(pstm);
validImageListHandles.Add(newHandle);
return newHandle;
}
#else
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr ImageList_Read(UnsafeNativeMethods.IStream pstm);
#endif
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ImageList_Write(HandleRef himl, UnsafeNativeMethods.IStream pstm);
[DllImport(ExternDll.Comctl32)]
[ResourceExposure(ResourceScope.None)]
public static extern int ImageList_WriteEx(HandleRef himl, int dwFlags, UnsafeNativeMethods.IStream pstm);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool TrackPopupMenuEx(HandleRef hmenu, int fuFlags, int x, int y, HandleRef hwnd, NativeMethods.TPMPARAMS tpm);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr GetKeyboardLayout(int dwLayout);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr ActivateKeyboardLayout(HandleRef hkl, int uFlags);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetKeyboardLayoutList(int size, [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr[] hkls);
[DllImport(ExternDll.User32, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref NativeMethods.DEVMODE lpDevMode);
[DllImport(ExternDll.User32, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetMonitorInfo(HandleRef hmonitor, [In, Out]NativeMethods.MONITORINFOEX info);
[DllImport(ExternDll.User32, ExactSpelling=true)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr MonitorFromPoint(NativeMethods.POINTSTRUCT pt, int flags);
[DllImport(ExternDll.User32, ExactSpelling=true)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr MonitorFromRect(ref NativeMethods.RECT rect, int flags);
[DllImport(ExternDll.User32, ExactSpelling=true)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr MonitorFromWindow(HandleRef handle, int flags);
[DllImport(ExternDll.User32, ExactSpelling = true)]
[ResourceExposure(ResourceScope.None)]
public static extern bool EnumDisplayMonitors(HandleRef hdc, NativeMethods.COMRECT rcClip, NativeMethods.MonitorEnumProc lpfnEnum, IntPtr dwData);
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateHalftonePalette", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
private static extern IntPtr /*HPALETTE*/ IntCreateHalftonePalette(HandleRef hdc);
public static IntPtr /*HPALETTE*/ CreateHalftonePalette(HandleRef hdc) {
return System.Internal.HandleCollector.Add(IntCreateHalftonePalette(hdc), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetPaletteEntries(HandleRef hpal, int iStartIndex, int nEntries, int[] lppe);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetTextMetricsW(HandleRef hDC, [In, Out] ref NativeMethods.TEXTMETRIC lptm);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetTextMetricsA(HandleRef hDC, [In, Out] ref NativeMethods.TEXTMETRICA lptm);
public static int GetTextMetrics(HandleRef hDC, ref NativeMethods.TEXTMETRIC lptm) {
if (Marshal.SystemDefaultCharSize == 1)
{
// ANSI
NativeMethods.TEXTMETRICA lptmA = new NativeMethods.TEXTMETRICA();
int retVal = SafeNativeMethods.GetTextMetricsA(hDC, ref lptmA);
lptm.tmHeight = lptmA.tmHeight;
lptm.tmAscent = lptmA.tmAscent;
lptm.tmDescent = lptmA.tmDescent;
lptm.tmInternalLeading = lptmA.tmInternalLeading;
lptm.tmExternalLeading = lptmA.tmExternalLeading;
lptm.tmAveCharWidth = lptmA.tmAveCharWidth;
lptm.tmMaxCharWidth = lptmA.tmMaxCharWidth;
lptm.tmWeight = lptmA.tmWeight;
lptm.tmOverhang = lptmA.tmOverhang;
lptm.tmDigitizedAspectX = lptmA.tmDigitizedAspectX;
lptm.tmDigitizedAspectY = lptmA.tmDigitizedAspectY;
lptm.tmFirstChar = (char) lptmA.tmFirstChar;
lptm.tmLastChar = (char) lptmA.tmLastChar;
lptm.tmDefaultChar = (char) lptmA.tmDefaultChar;
lptm.tmBreakChar = (char) lptmA.tmBreakChar;
lptm.tmItalic = lptmA.tmItalic;
lptm.tmUnderlined = lptmA.tmUnderlined;
lptm.tmStruckOut = lptmA.tmStruckOut;
lptm.tmPitchAndFamily = lptmA.tmPitchAndFamily;
lptm.tmCharSet = lptmA.tmCharSet;
return retVal;
}
else
{
// Unicode
return SafeNativeMethods.GetTextMetricsW(hDC, ref lptm);
}
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateDIBSection", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Machine)]
private static extern IntPtr IntCreateDIBSection(HandleRef hdc, HandleRef pbmi, int iUsage, byte[] ppvBits, IntPtr hSection, int dwOffset);
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IntPtr CreateDIBSection(HandleRef hdc, HandleRef pbmi, int iUsage, byte[] ppvBits, IntPtr hSection, int dwOffset) {
return System.Internal.HandleCollector.Add(IntCreateDIBSection(hdc, pbmi, iUsage, ppvBits, hSection, dwOffset), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBitmap", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Machine)]
private static extern IntPtr /*HBITMAP*/ IntCreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, IntPtr lpvBits);
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, IntPtr lpvBits) {
return System.Internal.HandleCollector.Add(IntCreateBitmap(nWidth, nHeight, nPlanes, nBitsPerPixel, lpvBits), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBitmap", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Machine)]
private static extern IntPtr /*HBITMAP*/ IntCreateBitmapShort(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short[] lpvBits);
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short[] lpvBits) {
return System.Internal.HandleCollector.Add(IntCreateBitmapShort(nWidth, nHeight, nPlanes, nBitsPerPixel, lpvBits), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBitmap", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Machine)]
private static extern IntPtr /*HBITMAP*/ IntCreateBitmapByte(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, byte[] lpvBits);
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IntPtr /*HBITMAP*/ CreateBitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, byte[] lpvBits) {
return System.Internal.HandleCollector.Add(IntCreateBitmapByte(nWidth, nHeight, nPlanes, nBitsPerPixel, lpvBits), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreatePatternBrush", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr /*HBRUSH*/ IntCreatePatternBrush(HandleRef hbmp);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr /*HBRUSH*/ CreatePatternBrush(HandleRef hbmp) {
return System.Internal.HandleCollector.Add(IntCreatePatternBrush(hbmp), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateBrushIndirect", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr IntCreateBrushIndirect(NativeMethods.LOGBRUSH lb);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr CreateBrushIndirect(NativeMethods.LOGBRUSH lb) {
return System.Internal.HandleCollector.Add(IntCreateBrushIndirect(lb), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreatePen", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr IntCreatePen(int nStyle, int nWidth, int crColor);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr CreatePen(int nStyle, int nWidth, int crColor) {
return System.Internal.HandleCollector.Add(IntCreatePen(nStyle, nWidth, crColor), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool SetViewportExtEx(HandleRef hDC, int x, int y, NativeMethods.SIZE size);
[DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr LoadCursor(HandleRef hInst, int iconId);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public extern static bool GetClipCursor([In, Out] ref NativeMethods.RECT lpRect);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr GetCursor();
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetIconInfo(HandleRef hIcon, [In, Out] NativeMethods.ICONINFO info);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int IntersectClipRect(HandleRef hDC, int x1, int y1, int x2, int y2);
[DllImport(ExternDll.User32, ExactSpelling=true, EntryPoint="CopyImage", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
private static extern IntPtr IntCopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags);
public static IntPtr CopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags) {
return System.Internal.HandleCollector.Add(IntCopyImage(hImage, uType, cxDesired, cyDesired, fuFlags), NativeMethods.CommonHandles.GDI);
}
public static IntPtr CopyImageAsCursor(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags) {
return System.Internal.HandleCollector.Add(IntCopyImage(hImage, uType, cxDesired, cyDesired, fuFlags), NativeMethods.CommonHandles.Cursor);
}
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool AdjustWindowRectEx(ref NativeMethods.RECT lpRect, int dwStyle, bool bMenu, int dwExStyle);
[DllImport(ExternDll.Ole32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int DoDragDrop(IComDataObject dataObject, UnsafeNativeMethods.IOleDropSource dropSource, int allowedEffects, int[] finalEffect);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr GetSysColorBrush(int nIndex);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool EnableWindow(HandleRef hWnd, bool enable);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetDoubleClickTime();
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetUpdateRgn(HandleRef hwnd, HandleRef hrgn, bool fErase);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ValidateRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect);
//
// WARNING: Don't uncomment this code unless you absolutelly need it. Use instead Marshal.GetLastWin32Error
// and mark your PInvoke [DllImport(..., SetLastError=true)]
// From MSDN:
// GetLastWin32Error exposes the Win32 GetLastError API method from Kernel32.DLL. This method exists because
// it is not safe to make a direct platform invoke call to GetLastError to obtain this information. If you
// want to access this error code, you must call GetLastWin32Error rather than writing your own platform invoke
// definition for GetLastError and calling it. The common language runtime can make internal calls to APIs that
// overwrite the operating system maintained GetLastError.
//
//[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
//public extern static int GetLastError();
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int FillRect(HandleRef hdc, [In] ref NativeMethods.RECT rect, HandleRef hbrush);
[DllImport(ExternDll.Gdi32,ExactSpelling=true,CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int /*COLORREF*/ GetTextColor(HandleRef hDC);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetBkColor(HandleRef hDC);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int /*COLORREF*/ SetTextColor(HandleRef hDC, int crColor);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int SetBkColor(HandleRef hDC, int clr);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr /* HPALETTE */SelectPalette(HandleRef hdc, HandleRef hpal, int bForceBackground);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool SetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] NativeMethods.POINT point);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, EntryPoint="CreateRectRgn", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
private static extern IntPtr IntCreateRectRgn(int x1, int y1, int x2, int y2);
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2) {
return System.Internal.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), NativeMethods.CommonHandles.GDI);
}
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int CombineRgn(HandleRef hRgn, HandleRef hRgn1, HandleRef hRgn2, int nCombineMode);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int RealizePalette(HandleRef hDC);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool LPtoDP(HandleRef hDC, [In, Out] ref NativeMethods.RECT lpRect, int nCount);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool SetWindowOrgEx(HandleRef hDC, int x, int y, [In, Out] NativeMethods.POINT point);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetViewportOrgEx(HandleRef hDC, [In, Out] NativeMethods.POINT point);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int SetMapMode(HandleRef hDC, int nMapMode);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsWindowEnabled(HandleRef hWnd);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsWindowVisible(HandleRef hWnd);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ReleaseCapture();
[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern int GetCurrentThreadId();
[DllImport(ExternDll.User32, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
public static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData);
internal delegate bool EnumThreadWindowsCallback(IntPtr hWnd, IntPtr lParam);
[DllImport(ExternDll.User32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern int GetWindowThreadProcessId(HandleRef hWnd, out int lpdwProcessId);
[return:MarshalAs(UnmanagedType.Bool)]
[DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetExitCodeThread(HandleRef hWnd, out int lpdwExitCode);
[DllImport(ExternDll.User32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ShowWindow(HandleRef hWnd, int nCmdShow);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter,
int x, int y, int cx, int cy, int flags);
[DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetWindowTextLength(HandleRef hWnd);
// this is a wrapper that comctl exposes for the NT function since it doesn't exist natively on 95.
[DllImport(ExternDll.Comctl32, ExactSpelling=true), CLSCompliantAttribute(false)]
[ResourceExposure(ResourceScope.None)]
private static extern bool _TrackMouseEvent(NativeMethods.TRACKMOUSEEVENT tme);
public static bool TrackMouseEvent(NativeMethods.TRACKMOUSEEVENT tme) {
// only on NT - not on 95 - comctl32 has a wrapper for 95 and NT.
return _TrackMouseEvent(tme);
}
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool RedrawWindow(HandleRef hwnd, ref NativeMethods.RECT rcUpdate, HandleRef hrgnUpdate, int flags);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool RedrawWindow(HandleRef hwnd, NativeMethods.COMRECT rcUpdate, HandleRef hrgnUpdate, int flags);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool InvalidateRect(HandleRef hWnd, ref NativeMethods.RECT rect, bool erase);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool InvalidateRect(HandleRef hWnd, NativeMethods.COMRECT rect, bool erase);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool InvalidateRgn(HandleRef hWnd, HandleRef hrgn, bool erase);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool UpdateWindow(HandleRef hWnd);
[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern int GetCurrentProcessId();
[DllImport(ExternDll.User32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int ScrollWindowEx(HandleRef hWnd, int nXAmount, int nYAmount, NativeMethods.COMRECT rectScrollRegion, ref NativeMethods.RECT rectClip, HandleRef hrgnUpdate, ref NativeMethods.RECT prcUpdate, int flags);
[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.AppDomain)]
public static extern int GetThreadLocale();
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool MessageBeep(int type);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool DrawMenuBar(HandleRef hWnd);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public extern static bool IsChild(HandleRef parent, HandleRef child);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, IntPtr lpTimerFunc);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool KillTimer(HandleRef hwnd, int idEvent);
[DllImport(ExternDll.User32, CharSet=System.Runtime.InteropServices.CharSet.Auto),
SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api")]
[ResourceExposure(ResourceScope.None)]
public static extern int MessageBox(HandleRef hWnd, string text, string caption, int type);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr SelectObject(HandleRef hDC, HandleRef hObject);
[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetTickCount();
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ScrollWindow(HandleRef hWnd, int nXAmount, int nYAmount, ref NativeMethods.RECT rectScrollRegion, ref NativeMethods.RECT rectClip);
[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr GetCurrentProcess();
[DllImport(ExternDll.Kernel32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.Process)]
public static extern IntPtr GetCurrentThread();
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.AppDomain)]
public extern static bool SetThreadLocale(int Locale);
[DllImport(ExternDll.User32, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsWindowUnicode(HandleRef hWnd);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool DrawEdge(HandleRef hDC, ref NativeMethods.RECT rect, int edge, int flags);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool DrawFrameControl(HandleRef hDC, ref NativeMethods.RECT rect, int type, int state);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetClipRgn(HandleRef hDC, HandleRef hRgn);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetRgnBox(HandleRef hRegion, ref NativeMethods.RECT clipRect);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int SelectClipRgn(HandleRef hDC, HandleRef hRgn);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int SetROP2(HandleRef hDC, int nDrawMode);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool DrawIcon(HandleRef hDC, int x, int y, HandleRef hIcon);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool DrawIconEx(HandleRef hDC, int x, int y, HandleRef hIcon, int width, int height, int iStepIfAniCursor, HandleRef hBrushFlickerFree, int diFlags);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int SetBkMode(HandleRef hDC, int nBkMode);
[DllImport(ExternDll.Gdi32, SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight,
HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool ShowCaret(HandleRef hWnd);
[DllImport(ExternDll.User32, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool HideCaret(HandleRef hWnd);
[DllImport(ExternDll.User32, CharSet = CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern uint GetCaretBlinkTime();
// Theming/Visual Styles
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsAppThemed();
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeAppProperties();
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern void SetThemeAppProperties(int Flags);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr OpenThemeData(HandleRef hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszClassList);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int CloseThemeData(HandleRef hTheme);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetCurrentThemeName(StringBuilder pszThemeFileName, int dwMaxNameChars, StringBuilder pszColorBuff, int dwMaxColorChars, StringBuilder pszSizeBuff, int cchMaxSizeChars);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsThemePartDefined(HandleRef hTheme, int iPartId, int iStateId);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int DrawThemeBackground(HandleRef hTheme, HandleRef hdc, int partId, int stateId, [In] NativeMethods.COMRECT pRect, [In] NativeMethods.COMRECT pClipRect);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int DrawThemeEdge(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pDestRect, int uEdge, int uFlags, [Out] NativeMethods.COMRECT pContentRect);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int DrawThemeParentBackground(HandleRef hwnd, HandleRef hdc, [In] NativeMethods.COMRECT prc);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int DrawThemeText(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [MarshalAs(UnmanagedType.LPWStr)] string pszText, int iCharCount, int dwTextFlags, int dwTextFlags2, [In] NativeMethods.COMRECT pRect);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeBackgroundContentRect(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pBoundingRect, [Out] NativeMethods.COMRECT pContentRect);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeBackgroundExtent(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pContentRect, [Out] NativeMethods.COMRECT pExtentRect);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeBackgroundRegion(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT pRect, ref IntPtr pRegion);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeBool(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref bool pfVal);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeColor(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref int pColor);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeEnumValue(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref int piVal);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeFilename(HandleRef hTheme, int iPartId, int iStateId, int iPropId, StringBuilder pszThemeFilename, int cchMaxBuffChars);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeFont(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, int iPropId, NativeMethods.LOGFONT pFont);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeInt(HandleRef hTheme, int iPartId, int iStateId, int iPropId, ref int piVal);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemePartSize(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [In] NativeMethods.COMRECT prc, System.Windows.Forms.VisualStyles.ThemeSizeType eSize, [Out] NativeMethods.SIZE psz);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemePosition(HandleRef hTheme, int iPartId, int iStateId, int iPropId, [Out] NativeMethods.POINT pPoint);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeMargins(HandleRef hTheme, HandleRef hDC, int iPartId, int iStateId, int iPropId, ref NativeMethods.MARGINS margins);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeString(HandleRef hTheme, int iPartId, int iStateId, int iPropId, StringBuilder pszBuff, int cchMaxBuffChars);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeDocumentationProperty([MarshalAs(UnmanagedType.LPWStr)] string pszThemeName, [MarshalAs(UnmanagedType.LPWStr)] string pszPropertyName, StringBuilder pszValueBuff, int cchMaxValChars);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeTextExtent(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, [MarshalAs(UnmanagedType.LPWStr)] string pszText, int iCharCount, int dwTextFlags, [In] NativeMethods.COMRECT pBoundingRect, [Out] NativeMethods.COMRECT pExtentRect);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeTextMetrics(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, ref System.Windows.Forms.VisualStyles.TextMetrics ptm);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int HitTestThemeBackground(HandleRef hTheme, HandleRef hdc, int iPartId, int iStateId, int dwOptions, [In] NativeMethods.COMRECT pRect, HandleRef hrgn, [In] NativeMethods.POINTSTRUCT ptTest, ref int pwHitTestCode);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool IsThemeBackgroundPartiallyTransparent(HandleRef hTheme, int iPartId, int iStateId);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern bool GetThemeSysBool(HandleRef hTheme, int iBoolId);
[DllImport(ExternDll.Uxtheme, CharSet=CharSet.Auto)]
[ResourceExposure(ResourceScope.None)]
public static extern int GetThemeSysInt(HandleRef hTheme, int iIntId, ref int piValue);
[DllImportAttribute(ExternDll.User32)]
[ResourceExposure(ResourceScope.None)]
public static extern IntPtr OpenInputDesktop(int dwFlags, [MarshalAs(UnmanagedType.Bool)] bool fInherit, int dwDesiredAccess);
[DllImportAttribute(ExternDll.User32)]
[ResourceExposure(ResourceScope.None)]
public static extern bool CloseDesktop(IntPtr hDesktop);
// Color conversion
//
public static int RGBToCOLORREF(int rgbValue) {
// clear the A value, swap R & B values
int bValue = (rgbValue & 0xFF) << 16;
rgbValue &= 0xFFFF00;
rgbValue |= ((rgbValue >> 16) & 0xFF);
rgbValue &= 0x00FFFF;
rgbValue |= bValue;
return rgbValue;
}
public static Color ColorFromCOLORREF(int colorref) {
int r = colorref & 0xFF;
int g = (colorref >> 8) & 0xFF;
int b = (colorref >> 16) & 0xFF;
return Color.FromArgb(r, g, b);
}
public static int ColorToCOLORREF(Color color) {
return (int)color.R | ((int)color.G << 8) | ((int)color.B << 16);
}
[ComImport(), Guid("BEF6E003-A874-101A-8BBA-00AA00300CAB"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch)]
public interface IFontDisp {
string Name {get; set;}
long Size {get;set;}
bool Bold {get;set;}
bool Italic {get;set;}
bool Underline {get;set;}
bool Strikethrough {get;set;}
short Weight {get;set;}
short Charset {get;set;}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.AccessControl;
/*
Note on transaction support:
Eventually we will want to add support for NT's transactions to our
RegistryKey API's. When we do this, here's
the list of API's we need to make transaction-aware:
RegCreateKeyEx
RegDeleteKey
RegDeleteValue
RegEnumKeyEx
RegEnumValue
RegOpenKeyEx
RegQueryInfoKey
RegQueryValueEx
RegSetValueEx
We can ignore RegConnectRegistry (remote registry access doesn't yet have
transaction support) and RegFlushKey. RegCloseKey doesn't require any
additional work.
*/
/*
Note on ACL support:
The key thing to note about ACL's is you set them on a kernel object like a
registry key, then the ACL only gets checked when you construct handles to
them. So if you set an ACL to deny read access to yourself, you'll still be
able to read with that handle, but not with new handles.
Another peculiarity is a Terminal Server app compatibility hack. The OS
will second guess your attempt to open a handle sometimes. If a certain
combination of Terminal Server app compat registry keys are set, then the
OS will try to reopen your handle with lesser permissions if you couldn't
open it in the specified mode. So on some machines, we will see handles that
may not be able to read or write to a registry key. It's very strange. But
the real test of these handles is attempting to read or set a value in an
affected registry key.
For reference, at least two registry keys must be set to particular values
for this behavior:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1.
HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1
There might possibly be an interaction with yet a third registry key as well.
*/
namespace Microsoft.Win32
{
public sealed partial class RegistryKey : MarshalByRefObject, IDisposable
{
private void ClosePerfDataKey()
{
// System keys should never be closed. However, we want to call RegCloseKey
// on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources
// (i.e. when disposing is true) so that we release the PERFLIB cache and cause it
// to be refreshed (by re-reading the registry) when accessed subsequently.
// This is the only way we can see the just installed perf counter.
// NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race in closing
// the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources
// in this situation the down level OSes are not. We have a small window of race between
// the dispose below and usage elsewhere (other threads). This is By Design.
// This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey
// (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary.
Interop.Advapi32.RegCloseKey(HKEY_PERFORMANCE_DATA);
}
private void FlushCore()
{
if (_hkey != null && IsDirty())
{
Interop.Advapi32.RegFlushKey(_hkey);
}
}
private unsafe RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
int disposition = 0;
// By default, the new key will be writable.
SafeRegistryHandle result = null;
int ret = Interop.Advapi32.RegCreateKeyEx(_hkey,
subkey,
0,
null,
(int)registryOptions /* specifies if the key is volatile */,
GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree) | (int)_regView,
ref secAttrs,
out result,
out disposition);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, _remoteKey, false, _regView);
key._checkMode = permissionCheck;
if (subkey.Length == 0)
{
key._keyName = _keyName;
}
else
{
key._keyName = _keyName + "\\" + subkey;
}
return key;
}
else if (ret != 0) // syscall failed, ret is an error code.
{
Win32Error(ret, _keyName + "\\" + subkey); // Access denied?
}
Debug.Fail("Unexpected code path in RegistryKey::CreateSubKey");
return null;
}
private void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey)
{
int ret = Interop.Advapi32.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0);
if (ret != 0)
{
if (ret == Interop.Errors.ERROR_FILE_NOT_FOUND)
{
if (throwOnMissingSubKey)
{
throw new ArgumentException(SR.Arg_RegSubKeyAbsent);
}
}
else
{
Win32Error(ret, null);
}
}
}
private void DeleteSubKeyTreeCore(string subkey)
{
int ret = Interop.Advapi32.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0);
if (ret != 0)
{
Win32Error(ret, null);
}
}
private void DeleteValueCore(string name, bool throwOnMissingValue)
{
int errorCode = Interop.Advapi32.RegDeleteValue(_hkey, name);
//
// From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
// This still means the name doesn't exist. We need to be consistent with previous OS.
//
if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND ||
errorCode == Interop.Errors.ERROR_FILENAME_EXCED_RANGE)
{
if (throwOnMissingValue)
{
throw new ArgumentException(SR.Arg_RegSubKeyValueAbsent);
}
else
{
// Otherwise, reset and just return giving no indication to the user.
// (For compatibility)
errorCode = 0;
}
}
// We really should throw an exception here if errorCode was bad,
// but we can't for compatibility reasons.
Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
/// <summary>
/// Retrieves a new RegistryKey that represents the requested key. Valid
/// values are:
/// HKEY_CLASSES_ROOT,
/// HKEY_CURRENT_USER,
/// HKEY_LOCAL_MACHINE,
/// HKEY_USERS,
/// HKEY_PERFORMANCE_DATA,
/// HKEY_CURRENT_CONFIG.
/// </summary>
/// <param name="hKeyHive">HKEY_* to open.</param>
/// <returns>The RegistryKey requested.</returns>
private static RegistryKey OpenBaseKeyCore(RegistryHive hKeyHive, RegistryView view)
{
IntPtr hKey = (IntPtr)((int)hKeyHive);
int index = ((int)hKey) & 0x0FFFFFFF;
Debug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!");
Debug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");
bool isPerf = hKey == HKEY_PERFORMANCE_DATA;
// only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA.
SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf);
RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view);
key._checkMode = RegistryKeyPermissionCheck.Default;
key._keyName = s_hkeyNames[index];
return key;
}
private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view)
{
int index = (int)hKey & 0x0FFFFFFF;
if (index < 0 || index >= s_hkeyNames.Length || ((int)hKey & 0xFFFFFFF0) != 0x80000000)
{
throw new ArgumentException(SR.Arg_RegKeyOutOfRange);
}
// connect to the specified remote registry
SafeRegistryHandle foreignHKey = null;
int ret = Interop.Advapi32.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), false), out foreignHKey);
if (ret == Interop.Errors.ERROR_DLL_INIT_FAILED)
{
// return value indicates an error occurred
throw new ArgumentException(SR.Arg_DllInitFailure);
}
if (ret != 0)
{
Win32ErrorStatic(ret, null);
}
if (foreignHKey.IsInvalid)
{
// return value indicates an error occurred
throw new ArgumentException(SR.Format(SR.Arg_RegKeyNoRemoteConnect, machineName));
}
RegistryKey key = new RegistryKey(foreignHKey, true, false, true, ((IntPtr)hKey) == HKEY_PERFORMANCE_DATA, view);
key._checkMode = RegistryKeyPermissionCheck.Default;
key._keyName = s_hkeyNames[index];
return key;
}
private RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights)
{
SafeRegistryHandle result = null;
int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (rights | (int)_regView), out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, _remoteKey, false, _regView);
key._keyName = _keyName + "\\" + name;
key._checkMode = permissionCheck;
return key;
}
if (ret == Interop.Errors.ERROR_ACCESS_DENIED || ret == Interop.Errors.ERROR_BAD_IMPERSONATION_LEVEL)
{
// We need to throw SecurityException here for compatibility reason,
// although UnauthorizedAccessException will make more sense.
throw new SecurityException(SR.Security_RegistryPermission);
}
// Return null if we didn't find the key.
return null;
}
private RegistryKey InternalOpenSubKeyCore(string name, bool writable)
{
SafeRegistryHandle result = null;
int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (GetRegistryKeyAccess(writable) | (int)_regView), out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, _remoteKey, false, _regView);
key._checkMode = GetSubKeyPermissionCheck(writable);
key._keyName = _keyName + "\\" + name;
return key;
}
if (ret == Interop.Errors.ERROR_ACCESS_DENIED || ret == Interop.Errors.ERROR_BAD_IMPERSONATION_LEVEL)
{
// We need to throw SecurityException here for compatibility reasons,
// although UnauthorizedAccessException will make more sense.
throw new SecurityException(SR.Security_RegistryPermission);
}
// Return null if we didn't find the key.
return null;
}
internal RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable)
{
SafeRegistryHandle result = null;
int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (GetRegistryKeyAccess(writable) | (int)_regView), out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, _remoteKey, false, _regView);
key._keyName = _keyName + "\\" + name;
return key;
}
return null;
}
private SafeRegistryHandle SystemKeyHandle
{
get
{
Debug.Assert(IsSystemKey());
int ret = Interop.Errors.ERROR_INVALID_HANDLE;
IntPtr baseKey = (IntPtr)0;
switch (_keyName)
{
case "HKEY_CLASSES_ROOT":
baseKey = HKEY_CLASSES_ROOT;
break;
case "HKEY_CURRENT_USER":
baseKey = HKEY_CURRENT_USER;
break;
case "HKEY_LOCAL_MACHINE":
baseKey = HKEY_LOCAL_MACHINE;
break;
case "HKEY_USERS":
baseKey = HKEY_USERS;
break;
case "HKEY_PERFORMANCE_DATA":
baseKey = HKEY_PERFORMANCE_DATA;
break;
case "HKEY_CURRENT_CONFIG":
baseKey = HKEY_CURRENT_CONFIG;
break;
default:
Win32Error(ret, null);
break;
}
// open the base key so that RegistryKey.Handle will return a valid handle
SafeRegistryHandle result;
ret = Interop.Advapi32.RegOpenKeyEx(baseKey,
null,
0,
GetRegistryKeyAccess(IsWritable()) | (int)_regView,
out result);
if (ret == 0 && !result.IsInvalid)
{
return result;
}
else
{
Win32Error(ret, null);
throw new IOException(Interop.Kernel32.GetMessage(ret), ret);
}
}
}
private int InternalSubKeyCountCore()
{
int subkeys = 0;
int junk = 0;
int ret = Interop.Advapi32.RegQueryInfoKey(_hkey,
null,
null,
IntPtr.Zero,
ref subkeys, // subkeys
null,
null,
ref junk, // values
null,
null,
null,
null);
if (ret != 0)
{
Win32Error(ret, null);
}
return subkeys;
}
private string[] InternalGetSubKeyNamesCore(int subkeys)
{
var names = new List<string>(subkeys);
char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1);
try
{
int result;
int nameLength = name.Length;
while ((result = Interop.Advapi32.RegEnumKeyEx(
_hkey,
names.Count,
name,
ref nameLength,
null,
null,
null,
null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
switch (result)
{
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name, 0, nameLength));
nameLength = name.Length;
break;
default:
// Throw the error
Win32Error(result, null);
break;
}
}
}
finally
{
ArrayPool<char>.Shared.Return(name);
}
return names.ToArray();
}
private int InternalValueCountCore()
{
int values = 0;
int junk = 0;
int ret = Interop.Advapi32.RegQueryInfoKey(_hkey,
null,
null,
IntPtr.Zero,
ref junk, // subkeys
null,
null,
ref values, // values
null,
null,
null,
null);
if (ret != 0)
{
Win32Error(ret, null);
}
return values;
}
/// <summary>Retrieves an array of strings containing all the value names.</summary>
/// <returns>All value names.</returns>
private unsafe string[] GetValueNamesCore(int values)
{
var names = new List<string>(values);
// Names in the registry aren't usually very long, although they can go to as large
// as 16383 characters (MaxValueLength).
//
// Every call to RegEnumValue will allocate another buffer to get the data from
// NtEnumerateValueKey before copying it back out to our passed in buffer. This can
// add up quickly- we'll try to keep the memory pressure low and grow the buffer
// only if needed.
char[] name = ArrayPool<char>.Shared.Rent(100);
try
{
int result;
int nameLength = name.Length;
while ((result = Interop.Advapi32.RegEnumValue(
_hkey,
names.Count,
name,
ref nameLength,
IntPtr.Zero,
null,
null,
null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
switch (result)
{
// The size is only ever reported back correctly in the case
// of ERROR_SUCCESS. It will almost always be changed, however.
case Interop.Errors.ERROR_SUCCESS:
names.Add(new string(name, 0, nameLength));
break;
case Interop.Errors.ERROR_MORE_DATA:
if (IsPerfDataKey())
{
// Enumerating the values for Perf keys always returns
// ERROR_MORE_DATA, but has a valid name. Buffer does need
// to be big enough however. 8 characters is the largest
// known name. The size isn't returned, but the string is
// null terminated.
fixed (char* c = &name[0])
{
names.Add(new string(c));
}
}
else
{
char[] oldName = name;
int oldLength = oldName.Length;
name = null;
ArrayPool<char>.Shared.Return(oldName);
name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2));
}
break;
default:
// Throw the error
Win32Error(result, null);
break;
}
// Always set the name length back to the buffer size
nameLength = name.Length;
}
}
finally
{
if (name != null)
ArrayPool<char>.Shared.Return(name);
}
return names.ToArray();
}
private object InternalGetValueCore(string name, object defaultValue, bool doNotExpand)
{
object data = defaultValue;
int type = 0;
int datasize = 0;
int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
if (IsPerfDataKey())
{
int size = 65000;
int sizeInput = size;
int r;
byte[] blob = new byte[size];
while (Interop.Errors.ERROR_MORE_DATA == (r = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput)))
{
if (size == int.MaxValue)
{
// ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue
Win32Error(r, name);
}
else if (size > (int.MaxValue / 2))
{
// at this point in the loop "size * 2" would cause an overflow
size = int.MaxValue;
}
else
{
size *= 2;
}
sizeInput = size;
blob = new byte[size];
}
if (r != 0)
{
Win32Error(r, name);
}
return blob;
}
else
{
// For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
// Some OS's returned ERROR_MORE_DATA even in success cases, so we
// want to continue on through the function.
if (ret != Interop.Errors.ERROR_MORE_DATA)
{
return data;
}
}
}
if (datasize < 0)
{
// unexpected code path
Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
datasize = 0;
}
switch (type)
{
case Interop.Advapi32.RegistryValues.REG_NONE:
case Interop.Advapi32.RegistryValues.REG_DWORD_BIG_ENDIAN:
case Interop.Advapi32.RegistryValues.REG_BINARY:
{
byte[] blob = new byte[datasize];
ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
data = blob;
}
break;
case Interop.Advapi32.RegistryValues.REG_QWORD:
{ // also REG_QWORD_LITTLE_ENDIAN
if (datasize > 8)
{
// prevent an AV in the edge case that datasize is larger than sizeof(long)
goto case Interop.Advapi32.RegistryValues.REG_BINARY;
}
long blob = 0;
Debug.Assert(datasize == 8, "datasize==8");
// Here, datasize must be 8 when calling this
ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Interop.Advapi32.RegistryValues.REG_DWORD:
{ // also REG_DWORD_LITTLE_ENDIAN
if (datasize > 4)
{
// prevent an AV in the edge case that datasize is larger than sizeof(int)
goto case Interop.Advapi32.RegistryValues.REG_QWORD;
}
int blob = 0;
Debug.Assert(datasize == 4, "datasize==4");
// Here, datasize must be four when calling this
ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Interop.Advapi32.RegistryValues.REG_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new string(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new string(blob);
}
}
break;
case Interop.Advapi32.RegistryValues.REG_EXPAND_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new string(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new string(blob);
}
if (!doNotExpand)
{
data = Environment.ExpandEnvironmentVariables((string)data);
}
}
break;
case Interop.Advapi32.RegistryValues.REG_MULTI_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize);
// make sure the string is null terminated before processing the data
if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
{
Array.Resize(ref blob, blob.Length + 1);
}
string[] strings = Array.Empty<string>();
int stringsCount = 0;
int cur = 0;
int len = blob.Length;
while (ret == 0 && cur < len)
{
int nextNull = cur;
while (nextNull < len && blob[nextNull] != (char)0)
{
nextNull++;
}
string toAdd = null;
if (nextNull < len)
{
Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
if (nextNull - cur > 0)
{
toAdd = new string(blob, cur, nextNull - cur);
}
else
{
// we found an empty string. But if we're at the end of the data,
// it's just the extra null terminator.
if (nextNull != len - 1)
{
toAdd = string.Empty;
}
}
}
else
{
toAdd = new string(blob, cur, len - cur);
}
cur = nextNull + 1;
if (toAdd != null)
{
if (strings.Length == stringsCount)
{
Array.Resize(ref strings, stringsCount > 0 ? stringsCount * 2 : 4);
}
strings[stringsCount++] = toAdd;
}
}
Array.Resize(ref strings, stringsCount);
data = strings;
}
break;
case Interop.Advapi32.RegistryValues.REG_LINK:
default:
break;
}
return data;
}
private RegistryValueKind GetValueKindCore(string name)
{
int type = 0;
int datasize = 0;
int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
Win32Error(ret, null);
}
return
type == Interop.Advapi32.RegistryValues.REG_NONE ? RegistryValueKind.None :
!Enum.IsDefined(typeof(RegistryValueKind), type) ? RegistryValueKind.Unknown :
(RegistryValueKind)type;
}
private unsafe void SetValueCore(string name, object value, RegistryValueKind valueKind)
{
int ret = 0;
try
{
switch (valueKind)
{
case RegistryValueKind.ExpandString:
case RegistryValueKind.String:
{
string data = value.ToString();
ret = Interop.Advapi32.RegSetValueEx(_hkey,
name,
0,
(int)valueKind,
data,
checked(data.Length * 2 + 2));
break;
}
case RegistryValueKind.MultiString:
{
// Other thread might modify the input array after we calculate the buffer length.
// Make a copy of the input array to be safe.
string[] dataStrings = (string[])(((string[])value).Clone());
// First determine the size of the array
//
// Format is null terminator between strings and final null terminator at the end.
// e.g. str1\0str2\0str3\0\0
//
int sizeInChars = 1; // no matter what, we have the final null terminator.
for (int i = 0; i < dataStrings.Length; i++)
{
if (dataStrings[i] == null)
{
throw new ArgumentException(SR.Arg_RegSetStrArrNull);
}
sizeInChars = checked(sizeInChars + (dataStrings[i].Length + 1));
}
int sizeInBytes = checked(sizeInChars * sizeof(char));
// Write out the strings...
//
char[] dataChars = new char[sizeInChars];
int destinationIndex = 0;
for (int i = 0; i < dataStrings.Length; i++)
{
int length = dataStrings[i].Length;
dataStrings[i].CopyTo(0, dataChars, destinationIndex, length);
destinationIndex += (length + 1); // +1 for null terminator, which is already zero-initialized in new array.
}
ret = Interop.Advapi32.RegSetValueEx(_hkey,
name,
0,
Interop.Advapi32.RegistryValues.REG_MULTI_SZ,
dataChars,
sizeInBytes);
break;
}
case RegistryValueKind.None:
case RegistryValueKind.Binary:
byte[] dataBytes = (byte[])value;
ret = Interop.Advapi32.RegSetValueEx(_hkey,
name,
0,
(valueKind == RegistryValueKind.None ? Interop.Advapi32.RegistryValues.REG_NONE : Interop.Advapi32.RegistryValues.REG_BINARY),
dataBytes,
dataBytes.Length);
break;
case RegistryValueKind.DWord:
{
// We need to use Convert here because we could have a boxed type cannot be
// unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail.
int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Interop.Advapi32.RegSetValueEx(_hkey,
name,
0,
Interop.Advapi32.RegistryValues.REG_DWORD,
ref data,
4);
break;
}
case RegistryValueKind.QWord:
{
long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Interop.Advapi32.RegSetValueEx(_hkey,
name,
0,
Interop.Advapi32.RegistryValues.REG_QWORD,
ref data,
8);
break;
}
}
}
catch (Exception exc) when (exc is OverflowException || exc is InvalidOperationException || exc is FormatException || exc is InvalidCastException)
{
throw new ArgumentException(SR.Arg_RegSetMismatchedKind);
}
if (ret == 0)
{
SetDirty();
}
else
{
Win32Error(ret, null);
}
}
/// <summary>
/// After calling GetLastWin32Error(), it clears the last error field,
/// so you must save the HResult and pass it to this method. This method
/// will determine the appropriate exception to throw dependent on your
/// error, and depending on the error, insert a string into the message
/// gotten from the ResourceManager.
/// </summary>
private void Win32Error(int errorCode, string str)
{
switch (errorCode)
{
case Interop.Errors.ERROR_ACCESS_DENIED:
throw str != null ?
new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) :
new UnauthorizedAccessException();
case Interop.Errors.ERROR_INVALID_HANDLE:
// For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
// However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
// SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues
// in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
// on reentrant calls because of this error code path in RegistryKey
//
// Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
// however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
// this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
// having serialized access).
if (!IsPerfDataKey())
{
_hkey.SetHandleAsInvalid();
_hkey = null;
}
goto default;
case Interop.Errors.ERROR_FILE_NOT_FOUND:
throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode);
}
}
private static void Win32ErrorStatic(int errorCode, string str) =>
throw errorCode switch
{
Interop.Errors.ERROR_ACCESS_DENIED => str != null ?
new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) :
new UnauthorizedAccessException(),
_ => new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode),
};
private static int GetRegistryKeyAccess(bool isWritable)
{
int winAccess;
if (!isWritable)
{
winAccess = Interop.Advapi32.RegistryOperations.KEY_READ;
}
else
{
winAccess = Interop.Advapi32.RegistryOperations.KEY_READ | Interop.Advapi32.RegistryOperations.KEY_WRITE;
}
return winAccess;
}
private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode)
{
int winAccess = 0;
switch (mode)
{
case RegistryKeyPermissionCheck.ReadSubTree:
case RegistryKeyPermissionCheck.Default:
winAccess = Interop.Advapi32.RegistryOperations.KEY_READ;
break;
case RegistryKeyPermissionCheck.ReadWriteSubTree:
winAccess = Interop.Advapi32.RegistryOperations.KEY_READ | Interop.Advapi32.RegistryOperations.KEY_WRITE;
break;
default:
Debug.Fail("unexpected code path");
break;
}
return winAccess;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Redis;
using Microsoft.Azure.Management.Redis.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Redis
{
/// <summary>
/// Operations for managing the redis cache.
/// </summary>
internal partial class RedisOperations : IServiceOperations<RedisManagementClient>, IRedisOperations
{
/// <summary>
/// Initializes a new instance of the RedisOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RedisOperations(RedisManagementClient client)
{
this._client = client;
}
private RedisManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Redis.RedisManagementClient.
/// </summary>
public RedisManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with
/// potential downtime) an existing cache
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of CreateOrUpdate redis operation.
/// </returns>
public async Task<RedisCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.RedisVersion == null)
{
throw new ArgumentNullException("parameters.Properties.RedisVersion");
}
if (parameters.Properties.Sku == null)
{
throw new ArgumentNullException("parameters.Properties.Sku");
}
if (parameters.Properties.Sku.Family == null)
{
throw new ArgumentNullException("parameters.Properties.Sku.Family");
}
if (parameters.Properties.Sku.Name == null)
{
throw new ArgumentNullException("parameters.Properties.Sku.Name");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Cache/Redis/" + name.Trim() + "?";
url = url + "api-version=2014-04-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject redisCreateOrUpdateParametersValue = new JObject();
requestDoc = redisCreateOrUpdateParametersValue;
redisCreateOrUpdateParametersValue["location"] = parameters.Location;
JObject propertiesValue = new JObject();
redisCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["redisVersion"] = parameters.Properties.RedisVersion;
JObject skuValue = new JObject();
propertiesValue["sku"] = skuValue;
skuValue["name"] = parameters.Properties.Sku.Name;
skuValue["family"] = parameters.Properties.Sku.Family;
skuValue["capacity"] = parameters.Properties.Sku.Capacity;
if (parameters.Properties.MaxMemoryPolicy != null)
{
propertiesValue["maxMemoryPolicy"] = parameters.Properties.MaxMemoryPolicy;
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.Type = typeInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
RedisReadablePropertiesWithAccessKey propertiesInstance = new RedisReadablePropertiesWithAccessKey();
result.Properties = propertiesInstance;
JToken accessKeysValue = propertiesValue2["accessKeys"];
if (accessKeysValue != null && accessKeysValue.Type != JTokenType.Null)
{
RedisAccessKeys accessKeysInstance = new RedisAccessKeys();
propertiesInstance.AccessKeys = accessKeysInstance;
JToken primaryKeyValue = accessKeysValue["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
accessKeysInstance.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = accessKeysValue["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
accessKeysInstance.SecondaryKey = secondaryKeyInstance;
}
}
JToken provisioningStateValue = propertiesValue2["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue2["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue2["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue2["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue2["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue2 = propertiesValue2["sku"];
if (skuValue2 != null && skuValue2.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue2["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue2["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue2["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue2["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> DeleteAsync(string resourceGroupName, string name, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Cache/Redis/" + name.Trim() + "?";
url = url + "api-version=2014-04-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NotFound)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of GET redis operation.
/// </returns>
public async Task<RedisGetResponse> GetAsync(string resourceGroupName, string name, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Cache/Redis/" + name.Trim() + "?";
url = url + "api-version=2014-04-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.Type = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RedisReadableProperties propertiesInstance = new RedisReadableProperties();
result.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets all redis caches in a resource group (if provided) otherwise
/// all in subscription.
/// </summary>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public async Task<RedisListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "");
if (resourceGroupName != null)
{
url = url + "/resourceGroups/" + Uri.EscapeDataString(resourceGroupName != null ? resourceGroupName.Trim() : "");
}
url = url + "/providers/Microsoft.Cache/Redis/?";
url = url + "api-version=2014-04-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
RedisResource redisResourceInstance = new RedisResource();
result.Value.Add(redisResourceInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
redisResourceInstance.Id = idInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
redisResourceInstance.Location = locationInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
redisResourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
redisResourceInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RedisReadableProperties propertiesInstance = new RedisReadableProperties();
redisResourceInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of redis list keys operation.
/// </returns>
public async Task<RedisListKeysResponse> ListKeysAsync(string resourceGroupName, string name, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
Tracing.Enter(invocationId, this, "ListKeysAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Cache/Redis/" + name.Trim() + "/listKeys?";
url = url + "api-version=2014-04-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisListKeysResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisListKeysResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken primaryKeyValue = responseDoc["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
result.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = responseDoc["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
result.SecondaryKey = secondaryKeyInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets all redis caches using next link.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public async Task<RedisListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
Tracing.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = nextLink.Trim();
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
RedisResource redisResourceInstance = new RedisResource();
result.Value.Add(redisResourceInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
redisResourceInstance.Id = idInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
redisResourceInstance.Location = locationInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
redisResourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
redisResourceInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RedisReadableProperties propertiesInstance = new RedisReadableProperties();
redisResourceInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Specifies which key to reset.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> RegenerateKeyAsync(string resourceGroupName, string name, RedisRegenerateKeyParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "RegenerateKeyAsync", tracingParameters);
}
// Construct URL
string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Cache/Redis/" + name.Trim() + "/regenerateKey?";
url = url + "api-version=2014-04-01-preview";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject redisRegenerateKeyParametersValue = new JObject();
requestDoc = redisRegenerateKeyParametersValue;
redisRegenerateKeyParametersValue["keyType"] = parameters.KeyType.ToString();
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using NUnit.Framework;
using PEG.SyntaxTree;
namespace PEG.Tests
{
[TestFixture]
public class CodeGrammarTest
{
public class TestGrammar1 : Grammar<TestGrammar1>
{
public virtual Expression LetterA()
{
return 'a';
}
public virtual Expression LetterB()
{
return 'b';
}
public virtual Expression LetterChoice()
{
return 'a'._() | 'b';
}
public virtual Expression NonterminalAndLetterChoice()
{
return LetterA() | 'b';
}
public virtual Expression NonterminalAndNonterminalChoice()
{
return LetterA() | LetterB();
}
public virtual Expression LetterSequence()
{
return 'a'._() + 'b';
}
public virtual Expression NonterminalAndLetterSequence()
{
return LetterA() + 'b';
}
public virtual Expression NonterminalAndNonterminalSequence()
{
return LetterA() + LetterB();
}
public virtual Expression NotLetterA()
{
return !LetterA();
}
public virtual Expression AndLetterA()
{
return LetterA().And();
}
public virtual Expression OneOrMoreLetterA()
{
return +LetterA();
}
public virtual Expression ZeroOrMoreLetterA()
{
return -LetterA();
}
public virtual Expression OptionalLetterA()
{
return ~LetterA();
}
public virtual Expression TwoSequences()
{
return LetterA() + LetterB() | LetterB() + LetterA();
}
public virtual Expression ThreeChoices()
{
return LetterA() | LetterB() | 'c';
}
public virtual Expression ThreeExpressionSequence()
{
return LetterA() + LetterB() + 'c';
}
}
[Test]
public void TestGrammar1Letter()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.LetterA());
Assert.AreEqual("LetterA", nonterminal.Name);
Assert.AreEqual('a', ((CharacterTerminal)nonterminal.Expression).Character);
}
[Test]
public void TestGrammar1LetterChoice()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.LetterChoice());
Assert.AreEqual("LetterChoice", nonterminal.Name);
OrderedChoice orderedChoice = (OrderedChoice)nonterminal.Expression;
Assert.AreEqual('a', ((CharacterTerminal)orderedChoice.Expressions[0]).Character);
Assert.AreEqual('b', ((CharacterTerminal)orderedChoice.Expressions[1]).Character);
}
[Test]
public void TestGrammar1NonterminalAndLetterChoice()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.NonterminalAndLetterChoice());
Assert.AreEqual("NonterminalAndLetterChoice", nonterminal.Name);
OrderedChoice orderedChoice = (OrderedChoice)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)orderedChoice.Expressions[0]).Name);
Assert.AreEqual('b', ((CharacterTerminal)orderedChoice.Expressions[1]).Character);
}
[Test]
public void TestGrammar1NonterminalAndNonterminalChoice()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.NonterminalAndNonterminalChoice());
Assert.AreEqual("NonterminalAndNonterminalChoice", nonterminal.Name);
OrderedChoice orderedChoice = (OrderedChoice)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)orderedChoice.Expressions[0]).Name);
Assert.AreEqual("LetterB", ((Nonterminal)orderedChoice.Expressions[1]).Name);
}
[Test]
public void TestGrammar1LetterSequence()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.LetterSequence());
Assert.AreEqual("LetterSequence", nonterminal.Name);
Sequence orderedChoice = (Sequence)nonterminal.Expression;
Assert.AreEqual('a', ((CharacterTerminal)orderedChoice.Expressions[0]).Character);
Assert.AreEqual('b', ((CharacterTerminal)orderedChoice.Expressions[1]).Character);
}
[Test]
public void TestGrammar1NonterminalAndLetterSequence()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.NonterminalAndLetterSequence());
Assert.AreEqual("NonterminalAndLetterSequence", nonterminal.Name);
Sequence orderedChoice = (Sequence)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)orderedChoice.Expressions[0]).Name);
Assert.AreEqual('b', ((CharacterTerminal)orderedChoice.Expressions[1]).Character);
}
[Test]
public void TestGrammar1NonterminalAndNonterminalSequence()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.NonterminalAndNonterminalSequence());
Assert.AreEqual("NonterminalAndNonterminalSequence", nonterminal.Name);
Sequence orderedChoice = (Sequence)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)orderedChoice.Expressions[0]).Name);
Assert.AreEqual("LetterB", ((Nonterminal)orderedChoice.Expressions[1]).Name);
}
[Test]
public void TestGrammar1NotLetterA()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.NotLetterA());
Assert.AreEqual("NotLetterA", nonterminal.Name);
NotPredicate expression = (NotPredicate)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)expression.Operand).Name);
}
[Test]
public void TestGrammarAndLetterA()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.AndLetterA());
Assert.AreEqual("AndLetterA", nonterminal.Name);
AndPredicate expression = (AndPredicate)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)expression.Operand).Name);
}
[Test]
public void TestGrammarOneOrMoreLetterA()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.OneOrMoreLetterA());
Assert.AreEqual("OneOrMoreLetterA", nonterminal.Name);
OneOrMore expression = (OneOrMore)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)expression.Operand).Name);
}
[Test]
public void TestGrammarZeroOrMoreLetterA()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.ZeroOrMoreLetterA());
Assert.AreEqual("ZeroOrMoreLetterA", nonterminal.Name);
ZeroOrMore expression = (ZeroOrMore)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)expression.Operand).Name);
}
[Test]
public void TestGrammarOptionalLetterA()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.OptionalLetterA());
Assert.AreEqual("OptionalLetterA", nonterminal.Name);
Optional expression = (Optional)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)expression.Operand).Name);
}
[Test]
public void TestGrammarTwoSequences()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.TwoSequences());
Assert.AreEqual("TwoSequences", nonterminal.Name);
OrderedChoice orderedChoice = (OrderedChoice)nonterminal.Expression;
Sequence sequence1 = (Sequence)orderedChoice.Expressions[0];
Sequence sequence2 = (Sequence)orderedChoice.Expressions[1];
Assert.AreEqual("LetterA", ((Nonterminal)sequence1.Expressions[0]).Name);
Assert.AreEqual("LetterB", ((Nonterminal)sequence1.Expressions[1]).Name);
Assert.AreEqual("LetterB", ((Nonterminal)sequence2.Expressions[0]).Name);
Assert.AreEqual("LetterA", ((Nonterminal)sequence2.Expressions[1]).Name);
}
[Test]
public void TestGrammarThreeChoices()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.ThreeChoices());
Assert.AreEqual("ThreeChoices", nonterminal.Name);
OrderedChoice orderedChoice = (OrderedChoice)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)orderedChoice.Expressions[0]).Name);
Assert.AreEqual("LetterB", ((Nonterminal)orderedChoice.Expressions[1]).Name);
Assert.AreEqual('c', ((CharacterTerminal)orderedChoice.Expressions[2]).Character);
}
[Test]
public void TestGrammarThreeExpressionSequence()
{
TestGrammar1 grammar = TestGrammar1.Create();
Nonterminal nonterminal = grammar.GetNonterminal(o => o.ThreeExpressionSequence());
Assert.AreEqual("ThreeExpressionSequence", nonterminal.Name);
Sequence sequence = (Sequence)nonterminal.Expression;
Assert.AreEqual("LetterA", ((Nonterminal)sequence.Expressions[0]).Name);
Assert.AreEqual("LetterB", ((Nonterminal)sequence.Expressions[1]).Name);
Assert.AreEqual('c', ((CharacterTerminal)sequence.Expressions[2]).Character);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
namespace System
{
public partial class String
{
private const int TrimHead = 0;
private const int TrimTail = 1;
private const int TrimBoth = 2;
unsafe private static void FillStringChecked(String dest, int destPos, String src)
{
if (src.Length > dest.Length - destPos)
{
throw new IndexOutOfRangeException();
}
fixed (char* pDest = &dest._firstChar)
fixed (char* pSrc = &src._firstChar)
{
wstrcpy(pDest + destPos, pSrc, src.Length);
}
}
public static String Concat(Object arg0)
{
if (arg0 == null)
{
return String.Empty;
}
return arg0.ToString();
}
public static String Concat(Object arg0, Object arg1)
{
if (arg0 == null)
{
arg0 = String.Empty;
}
if (arg1 == null)
{
arg1 = String.Empty;
}
return Concat(arg0.ToString(), arg1.ToString());
}
public static String Concat(Object arg0, Object arg1, Object arg2)
{
if (arg0 == null)
{
arg0 = String.Empty;
}
if (arg1 == null)
{
arg1 = String.Empty;
}
if (arg2 == null)
{
arg2 = String.Empty;
}
return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString());
}
public static string Concat(params object[] args)
{
if (args == null)
{
throw new ArgumentNullException("args");
}
if (args.Length <= 1)
{
return args.Length == 0 ?
string.Empty :
args[0]?.ToString() ?? string.Empty;
}
// We need to get an intermediary string array
// to fill with each of the args' ToString(),
// and then just concat that in one operation.
// This way we avoid any intermediary string representations,
// or buffer resizing if we use StringBuilder (although the
// latter case is partially alleviated due to StringBuilder's
// linked-list style implementation)
var strings = new string[args.Length];
int totalLength = 0;
for (int i = 0; i < args.Length; i++)
{
object value = args[i];
string toString = value?.ToString() ?? string.Empty; // We need to handle both the cases when value or value.ToString() is null
strings[i] = toString;
totalLength += toString.Length;
if (totalLength < 0) // Check for a positive overflow
{
throw new OutOfMemoryException();
}
}
// If all of the ToStrings are null/empty, just return string.Empty
if (totalLength == 0)
{
return string.Empty;
}
string result = FastAllocateString(totalLength);
int position = 0; // How many characters we've copied so far
for (int i = 0; i < strings.Length; i++)
{
string s = strings[i];
Contract.Assert(s != null);
Contract.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
FillStringChecked(result, position, s);
position += s.Length;
}
return result;
}
public static string Concat<T>(IEnumerable<T> values)
{
if (values == null)
throw new ArgumentNullException("values");
using (IEnumerator<T> en = values.GetEnumerator())
{
if (!en.MoveNext())
return string.Empty;
// We called MoveNext once, so this will be the first item
T currentValue = en.Current;
// Call ToString before calling MoveNext again, since
// we want to stay consistent with the below loop
// Everything should be called in the order
// MoveNext-Current-ToString, unless further optimizations
// can be made, to avoid breaking changes
string firstString = currentValue?.ToString();
// If there's only 1 item, simply call ToString on that
if (!en.MoveNext())
{
// We have to handle the case of either currentValue
// or its ToString being null
return firstString ?? string.Empty;
}
StringBuilder result = StringBuilderCache.Acquire();
result.Append(firstString);
do
{
currentValue = en.Current;
if (currentValue != null)
{
result.Append(currentValue.ToString());
}
}
while (en.MoveNext());
return StringBuilderCache.GetStringAndRelease(result);
}
}
public static string Concat(IEnumerable<string> values)
{
if (values == null)
throw new ArgumentNullException("values");
using (IEnumerator<string> en = values.GetEnumerator())
{
if (!en.MoveNext())
return string.Empty;
string firstValue = en.Current;
if (!en.MoveNext())
{
return firstValue ?? string.Empty;
}
StringBuilder result = StringBuilderCache.Acquire();
result.Append(firstValue);
do
{
result.Append(en.Current);
}
while (en.MoveNext());
return StringBuilderCache.GetStringAndRelease(result);
}
}
public static String Concat(String str0, String str1)
{
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return String.Empty;
}
return str1;
}
if (IsNullOrEmpty(str1))
{
return str0;
}
int str0Length = str0.Length;
String result = FastAllocateString(str0Length + str1.Length);
FillStringChecked(result, 0, str0);
FillStringChecked(result, str0Length, str1);
return result;
}
public static String Concat(String str0, String str1, String str2)
{
if (IsNullOrEmpty(str0))
{
return Concat(str1, str2);
}
if (IsNullOrEmpty(str1))
{
return Concat(str0, str2);
}
if (IsNullOrEmpty(str2))
{
return Concat(str0, str1);
}
int totalLength = str0.Length + str1.Length + str2.Length;
String result = FastAllocateString(totalLength);
FillStringChecked(result, 0, str0);
FillStringChecked(result, str0.Length, str1);
FillStringChecked(result, str0.Length + str1.Length, str2);
return result;
}
public static String Concat(String str0, String str1, String str2, String str3)
{
if (IsNullOrEmpty(str0))
{
return Concat(str1, str2, str3);
}
if (IsNullOrEmpty(str1))
{
return Concat(str0, str2, str3);
}
if (IsNullOrEmpty(str2))
{
return Concat(str0, str1, str3);
}
if (IsNullOrEmpty(str3))
{
return Concat(str0, str1, str2);
}
int totalLength = str0.Length + str1.Length + str2.Length + str3.Length;
String result = FastAllocateString(totalLength);
FillStringChecked(result, 0, str0);
FillStringChecked(result, str0.Length, str1);
FillStringChecked(result, str0.Length + str1.Length, str2);
FillStringChecked(result, str0.Length + str1.Length + str2.Length, str3);
return result;
}
public static String Concat(params String[] values)
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length <= 1)
{
return values.Length == 0 ?
string.Empty :
values[0] ?? string.Empty;
}
// It's possible that the input values array could be changed concurrently on another
// thread, such that we can't trust that each read of values[i] will be equivalent.
// Worst case, we can make a defensive copy of the array and use that, but we first
// optimistically try the allocation and copies assuming that the array isn't changing,
// which represents the 99.999% case, in particular since string.Concat is used for
// string concatenation by the languages, with the input array being a params array.
// Sum the lengths of all input strings
long totalLengthLong = 0;
for (int i = 0; i < values.Length; i++)
{
string value = values[i];
if (value != null)
{
totalLengthLong += value.Length;
}
}
// If it's too long, fail, or if it's empty, return an empty string.
if (totalLengthLong > int.MaxValue)
{
throw new OutOfMemoryException();
}
int totalLength = (int)totalLengthLong;
if (totalLength == 0)
{
return string.Empty;
}
// Allocate a new string and copy each input string into it
string result = FastAllocateString(totalLength);
int copiedLength = 0;
for (int i = 0; i < values.Length; i++)
{
string value = values[i];
if (!string.IsNullOrEmpty(value))
{
int valueLen = value.Length;
if (valueLen > totalLength - copiedLength)
{
copiedLength = -1;
break;
}
FillStringChecked(result, copiedLength, value);
copiedLength += valueLen;
}
}
// If we copied exactly the right amount, return the new string. Otherwise,
// something changed concurrently to mutate the input array: fall back to
// doing the concatenation again, but this time with a defensive copy. This
// fall back should be extremely rare.
return copiedLength == totalLength ? result : Concat((string[])values.Clone());
}
public static String Format(String format, params Object[] args)
{
if (args == null)
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in FormatHelper.
throw new ArgumentNullException((format == null) ? "format" : "args");
}
return FormatHelper(null, format, new ParamsArray(args));
}
public static String Format(String format, Object arg0)
{
return FormatHelper(null, format, new ParamsArray(arg0));
}
public static String Format(String format, Object arg0, Object arg1)
{
return FormatHelper(null, format, new ParamsArray(arg0, arg1));
}
public static String Format(String format, Object arg0, Object arg1, Object arg2)
{
return FormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
}
public static String Format(IFormatProvider provider, String format, params Object[] args)
{
if (args == null)
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in FormatHelper.
throw new ArgumentNullException((format == null) ? "format" : "args");
}
return FormatHelper(provider, format, new ParamsArray(args));
}
public static String Format(IFormatProvider provider, String format, Object arg0)
{
return FormatHelper(provider, format, new ParamsArray(arg0));
}
public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1)
{
return FormatHelper(provider, format, new ParamsArray(arg0, arg1));
}
public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2)
{
return FormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
}
private static String FormatHelper(IFormatProvider provider, String format, ParamsArray args)
{
if (format == null)
throw new ArgumentNullException("format");
return StringBuilderCache.GetStringAndRelease(
StringBuilderCache
.Acquire(format.Length + args.Length * 8)
.AppendFormatHelper(provider, format, args));
}
public String Insert(int startIndex, String value)
{
if (value == null)
throw new ArgumentNullException("value");
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException("startIndex");
int oldLength = Length;
int insertLength = value.Length;
if (oldLength == 0)
return value;
if (insertLength == 0)
return this;
int newLength = oldLength + insertLength;
if (newLength < 0)
throw new OutOfMemoryException();
String result = FastAllocateString(newLength);
unsafe
{
fixed (char* srcThis = &_firstChar)
{
fixed (char* srcInsert = &value._firstChar)
{
fixed (char* dst = &result._firstChar)
{
wstrcpy(dst, srcThis, startIndex);
wstrcpy(dst + startIndex, srcInsert, insertLength);
wstrcpy(dst + startIndex + insertLength, srcThis + startIndex, oldLength - startIndex);
}
}
}
}
return result;
}
// Joins an array of strings together as one string with a separator between each original string.
//
public static String Join(String separator, params String[] value)
{
if (value == null)
throw new ArgumentNullException("value");
return Join(separator, value, 0, value.Length);
}
public static string Join(string separator, params object[] values)
{
if (values == null)
throw new ArgumentNullException("values");
if (values.Length == 0 || values[0] == null)
return string.Empty;
string firstString = values[0].ToString();
if (values.Length == 1)
{
return firstString ?? string.Empty;
}
StringBuilder result = StringBuilderCache.Acquire();
result.Append(firstString);
for (int i = 1; i < values.Length; i++)
{
result.Append(separator);
object value = values[i];
if (value != null)
{
result.Append(value.ToString());
}
}
return StringBuilderCache.GetStringAndRelease(result);
}
public static String Join<T>(String separator, IEnumerable<T> values)
{
if (values == null)
throw new ArgumentNullException("values");
using (IEnumerator<T> en = values.GetEnumerator())
{
if (!en.MoveNext())
return string.Empty;
// We called MoveNext once, so this will be the first item
T currentValue = en.Current;
// Call ToString before calling MoveNext again, since
// we want to stay consistent with the below loop
// Everything should be called in the order
// MoveNext-Current-ToString, unless further optimizations
// can be made, to avoid breaking changes
string firstString = currentValue?.ToString();
// If there's only 1 item, simply call ToString on that
if (!en.MoveNext())
{
// We have to handle the case of either currentValue
// or its ToString being null
return firstString ?? string.Empty;
}
StringBuilder result = StringBuilderCache.Acquire();
result.Append(firstString);
do
{
currentValue = en.Current;
result.Append(separator);
if (currentValue != null)
{
result.Append(currentValue.ToString());
}
}
while (en.MoveNext());
return StringBuilderCache.GetStringAndRelease(result);
}
}
public static String Join(String separator, IEnumerable<String> values)
{
if (values == null)
throw new ArgumentNullException("values");
using (IEnumerator<String> en = values.GetEnumerator())
{
if (!en.MoveNext())
return String.Empty;
String firstValue = en.Current;
if (!en.MoveNext())
{
// Only one value available
return firstValue ?? String.Empty;
}
// Null separator and values are handled by the StringBuilder
StringBuilder result = StringBuilderCache.Acquire();
result.Append(firstValue);
do
{
result.Append(separator);
result.Append(en.Current);
} while (en.MoveNext());
return StringBuilderCache.GetStringAndRelease(result);
}
}
// Joins an array of strings together as one string with a separator between each original string.
//
public unsafe static String Join(String separator, String[] value, int startIndex, int count)
{
//Range check the array
if (value == null)
throw new ArgumentNullException("value");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount);
if (startIndex > value.Length - count)
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_IndexCountBuffer);
//Treat null as empty string.
if (separator == null)
{
separator = String.Empty;
}
//If count is 0, that skews a whole bunch of the calculations below, so just special case that.
if (count == 0)
{
return String.Empty;
}
if (count == 1)
{
return value[startIndex] ?? String.Empty;
}
int endIndex = startIndex + count - 1;
StringBuilder result = StringBuilderCache.Acquire();
// Append the first string first and then append each following string prefixed by the separator.
result.Append(value[startIndex]);
for (int stringToJoinIndex = startIndex + 1; stringToJoinIndex <= endIndex; stringToJoinIndex++)
{
result.Append(separator);
result.Append(value[stringToJoinIndex]);
}
return StringBuilderCache.GetStringAndRelease(result);
}
public String PadLeft(int totalWidth)
{
return PadLeft(totalWidth, ' ');
}
public String PadLeft(int totalWidth, char paddingChar)
{
if (totalWidth < 0)
throw new ArgumentOutOfRangeException("totalWidth", SR.ArgumentOutOfRange_NeedNonNegNum);
int oldLength = Length;
int count = totalWidth - oldLength;
if (count <= 0)
return this;
String result = FastAllocateString(totalWidth);
unsafe
{
fixed (char* dst = &result._firstChar)
{
for (int i = 0; i < count; i++)
dst[i] = paddingChar;
fixed (char* src = &_firstChar)
{
wstrcpy(dst + count, src, oldLength);
}
}
}
return result;
}
public String PadRight(int totalWidth)
{
return PadRight(totalWidth, ' ');
}
public String PadRight(int totalWidth, char paddingChar)
{
if (totalWidth < 0)
throw new ArgumentOutOfRangeException("totalWidth", SR.ArgumentOutOfRange_NeedNonNegNum);
int oldLength = Length;
int count = totalWidth - oldLength;
if (count <= 0)
return this;
String result = FastAllocateString(totalWidth);
unsafe
{
fixed (char* dst = &result._firstChar)
{
fixed (char* src = &_firstChar)
{
wstrcpy(dst, src, oldLength);
}
for (int i = 0; i < count; i++)
dst[oldLength + i] = paddingChar;
}
}
return result;
}
public String Remove(int startIndex, int count)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount);
int oldLength = this.Length;
if (count > oldLength - startIndex)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_IndexCount);
if (count == 0)
return this;
int newLength = oldLength - count;
if (newLength == 0)
return string.Empty;
String result = FastAllocateString(newLength);
unsafe
{
fixed (char* src = &_firstChar)
{
fixed (char* dst = &result._firstChar)
{
wstrcpy(dst, src, startIndex);
wstrcpy(dst + startIndex, src + startIndex + count, newLength - startIndex);
}
}
}
return result;
}
// a remove that just takes a startindex.
public string Remove(int startIndex)
{
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException("startIndex",
SR.ArgumentOutOfRange_StartIndex);
}
if (startIndex >= Length)
{
throw new ArgumentOutOfRangeException("startIndex",
SR.ArgumentOutOfRange_StartIndexLessThanLength);
}
return Substring(0, startIndex);
}
// Replaces all instances of oldChar with newChar.
//
public String Replace(char oldChar, char newChar)
{
if (oldChar == newChar)
return this;
unsafe
{
int remainingLength = Length;
fixed (char* pChars = &_firstChar)
{
char* pSrc = pChars;
while (remainingLength > 0)
{
if (*pSrc == oldChar)
{
break;
}
remainingLength--;
pSrc++;
}
}
if (remainingLength == 0)
return this;
String result = FastAllocateString(Length);
fixed (char* pChars = &_firstChar)
{
fixed (char* pResult = &result._firstChar)
{
int copyLength = Length - remainingLength;
//Copy the characters already proven not to match.
if (copyLength > 0)
{
wstrcpy(pResult, pChars, copyLength);
}
//Copy the remaining characters, doing the replacement as we go.
char* pSrc = pChars + copyLength;
char* pDst = pResult + copyLength;
do
{
char currentChar = *pSrc;
if (currentChar == oldChar)
currentChar = newChar;
*pDst = currentChar;
remainingLength--;
pSrc++;
pDst++;
} while (remainingLength > 0);
}
}
return result;
}
}
public String Replace(String oldValue, String newValue)
{
unsafe
{
if (oldValue == null)
throw new ArgumentNullException("oldValue");
if (oldValue.Length == 0)
throw new ArgumentException(SR.Format(SR.Argument_StringZeroLength, "oldValue"));
// Api behavior: if newValue is null, instances of oldValue are to be removed.
if (newValue == null)
newValue = String.Empty;
int numOccurrences = 0;
int[] replacementIndices = new int[this.Length];
fixed (char* pThis = &_firstChar)
{
fixed (char* pOldValue = &oldValue._firstChar)
{
int idx = 0;
int lastPossibleMatchIdx = this.Length - oldValue.Length;
while (idx <= lastPossibleMatchIdx)
{
int probeIdx = idx;
int oldValueIdx = 0;
bool foundMismatch = false;
while (oldValueIdx < oldValue.Length)
{
Debug.Assert(probeIdx >= 0 && probeIdx < this.Length);
Debug.Assert(oldValueIdx >= 0 && oldValueIdx < oldValue.Length);
if (pThis[probeIdx] != pOldValue[oldValueIdx])
{
foundMismatch = true;
break;
}
probeIdx++;
oldValueIdx++;
}
if (!foundMismatch)
{
// Found a match for the string. Record the location of the match and skip over the "oldValue."
replacementIndices[numOccurrences++] = idx;
Debug.Assert(probeIdx == idx + oldValue.Length);
idx = probeIdx;
}
else
{
idx++;
}
}
}
}
if (numOccurrences == 0)
return this;
int dstLength = checked(this.Length + (newValue.Length - oldValue.Length) * numOccurrences);
String dst = FastAllocateString(dstLength);
fixed (char* pThis = &_firstChar)
{
fixed (char* pDst = &dst._firstChar)
{
fixed (char* pNewValue = &newValue._firstChar)
{
int dstIdx = 0;
int thisIdx = 0;
for (int r = 0; r < numOccurrences; r++)
{
int replacementIdx = replacementIndices[r];
// Copy over the non-matching portion of the original that precedes this occurrence of oldValue.
int count = replacementIdx - thisIdx;
Debug.Assert(count >= 0);
Debug.Assert(thisIdx >= 0 && thisIdx <= this.Length - count);
Debug.Assert(dstIdx >= 0 && dstIdx <= dst.Length - count);
if (count != 0)
{
wstrcpy(&(pDst[dstIdx]), &(pThis[thisIdx]), count);
dstIdx += count;
}
thisIdx = replacementIdx + oldValue.Length;
// Copy over newValue to replace the oldValue.
Debug.Assert(thisIdx >= 0 && thisIdx <= this.Length);
Debug.Assert(dstIdx >= 0 && dstIdx <= dst.Length - newValue.Length);
wstrcpy(&(pDst[dstIdx]), pNewValue, newValue.Length);
dstIdx += newValue.Length;
}
// Copy over the final non-matching portion at the end of the string.
int tailLength = this.Length - thisIdx;
Debug.Assert(tailLength >= 0);
Debug.Assert(thisIdx == this.Length - tailLength);
Debug.Assert(dstIdx == dst.Length - tailLength);
wstrcpy(&(pDst[dstIdx]), &(pThis[thisIdx]), tailLength);
}
}
}
return dst;
}
}
// Creates an array of strings by splitting this string at each
// occurrence of a separator. The separator is searched for, and if found,
// the substring preceding the occurrence is stored as the first element in
// the array of strings. We then continue in this manner by searching
// the substring that follows the occurrence. On the other hand, if the separator
// is not found, the array of strings will contain this instance as its only element.
// If the separator is null
// whitespace (i.e., Character.IsWhitespace) is used as the separator.
//
public String[] Split(params char[] separator)
{
return Split(separator, Int32.MaxValue, StringSplitOptions.None);
}
// Creates an array of strings by splitting this string at each
// occurrence of a separator. The separator is searched for, and if found,
// the substring preceding the occurrence is stored as the first element in
// the array of strings. We then continue in this manner by searching
// the substring that follows the occurrence. On the other hand, if the separator
// is not found, the array of strings will contain this instance as its only element.
// If the separator is the empty string (i.e., String.Empty), then
// whitespace (i.e., Character.IsWhitespace) is used as the separator.
// If there are more than count different strings, the last n-(count-1)
// elements are concatenated and added as the last String.
//
public string[] Split(char[] separator, int count)
{
return Split(separator, count, StringSplitOptions.None);
}
public String[] Split(char[] separator, StringSplitOptions options)
{
return Split(separator, Int32.MaxValue, options);
}
public String[] Split(char[] separator, int count, StringSplitOptions options)
{
if (count < 0)
throw new ArgumentOutOfRangeException("count",
SR.ArgumentOutOfRange_NegativeCount);
if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, options));
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
if ((count == 0) || (omitEmptyEntries && this.Length == 0))
{
return Array.Empty<String>();
}
if (count == 1)
{
return new String[] { this };
}
int[] sepList = new int[Length];
int numReplaces = MakeSeparatorList(separator, sepList);
// Handle the special case of no replaces.
if (0 == numReplaces)
{
return new String[] { this };
}
if (omitEmptyEntries)
{
return SplitOmitEmptyEntries(sepList, null, numReplaces, count);
}
else
{
return SplitKeepEmptyEntries(sepList, null, numReplaces, count);
}
}
public String[] Split(String[] separator, StringSplitOptions options)
{
return Split(separator, Int32.MaxValue, options);
}
public String[] Split(String[] separator, Int32 count, StringSplitOptions options)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException("count",
SR.ArgumentOutOfRange_NegativeCount);
}
if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options));
}
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
if (separator == null || separator.Length == 0)
{
return Split((char[])null, count, options);
}
if ((count == 0) || (omitEmptyEntries && this.Length == 0))
{
return Array.Empty<String>();
}
if (count == 1)
{
return new String[] { this };
}
int[] sepList = new int[Length];
int[] lengthList = new int[Length];
int numReplaces = MakeSeparatorList(separator, sepList, lengthList);
//Handle the special case of no replaces.
if (0 == numReplaces)
{
return new String[] { this };
}
if (omitEmptyEntries)
{
return SplitOmitEmptyEntries(sepList, lengthList, numReplaces, count);
}
else
{
return SplitKeepEmptyEntries(sepList, lengthList, numReplaces, count);
}
}
// Note a special case in this function:
// If there is no separator in the string, a string array which only contains
// the original string will be returned regardless of the count.
//
private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 numReplaces, int count)
{
int currIndex = 0;
int arrIndex = 0;
count--;
int numActualReplaces = (numReplaces < count) ? numReplaces : count;
//Allocate space for the new array.
//+1 for the string from the end of the last replace to the end of the String.
String[] splitStrings = new String[numActualReplaces + 1];
for (int i = 0; i < numActualReplaces && currIndex < Length; i++)
{
splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex);
currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
}
//Handle the last string at the end of the array if there is one.
if (currIndex < Length && numActualReplaces >= 0)
{
splitStrings[arrIndex] = Substring(currIndex);
}
else if (arrIndex == numActualReplaces)
{
//We had a separator character at the end of a string. Rather than just allowing
//a null character, we'll replace the last element in the array with an empty string.
splitStrings[arrIndex] = String.Empty;
}
return splitStrings;
}
// This function will not keep the Empty String
private String[] SplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 numReplaces, int count)
{
// Allocate array to hold items. This array may not be
// filled completely in this function, we will create a
// new array and copy string references to that new array.
int maxItems = (numReplaces < count) ? (numReplaces + 1) : count;
String[] splitStrings = new String[maxItems];
int currIndex = 0;
int arrIndex = 0;
for (int i = 0; i < numReplaces && currIndex < Length; i++)
{
if (sepList[i] - currIndex > 0)
{
splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex);
}
currIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
if (arrIndex == count - 1)
{
// If all the remaining entries at the end are empty, skip them
while (i < numReplaces - 1 && currIndex == sepList[++i])
{
currIndex += ((lengthList == null) ? 1 : lengthList[i]);
}
break;
}
}
//Handle the last string at the end of the array if there is one.
if (currIndex < Length)
{
splitStrings[arrIndex++] = Substring(currIndex);
}
String[] stringArray = splitStrings;
if (arrIndex != maxItems)
{
stringArray = new String[arrIndex];
for (int j = 0; j < arrIndex; j++)
{
stringArray[j] = splitStrings[j];
}
}
return stringArray;
}
//--------------------------------------------------------------------
// This function returns the number of the places within this instance where
// characters in Separator occur.
// Args: separator -- A string containing all of the split characters.
// sepList -- an array of ints for split char indicies.
//--------------------------------------------------------------------
private unsafe int MakeSeparatorList(char[] separator, int[] sepList)
{
int foundCount = 0;
if (separator == null || separator.Length == 0)
{
fixed (char* pwzChars = &_firstChar)
{
//If they passed null or an empty string, look for whitespace.
for (int i = 0; i < Length && foundCount < sepList.Length; i++)
{
if (Char.IsWhiteSpace(pwzChars[i]))
{
sepList[foundCount++] = i;
}
}
}
}
else
{
int sepListCount = sepList.Length;
int sepCount = separator.Length;
//If they passed in a string of chars, actually look for those chars.
fixed (char* pwzChars = &_firstChar, pSepChars = separator)
{
for (int i = 0; i < Length && foundCount < sepListCount; i++)
{
char* pSep = pSepChars;
for (int j = 0; j < sepCount; j++, pSep++)
{
if (pwzChars[i] == *pSep)
{
sepList[foundCount++] = i;
break;
}
}
}
}
}
return foundCount;
}
//--------------------------------------------------------------------
// This function returns the number of the places within this instance where
// instances of separator strings occur.
// Args: separators -- An array containing all of the split strings.
// sepList -- an array of ints for split string indicies.
// lengthList -- an array of ints for split string lengths.
//--------------------------------------------------------------------
private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList)
{
int foundCount = 0;
int sepListCount = sepList.Length;
int sepCount = separators.Length;
fixed (char* pwzChars = &_firstChar)
{
for (int i = 0; i < Length && foundCount < sepListCount; i++)
{
for (int j = 0; j < separators.Length; j++)
{
String separator = separators[j];
if (String.IsNullOrEmpty(separator))
{
continue;
}
Int32 currentSepLength = separator.Length;
if (pwzChars[i] == separator[0] && currentSepLength <= Length - i)
{
if (currentSepLength == 1
|| String.CompareOrdinal(this, i, separator, 0, currentSepLength) == 0)
{
sepList[foundCount] = i;
lengthList[foundCount] = currentSepLength;
foundCount++;
i += currentSepLength - 1;
break;
}
}
}
}
}
return foundCount;
}
// Returns a substring of this string.
//
public String Substring(int startIndex)
{
return this.Substring(startIndex, Length - startIndex);
}
// Returns a substring of this string.
//
public String Substring(int startIndex, int length)
{
//Bounds Checking.
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex);
}
if (startIndex > Length)
{
throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndexLargerThanLength);
}
if (length < 0)
{
throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength);
}
if (startIndex > Length - length)
{
throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_IndexLength);
}
if (length == 0)
{
return String.Empty;
}
if (startIndex == 0 && length == this.Length)
{
return this;
}
return InternalSubString(startIndex, length);
}
private unsafe string InternalSubString(int startIndex, int length)
{
String result = FastAllocateString(length);
fixed (char* dest = &result._firstChar)
fixed (char* src = &_firstChar)
{
wstrcpy(dest, src + startIndex, length);
}
return result;
}
// Creates a copy of this string in lower case. The culture is set by culture.
public String ToLower()
{
return FormatProvider.ToLower(this);
}
// Creates a copy of this string in lower case based on invariant culture.
public String ToLowerInvariant()
{
return FormatProvider.ToLowerInvariant(this);
}
public String ToUpper()
{
return FormatProvider.ToUpper(this);
}
//Creates a copy of this string in upper case based on invariant culture.
public String ToUpperInvariant()
{
return FormatProvider.ToUpperInvariant(this);
}
// Removes a set of characters from the end of this string.
public String Trim(params char[] trimChars)
{
if (null == trimChars || trimChars.Length == 0)
{
return TrimHelper(TrimBoth);
}
return TrimHelper(trimChars, TrimBoth);
}
// Removes a set of characters from the beginning of this string.
public String TrimStart(params char[] trimChars)
{
if (null == trimChars || trimChars.Length == 0)
{
return TrimHelper(TrimHead);
}
return TrimHelper(trimChars, TrimHead);
}
// Removes a set of characters from the end of this string.
public String TrimEnd(params char[] trimChars)
{
if (null == trimChars || trimChars.Length == 0)
{
return TrimHelper(TrimTail);
}
return TrimHelper(trimChars, TrimTail);
}
// Trims the whitespace from both ends of the string. Whitespace is defined by
// Char.IsWhiteSpace.
//
public String Trim()
{
return TrimHelper(TrimBoth);
}
private String TrimHelper(int trimType)
{
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length - 1;
int start = 0;
//Trim specified characters.
if (trimType != TrimTail)
{
for (start = 0; start < this.Length; start++)
{
if (!Char.IsWhiteSpace(this[start])) break;
}
}
if (trimType != TrimHead)
{
for (end = Length - 1; end >= start; end--)
{
if (!Char.IsWhiteSpace(this[end])) break;
}
}
return CreateTrimmedString(start, end);
}
private String TrimHelper(char[] trimChars, int trimType)
{
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length - 1;
int start = 0;
//Trim specified characters.
if (trimType != TrimTail)
{
for (start = 0; start < this.Length; start++)
{
int i = 0;
char ch = this[start];
for (i = 0; i < trimChars.Length; i++)
{
if (trimChars[i] == ch) break;
}
if (i == trimChars.Length)
{ // the character is not white space
break;
}
}
}
if (trimType != TrimHead)
{
for (end = Length - 1; end >= start; end--)
{
int i = 0;
char ch = this[end];
for (i = 0; i < trimChars.Length; i++)
{
if (trimChars[i] == ch) break;
}
if (i == trimChars.Length)
{ // the character is not white space
break;
}
}
}
return CreateTrimmedString(start, end);
}
private String CreateTrimmedString(int start, int end)
{
int len = end - start + 1;
if (len == this.Length)
{
// Don't allocate a new string as the trimmed string has not changed.
return this;
}
else
{
if (len == 0)
{
return String.Empty;
}
return InternalSubString(start, len);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Internal.DeveloperExperience;
using Internal.Runtime.Augments;
namespace System
{
internal class PreallocatedOutOfMemoryException
{
public static OutOfMemoryException Instance { get; private set; }
// Eagerly preallocate instance of out of memory exception to avoid infinite recursion once we run out of memory
internal static void Initialize()
{
Instance = new OutOfMemoryException(message: null); // Cannot call the nullary constructor as that triggers non-trivial resource manager logic.
}
}
[ReflectionBlocked]
public class RuntimeExceptionHelpers
{
//------------------------------------------------------------------------------------------------------------
// @TODO: this function is related to throwing exceptions out of Rtm. If we did not have to throw
// out of Rtm, then we would note have to have the code below to get a classlib exception object given
// an exception id, or the special functions to back up the MDIL THROW_* instructions, or the allocation
// failure helper. If we could move to a world where we never throw out of Rtm, perhaps by moving parts
// of Rtm that do need to throw out to Bartok- or Binder-generated functions, then we could remove all of this.
//------------------------------------------------------------------------------------------------------------
// This is the classlib-provided "get exception" function that will be invoked whenever the runtime
// needs to throw an exception back to a method in a non-runtime module. The classlib is expected
// to convert every code in the ExceptionIDs enum to an exception object.
[RuntimeExport("GetRuntimeException")]
public static Exception GetRuntimeException(ExceptionIDs id)
{
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
// @TODO: this function should return pre-allocated exception objects, either frozen in the image
// or preallocated during DllMain(). In particular, this function will be called when out of memory,
// and failure to create an exception will result in infinite recursion and therefore a stack overflow.
switch (id)
{
case ExceptionIDs.OutOfMemory:
return PreallocatedOutOfMemoryException.Instance;
case ExceptionIDs.Arithmetic:
return new ArithmeticException();
case ExceptionIDs.ArrayTypeMismatch:
return new ArrayTypeMismatchException();
case ExceptionIDs.DivideByZero:
return new DivideByZeroException();
case ExceptionIDs.IndexOutOfRange:
return new IndexOutOfRangeException();
case ExceptionIDs.InvalidCast:
return new InvalidCastException();
case ExceptionIDs.Overflow:
return new OverflowException();
case ExceptionIDs.NullReference:
return new NullReferenceException();
case ExceptionIDs.AccessViolation:
FailFast("Access Violation: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The application will be terminated since this platform does not support throwing an AccessViolationException.");
return null;
case ExceptionIDs.DataMisaligned:
return new DataMisalignedException();
default:
FailFast("The runtime requires an exception for a case that this class library does not understand.");
return null;
}
}
catch
{
return null; // returning null will cause the runtime to FailFast via the class library.
}
}
public enum RhFailFastReason
{
Unknown = 0,
InternalError = 1, // "Runtime internal error"
UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope."
UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method."
ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object."
IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code."
PN_UnhandledException = 6, // ProjectN: "Unhandled exception: a managed exception was not handled before reaching unmanaged code"
PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition."
Max
}
private static string GetStringForFailFastReason(RhFailFastReason reason)
{
switch (reason)
{
case RhFailFastReason.InternalError:
return "Runtime internal error";
case RhFailFastReason.UnhandledException_ExceptionDispatchNotAllowed:
return "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope.";
case RhFailFastReason.UnhandledException_CallerDidNotHandle:
return "Unhandled exception: no handler found in calling method.";
case RhFailFastReason.ClassLibDidNotTranslateExceptionID:
return "Unable to translate failure into a classlib-specific exception object.";
case RhFailFastReason.IllegalNativeCallableEntry:
return "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code.";
case RhFailFastReason.PN_UnhandledException:
return "Unhandled exception: a managed exception was not handled before reaching unmanaged code.";
case RhFailFastReason.PN_UnhandledExceptionFromPInvoke:
return "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition.";
default:
return "Unknown reason.";
}
}
public static void FailFast(String message)
{
FailFast(message, null, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero);
}
public static unsafe void FailFast(string message, Exception exception)
{
FailFast(message, exception, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero);
}
// Used to report exceptions that *logically* go unhandled in the Fx code. For example, an
// exception that escapes from a ThreadPool workitem, or from a void-returning async method.
public static void ReportUnhandledException(Exception exception)
{
// ReportUnhandledError will also call this in APPX scenarios,
// but WinRT can failfast before we get another chance
// (in APPX scenarios, this one will get overwritten by the one with the CCW pointer)
GenerateExceptionInformationForDump(exception, IntPtr.Zero);
#if ENABLE_WINRT
// If possible report the exception to GEH, if not fail fast.
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks == null || !callbacks.ReportUnhandledError(exception))
FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception);
#else
FailFast(GetStringForFailFastReason(RhFailFastReason.PN_UnhandledException), exception);
#endif
}
// This is the classlib-provided fail-fast function that will be invoked whenever the runtime
// needs to cause the process to exit. It is the classlib's opprotunity to customize the
// termination behavior in whatever way necessary.
[RuntimeExport("FailFast")]
public static void RuntimeFailFast(RhFailFastReason reason, Exception exception, IntPtr pExAddress, IntPtr pExContext)
{
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
if (!SafeToPerformRichExceptionSupport)
return;
// Avoid complex processing and allocations if we are already in failfast or out of memory.
// We do not set InFailFast.Value here, because we want rich diagnostics in the FailFast
// call below and reentrancy is not possible for this method (all exceptions are ignored).
bool minimalFailFast = InFailFast.Value || (exception is OutOfMemoryException);
string failFastMessage = "";
if (!minimalFailFast)
{
if ((reason == RhFailFastReason.PN_UnhandledException) && (exception != null))
{
Debug.WriteLine("Unhandled Exception: " + exception.ToString());
}
failFastMessage = String.Format("Runtime-generated FailFast: ({0}): {1}{2}",
reason.ToString(), // Explicit call to ToString() to avoid MissingMetadataException inside String.Format()
GetStringForFailFastReason(reason),
exception != null ? " [exception object available]" : "");
}
FailFast(failFastMessage, exception, reason, pExAddress, pExContext);
}
catch
{
// Returning from this callback will cause the runtime to FailFast without involving the class
// library.
}
}
internal static void FailFast(string message, Exception exception, RhFailFastReason reason, IntPtr pExAddress, IntPtr pExContext)
{
// If this a recursive call to FailFast, avoid all unnecessary and complex activity the second time around to avoid the recursion
// that got us here the first time (Some judgement is required as to what activity is "unnecessary and complex".)
bool minimalFailFast = InFailFast.Value || (exception is OutOfMemoryException);
InFailFast.Value = true;
if (!minimalFailFast)
{
String output = (exception != null) ?
"Unhandled Exception: " + exception.ToString()
: message;
DeveloperExperience.Default.WriteLine(output);
GenerateExceptionInformationForDump(exception, IntPtr.Zero);
}
uint errorCode = 0x80004005; // E_FAIL
// To help enable testing to bucket the failures we choose one of the following as errorCode:
// * hashcode of EETypePtr if it is an unhandled managed exception
// * HRESULT, if available
// * RhFailFastReason, if it is one of the known reasons
if (exception != null)
{
if (reason == RhFailFastReason.PN_UnhandledException)
errorCode = (uint)(exception.EETypePtr.GetHashCode());
else if (exception.HResult != 0)
errorCode = (uint)exception.HResult;
}
else if (reason != RhFailFastReason.Unknown)
{
errorCode = (uint)reason + 0x1000; // Add something to avoid common low level exit codes
}
Interop.mincore.RaiseFailFastException(errorCode, pExAddress, pExContext);
}
// Use a nested class to avoid running the class constructor of the outer class when
// accessing this flag.
private static class InFailFast
{
// This boolean is used to stop runaway FailFast recursions. Though this is technically a concurrently set field, it only gets set during
// fatal process shutdowns and it's only purpose is a reasonable-case effort to make a bad situation a little less bad.
// Trying to use locks or other concurrent access apis would actually defeat the purpose of making FailFast as robust as possible.
public static bool Value;
}
#pragma warning disable 414 // field is assigned, but never used -- This is because C# doesn't realize that we
// copy the field into a buffer.
/// <summary>
/// This is the header that describes our 'error report' buffer to the minidump auxiliary provider.
/// Its format is know to that system-wide DLL, so do not change it. The remainder of the buffer is
/// opaque to the minidump auxiliary provider, so it'll have its own format that is more easily
/// changed.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct ERROR_REPORT_BUFFER_HEADER
{
private int _headerSignature;
private int _bufferByteCount;
public void WriteHeader(int cbBuffer)
{
_headerSignature = 0x31304244; // 'DB01'
_bufferByteCount = cbBuffer;
}
}
/// <summary>
/// This header describes the contents of the serialized error report to DAC, which can deserialize it
/// from a dump file or live debugging session. This format is easier to change than the
/// ERROR_REPORT_BUFFER_HEADER, but it is still well-known to DAC, so any changes must update the
/// version number and also have corresponding changes made to DAC.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct SERIALIZED_ERROR_REPORT_HEADER
{
private int _errorReportSignature; // This is the version of the 'container format'.
private int _exceptionSerializationVersion; // This is the version of the Exception format. It is
// separate from the 'container format' version since the
// implementation of the Exception serialization is owned by
// the Exception class.
private int _exceptionCount; // We just contain a logical array of exceptions.
private int _loadedModuleCount; // Number of loaded modules. present when signature >= ER02.
// {ExceptionCount} serialized Exceptions follow.
// {LoadedModuleCount} module handles follow. present when signature >= ER02.
public void WriteHeader(int nExceptions, int nLoadedModules)
{
_errorReportSignature = 0x32305245; // 'ER02'
_exceptionSerializationVersion = Exception.CurrentSerializationSignature;
_exceptionCount = nExceptions;
_loadedModuleCount = nLoadedModules;
}
}
/// <summary>
/// Holds metadata about an exception in flight. Class because ConditionalWeakTable only accepts reference types
/// </summary>
private class ExceptionData
{
public ExceptionData()
{
// Set this to a non-zero value so that logic mapping entries to threads
// doesn't think an uninitialized ExceptionData is on thread 0
ExceptionMetadata.ThreadId = 0xFFFFFFFF;
}
public struct ExceptionMetadataStruct
{
public UInt32 ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0.
public UInt32 InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception'
public UInt32 ThreadId { get; set; } // Managed thread ID the eception was thrown on
public Int32 NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them.
// The highest number is the most recent exception. -1 means the exception is not currently in flight
// (but it may still be an InnerException).
public IntPtr ExceptionCCWPtr { get; set; } // If the exception was thrown in an interop scenario, this contains the CCW pointer, otherwise, IntPtr.Zero
}
public ExceptionMetadataStruct ExceptionMetadata;
/// <summary>
/// Data created by Exception.SerializeForDump()
/// </summary>
public byte[] SerializedExceptionData { get; set; }
/// <summary>
/// Serializes the exception metadata and SerializedExceptionData
/// </summary>
public unsafe byte[] Serialize()
{
checked
{
byte[] serializedData = new byte[sizeof(ExceptionMetadataStruct) + SerializedExceptionData.Length];
fixed (byte* pSerializedData = &serializedData[0])
{
ExceptionMetadataStruct* pMetadata = (ExceptionMetadataStruct*)pSerializedData;
pMetadata->ExceptionId = ExceptionMetadata.ExceptionId;
pMetadata->InnerExceptionId = ExceptionMetadata.InnerExceptionId;
pMetadata->ThreadId = ExceptionMetadata.ThreadId;
pMetadata->NestingLevel = ExceptionMetadata.NestingLevel;
pMetadata->ExceptionCCWPtr = ExceptionMetadata.ExceptionCCWPtr;
PInvokeMarshal.CopyToNative(SerializedExceptionData, 0, (IntPtr)(pSerializedData + sizeof(ExceptionMetadataStruct)), SerializedExceptionData.Length);
}
return serializedData;
}
}
}
/// <summary>
/// Table of exceptions that were on stacks triggering GenerateExceptionInformationForDump
/// </summary>
private static readonly ConditionalWeakTable<Exception, ExceptionData> s_exceptionDataTable = new ConditionalWeakTable<Exception, ExceptionData>();
/// <summary>
/// Counter for exception ID assignment
/// </summary>
private static int s_currentExceptionId = 0;
/// <summary>
/// This method will call the runtime to gather the Exception objects from every exception dispatch in
/// progress on the current thread. It will then serialize them into a new buffer and pass that
/// buffer back to the runtime, which will publish it to a place where a global "minidump auxiliary
/// provider" will be able to save the buffer's contents into triage dumps.
///
/// Thread safety information: The guarantee of this method is that the buffer it produces will have
/// complete and correct information for all live exceptions on the current thread (as long as the same exception object
/// is not thrown simultaneously on multiple threads). It will do a best-effort attempt to serialize information about exceptions
/// already recorded on other threads, but that data can be lost or corrupted. The restrictions are:
/// 1. Only exceptions active or recorded on the current thread have their table data modified.
/// 2. After updating data in the table, we serialize a snapshot of the table (provided by ConditionalWeakTable.Values),
/// regardless of what other threads might do to the table before or after. However, because of #1, this thread's
/// exception data should stay stable
/// 3. There is a dependency on the fact that ConditionalWeakTable's members are all threadsafe and that .Values returns a snapshot
/// </summary>
public static void GenerateExceptionInformationForDump(Exception currentException, IntPtr exceptionCCWPtr)
{
LowLevelList<byte[]> serializedExceptions = new LowLevelList<byte[]>();
// If currentException is null, there's a state corrupting exception in flight and we can't serialize it
if (currentException != null)
{
SerializeExceptionsForDump(currentException, exceptionCCWPtr, serializedExceptions);
}
GenerateErrorReportForDump(serializedExceptions);
}
private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList<byte[]> serializedExceptions)
{
const UInt32 NoInnerExceptionValue = 0xFFFFFFFF;
// Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException)
// If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions.
const int MaxBufferSize = 20000;
int nExceptions;
RuntimeImports.RhGetExceptionsForCurrentThread(null, out nExceptions);
Exception[] curThreadExceptions = new Exception[nExceptions];
RuntimeImports.RhGetExceptionsForCurrentThread(curThreadExceptions, out nExceptions);
LowLevelList<Exception> exceptions = new LowLevelList<Exception>(curThreadExceptions);
LowLevelList<Exception> nonThrownInnerExceptions = new LowLevelList<Exception>();
uint currentThreadId = (uint)Environment.CurrentNativeThreadId;
// Reset nesting levels for exceptions on this thread that might not be currently in flight
foreach (KeyValuePair<Exception, ExceptionData> item in s_exceptionDataTable)
{
ExceptionData exceptionData = item.Value;
if (exceptionData.ExceptionMetadata.ThreadId == currentThreadId)
{
exceptionData.ExceptionMetadata.NestingLevel = -1;
}
}
// Find all inner exceptions, even if they're not currently being handled
for (int i = 0; i < exceptions.Count; i++)
{
if (exceptions[i].InnerException != null && !exceptions.Contains(exceptions[i].InnerException))
{
exceptions.Add(exceptions[i].InnerException);
nonThrownInnerExceptions.Add(exceptions[i].InnerException);
}
}
int currentNestingLevel = curThreadExceptions.Length - 1;
// Make sure we serialize currentException
if (!exceptions.Contains(currentException))
{
// When this happens, currentException is probably passed to this function through System.Environment.FailFast(), we
// would want to treat as if this exception is last thrown in the current thread.
exceptions.Insert(0, currentException);
currentNestingLevel++;
}
// Populate exception data for all exceptions interesting to this thread.
// Whether or not there was previously data for that object, it might have changed.
for (int i = 0; i < exceptions.Count; i++)
{
ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]);
exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId);
if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue)
{
exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId);
}
exceptionData.ExceptionMetadata.ThreadId = currentThreadId;
// Only include nesting information for exceptions that were thrown on this thread
if (!nonThrownInnerExceptions.Contains(exceptions[i]))
{
exceptionData.ExceptionMetadata.NestingLevel = currentNestingLevel;
currentNestingLevel--;
}
else
{
exceptionData.ExceptionMetadata.NestingLevel = -1;
}
// Only match the CCW pointer up to the current exception
if (Object.ReferenceEquals(exceptions[i], currentException))
{
exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr;
}
byte[] serializedEx = exceptions[i].SerializeForDump();
exceptionData.SerializedExceptionData = serializedEx;
}
// Populate inner exception ids now that we have all of them in the table
for (int i = 0; i < exceptions.Count; i++)
{
ExceptionData exceptionData;
if (!s_exceptionDataTable.TryGetValue(exceptions[i], out exceptionData))
{
// This shouldn't happen, but we can't meaningfully throw here
continue;
}
if (exceptions[i].InnerException != null)
{
ExceptionData innerExceptionData;
if (s_exceptionDataTable.TryGetValue(exceptions[i].InnerException, out innerExceptionData))
{
exceptionData.ExceptionMetadata.InnerExceptionId = innerExceptionData.ExceptionMetadata.ExceptionId;
}
}
else
{
exceptionData.ExceptionMetadata.InnerExceptionId = NoInnerExceptionValue;
}
}
int totalSerializedExceptionSize = 0;
// Make sure we include the current exception, regardless of buffer size
ExceptionData currentExceptionData = null;
if (s_exceptionDataTable.TryGetValue(currentException, out currentExceptionData))
{
byte[] serializedExceptionData = currentExceptionData.Serialize();
serializedExceptions.Add(serializedExceptionData);
totalSerializedExceptionSize = serializedExceptionData.Length;
}
checked
{
foreach (KeyValuePair<Exception, ExceptionData> item in s_exceptionDataTable)
{
ExceptionData exceptionData = item.Value;
// Already serialized currentException
if (currentExceptionData != null && exceptionData.ExceptionMetadata.ExceptionId == currentExceptionData.ExceptionMetadata.ExceptionId)
{
continue;
}
byte[] serializedExceptionData = exceptionData.Serialize();
if (totalSerializedExceptionSize + serializedExceptionData.Length >= MaxBufferSize)
{
break;
}
serializedExceptions.Add(serializedExceptionData);
totalSerializedExceptionSize += serializedExceptionData.Length;
}
}
}
private static unsafe void GenerateErrorReportForDump(LowLevelList<byte[]> serializedExceptions)
{
checked
{
int loadedModuleCount = (int)RuntimeImports.RhGetLoadedOSModules(null);
int cbModuleHandles = sizeof(System.IntPtr) * loadedModuleCount;
int cbFinalBuffer = sizeof(ERROR_REPORT_BUFFER_HEADER) + sizeof(SERIALIZED_ERROR_REPORT_HEADER) + cbModuleHandles;
for (int i = 0; i < serializedExceptions.Count; i++)
{
cbFinalBuffer += serializedExceptions[i].Length;
}
byte[] finalBuffer = new byte[cbFinalBuffer];
fixed (byte* pBuffer = &finalBuffer[0])
{
byte* pCursor = pBuffer;
int cbRemaining = cbFinalBuffer;
ERROR_REPORT_BUFFER_HEADER* pDacHeader = (ERROR_REPORT_BUFFER_HEADER*)pCursor;
pDacHeader->WriteHeader(cbFinalBuffer);
pCursor += sizeof(ERROR_REPORT_BUFFER_HEADER);
cbRemaining -= sizeof(ERROR_REPORT_BUFFER_HEADER);
SERIALIZED_ERROR_REPORT_HEADER* pPayloadHeader = (SERIALIZED_ERROR_REPORT_HEADER*)pCursor;
pPayloadHeader->WriteHeader(serializedExceptions.Count, loadedModuleCount);
pCursor += sizeof(SERIALIZED_ERROR_REPORT_HEADER);
cbRemaining -= sizeof(SERIALIZED_ERROR_REPORT_HEADER);
// copy the serialized exceptions to report buffer
for (int i = 0; i < serializedExceptions.Count; i++)
{
int cbChunk = serializedExceptions[i].Length;
PInvokeMarshal.CopyToNative(serializedExceptions[i], 0, (IntPtr)pCursor, cbChunk);
cbRemaining -= cbChunk;
pCursor += cbChunk;
}
// copy the module-handle array to report buffer
IntPtr[] loadedModuleHandles = new IntPtr[loadedModuleCount];
RuntimeImports.RhGetLoadedOSModules(loadedModuleHandles);
PInvokeMarshal.CopyToNative(loadedModuleHandles, 0, (IntPtr)pCursor, loadedModuleHandles.Length);
cbRemaining -= cbModuleHandles;
pCursor += cbModuleHandles;
Debug.Assert(cbRemaining == 0);
}
UpdateErrorReportBuffer(finalBuffer);
}
}
// This returns "true" once enough of the framework has been initialized to safely perform operations
// such as filling in the stack frame and generating diagnostic support.
public static bool SafeToPerformRichExceptionSupport
{
get
{
// Reflection needs to work as the exception code calls GetType() and GetType().ToString()
if (RuntimeAugments.CallbacksIfAvailable == null)
return false;
return true;
}
}
private static GCHandle s_ExceptionInfoBufferPinningHandle;
private static Lock s_ExceptionInfoBufferLock = new Lock();
private static unsafe void UpdateErrorReportBuffer(byte[] finalBuffer)
{
Debug.Assert(finalBuffer?.Length > 0);
using (LockHolder.Hold(s_ExceptionInfoBufferLock))
{
fixed (byte* pBuffer = &finalBuffer[0])
{
byte* pPrevBuffer = (byte*)RuntimeImports.RhSetErrorInfoBuffer(pBuffer);
Debug.Assert(s_ExceptionInfoBufferPinningHandle.IsAllocated == (pPrevBuffer != null));
if (pPrevBuffer != null)
{
byte[] currentExceptionInfoBuffer = (byte[])s_ExceptionInfoBufferPinningHandle.Target;
Debug.Assert(currentExceptionInfoBuffer?.Length > 0);
fixed (byte* pPrev = ¤tExceptionInfoBuffer[0])
Debug.Assert(pPrev == pPrevBuffer);
}
if (!s_ExceptionInfoBufferPinningHandle.IsAllocated)
{
// We allocate a pinning GC handle because we are logically giving the runtime 'unmanaged memory'.
s_ExceptionInfoBufferPinningHandle = GCHandle.Alloc(finalBuffer, GCHandleType.Pinned);
}
else
{
s_ExceptionInfoBufferPinningHandle.Target = finalBuffer;
}
}
}
}
}
}
| |
// $Id: mxGdiCanvas2D.cs,v 1.12 2013/05/23 10:29:42 gaudenz Exp $
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace com.mxgraph
{
/// <summary>
/// Used for exporting images.
/// <example>To render to an image from a given XML string, graph size and
/// and background color, the following code is used:
/// <code>
/// Image image = mxUtils.CreateImage(width, height, background);
/// Graphics g = Graphics.FromImage(image);
/// g.SmoothingMode = SmoothingMode.HighQuality;
/// mxSaxOutputHandler handler = new mxSaxOutputHandler(new mxGdiCanvas2D(g));
/// handler.Read(new XmlTextReader(new StringReader(xml)));
/// </code>
/// </example>
/// Text rendering is available for plain text only, with optional word wrapping.
/// </summary>
public class mxGdiCanvas2D : mxICanvas2D
{
/// <summary>
/// matchHtmlAlignment
/// </summary>
protected bool matchHtmlAlignment = true;
/// <summary>
/// htmlAsPlainText
/// </summary>
protected bool htmlAsPlainText = true;
/// <summary>
/// htmlAsPlainText
/// </summary>
protected bool wrapPlainText = true;
/// <summary>
/// Reference to the graphics instance for painting.
/// </summary>
protected Graphics graphics;
/// <summary>
/// Represents the current state of the canvas.
/// </summary>
protected CanvasState state = new CanvasState();
/// <summary>
/// Stack of states for save/restore.
/// </summary>
protected Stack<CanvasState> stack = new Stack<CanvasState>();
/// <summary>
/// Holds the current path.
/// </summary>
protected GraphicsPath currentPath;
/// <summary>
/// Holds the last point of a moveTo or lineTo operation to determine if the
/// current path is orthogonal.
/// </summary>
protected mxPoint lastPoint;
/// <summary>
/// FontCaching
/// </summary>
protected Font lastFont = null;
/// <summary>
/// FontCaching
/// </summary>
protected FontStyle lastFontStyle = 0;
/// <summary>
/// FontCaching
/// </summary>
protected float lastFontSize = 0;
/// <summary>
/// FontCaching
/// </summary>
protected String lastFontFamily = "";
/// <summary>
/// Constructs a new graphics export canvas.
/// </summary>
public mxGdiCanvas2D(Graphics g)
{
Graphics = g;
}
/// <summary>
/// Sets the graphics instance.
/// </summary>
Graphics Graphics
{
get { return graphics; }
set { graphics = value; }
}
/// <summary>
/// Saves the current canvas state.
/// </summary>
public void Save()
{
state.state = graphics.Save();
stack.Push(state);
state = (CanvasState) state.Clone();
}
/// <summary>
/// Restores the last canvas state.
/// </summary>
public void Restore()
{
state = stack.Pop();
graphics.Restore(state.state);
}
/// <summary>
/// Sets the given scale.
/// </summary>
/// <param name="value"></param>
public void Scale(double value)
{
// This implementation uses custom scale/translate and built-in rotation
state.scale = state.scale * value;
}
/// <summary>
/// Translates the canvas.
/// </summary>
/// <param name="dx"></param>
/// <param name="dy"></param>
public void Translate(double dx, double dy)
{
// This implementation uses custom scale/translate and built-in rotation
state.dx += dx;
state.dy += dy;
}
/// <summary>
/// Rotates the canvas.
/// </summary>
public void Rotate(double theta, bool flipH, bool flipV, double cx,
double cy)
{
cx += state.dx;
cy += state.dy;
cx *= state.scale;
cy *= state.scale;
// This implementation uses custom scale/translate and built-in rotation
// Rotation state is part of the AffineTransform in state.transform
if (flipH && flipV)
{
theta += 180;
}
else if (flipH ^ flipV)
{
double tx = (flipH) ? cx : 0;
int sx = (flipH) ? -1 : 1;
double ty = (flipV) ? cy : 0;
int sy = (flipV) ? -1 : 1;
graphics.TranslateTransform((float)-tx, (float)-ty, MatrixOrder.Append);
graphics.ScaleTransform(sx, sy, MatrixOrder.Append);
graphics.TranslateTransform((float)tx, (float)ty, MatrixOrder.Append);
}
graphics.TranslateTransform((float)-cx, (float)-cy, MatrixOrder.Append);
graphics.RotateTransform((float)theta, MatrixOrder.Append);
graphics.TranslateTransform((float)cx, (float)cy, MatrixOrder.Append);
}
/// <summary>
/// Sets the strokewidth.
/// </summary>
public double StrokeWidth
{
set
{
// Lazy and cached instantiation strategy for all stroke properties
if (value != state.strokeWidth)
{
state.strokeWidth = value;
}
}
}
/// <summary>
/// Caches color conversion as it is expensive.
/// </summary>
public string StrokeColor
{
set
{
// Lazy and cached instantiation strategy for all stroke properties
if (state.strokeColorValue == null || !state.strokeColorValue.Equals(value))
{
state.strokeColorValue = value;
state.strokeColor = null;
state.pen = null;
}
}
}
/// <summary>
/// Specifies if lines are dashed.
/// </summary>
public bool Dashed
{
set
{
state.dashed = value;
}
}
/// <summary>
/// Specifies if lines are dashed.
/// </summary>
public bool FixDash
{
set
{
state.fixDash = value;
}
}
/// <summary>
/// Sets the dashpattern.
/// </summary>
public string DashPattern
{
set
{
if (value != null && !state.dashPattern.Equals(value) && value.Length > 0)
{
String[] tokens = value.Split(' ');
float[] dashpattern = new float[tokens.Length];
for (int i = 0; i < tokens.Length; i++)
{
dashpattern[i] = (float) (float.Parse(tokens[i]));
}
state.dashPattern = dashpattern;
}
}
}
/// <summary>
/// Sets the linecap.
/// </summary>
public string LineCap
{
set
{
if (!state.lineCap.Equals(value))
{
state.lineCap = value;
}
}
}
/// <summary>
/// Sets the linejoin.
/// </summary>
public string LineJoin
{
set
{
if (!state.lineJoin.Equals(value))
{
state.lineJoin = value;
}
}
}
/// <summary>
/// Sets the miterlimit.
/// </summary>
public double MiterLimit
{
set
{
if (value != state.miterLimit)
{
state.miterLimit = value;
}
}
}
/// <summary>
/// Sets the fontsize.
/// </summary>
public double FontSize
{
set
{
if (value != state.fontSize)
{
state.fontSize = value;
}
}
}
/// <summary>
/// Sets the fontcolor.
/// </summary>
public string FontColor
{
set
{
if (state.fontColorValue == null || !state.fontColorValue.Equals(value))
{
state.fontColorValue = value;
state.fontBrush = null;
state.fontColor = null;
}
}
}
/// <summary>
/// Default value 0. See {@link mxConstants#STYLE_FONTSTYLE}.
/// </summary>
public string FontBackgroundColor
{
set
{
if (state.fontBackgroundColorValue == null || !state.fontBackgroundColorValue.Equals(value))
{
state.fontBackgroundColorValue = value;
state.fontBackgroundColor = null;
}
}
}
/// <summary>
/// Default value 0. See {@link mxConstants#STYLE_FONTSTYLE}.
/// </summary>
public string FontBorderColor
{
set
{
if (state.fontBorderColorValue == null || !state.fontBorderColorValue.Equals(value))
{
state.fontBorderColorValue = value;
state.fontBorderColor = null;
}
}
}
/// <summary>
/// Sets the font family.
/// </summary>
public string FontFamily
{
set
{
if (!state.fontFamily.Equals(value))
{
state.fontFamily = value;
}
}
}
/// <summary>
/// Sets the given fontstyle.
/// </summary>
public int FontStyle
{
set
{
if (value != state.fontStyle)
{
state.fontStyle = value;
}
}
}
/// <summary>
/// Sets the given alpha.
/// </summary>
public double Alpha
{
set
{
state.alpha = value;
}
}
/// <summary>
/// Sets the given alpha.
/// </summary>
public double StrokeAlpha
{
set
{
state.strokeAlpha = value;
}
}
/// <summary>
/// Sets the given alpha.
/// </summary>
public double FillAlpha
{
set
{
state.fillAlpha = value;
state.brush = new SolidBrush(ParseColor(state.fillColorValue, state.fillAlpha));
}
}
/// <summary>
/// Sets the given fillcolor.
/// </summary>
public string FillColor
{
set
{
state.fillColorValue = value;
state.brush = new SolidBrush(ParseColor(state.fillColorValue, state.fillAlpha));
}
}
/// <summary>
/// Default value {@link mxConstants#NONE}.
/// </summary>
public bool Shadow
{
set
{
state.shadow = value;
}
}
/// <summary>
/// Default value {@link mxConstants#NONE}.
/// </summary>
public string ShadowColor
{
set
{
if (state.shadowColorValue == null || !state.shadowColorValue.Equals(value))
{
state.shadowColorValue = value;
state.shadowColor = null;
}
}
}
/// <summary>
/// Default value 1. This method may add rendering overhead and should be
/// used with care.
/// </summary>
public double ShadowAlpha
{
set
{
state.shadowAlpha = value;
state.shadowColor = null;
}
}
/// <summary>
/// Prepares the canvas to draw a gradient.
/// </summary>
public void SetShadowOffset(double dx, double dy)
{
state.shadowOffsetX = dx;
state.shadowOffsetY = dy;
}
/// <summary>
/// Sets the given gradient.
/// </summary>
public void SetGradient(String color1, String color2, double x, double y,
double w, double h, String direction, double alpha1, double alpha2)
{
// LATER: Add lazy instantiation and check if paint already created
x = (state.dx + x) * state.scale;
y = (state.dy + y) * state.scale;
h *= state.scale;
w *= state.scale;
Color c1 = ParseColor(color1);
if (alpha1 != 1)
{
c1 = Color.FromArgb((int)(alpha1 * 255), c1.R, c1.G, c1.B);
}
Color c2 = ParseColor(color2);
if (alpha2 != 1)
{
c2 = Color.FromArgb((int)(alpha2 * 255), c2.R, c2.G, c2.B);
}
// FIXME: Needs to swap colors and use only horizontal and vertical
LinearGradientMode mode = LinearGradientMode.Vertical;
if (direction != null && direction.Length > 0
&& !direction.Equals(mxConstants.DIRECTION_SOUTH))
{
if (direction.Equals(mxConstants.DIRECTION_EAST))
{
mode = LinearGradientMode.Horizontal;
}
else if (direction.Equals(mxConstants.DIRECTION_NORTH))
{
Color tmp = c1;
c1 = c2;
c2 = tmp;
double tmp2 = alpha1;
alpha1 = alpha2;
alpha2 = tmp2;
}
else if (direction.Equals(mxConstants.DIRECTION_WEST))
{
mode = LinearGradientMode.Horizontal;
Color tmp = c1;
c1 = c2;
c2 = tmp;
double tmp2 = alpha1;
alpha1 = alpha2;
alpha2 = tmp2;
}
}
state.brush = new LinearGradientBrush(new RectangleF((float) x, (float) y,
(float) w, (float) h), c1, c2, mode);
}
/// <summary>
/// Helper method that uses {@link mxUtils#parseColor(String)}. Subclassers
/// can override this to implement caching for frequently used colors.
/// </summary>
protected Color ParseColor(string hex)
{
return ParseColor(hex, 1);
}
/// <summary>
/// Helper method that uses {@link mxUtils#parseColor(String)}. Subclassers
/// can override this to implement caching for frequently used colors.
/// </summary>
protected Color ParseColor(string hex, double alpha)
{
if (hex == null || alpha == 0 || hex.Equals(mxConstants.NONE))
{
// TODO: Return null
return Color.Transparent;
}
Color color = ColorTranslator.FromHtml(hex);
// Poor man's setAlpha
color = Color.FromArgb((int) (alpha * state.alpha * 255), color.R, color.G, color.B);
return color;
}
/// <summary>
/// Draws a rectangle.
/// </summary>
public void Rect(double x, double y, double w, double h)
{
currentPath = new GraphicsPath();
currentPath.AddRectangle(new RectangleF((float) ((state.dx + x) * state.scale),
(float) ((state.dy + y) * state.scale), (float) (w * state.scale),
(float) (h * state.scale)));
}
/// <summary>
/// Draws a rounded rectangle.
/// </summary>
public void Roundrect(double x, double y, double w, double h, double dx,
double dy)
{
Begin();
MoveTo(x + dx, y);
LineTo(x + w - dx, y);
QuadTo(x + w, y, x + w, y + dy);
LineTo(x + w, y + h - dy);
QuadTo(x + w, y + h, x + w - dx, y + h);
LineTo(x + dx, y + h);
QuadTo(x, y + h, x, y + h - dy);
LineTo(x, y + dy);
QuadTo(x, y, x + dx, y);
}
/// <summary>
/// Draws an ellipse.
/// </summary>
public void Ellipse(double x, double y, double w, double h)
{
currentPath = new GraphicsPath();
currentPath.AddEllipse((float) ((state.dx + x) * state.scale),
(float) ((state.dy + y) * state.scale), (float) (w * state.scale),
(float) (h * state.scale));
}
/// <summary>
/// Draws an image.
/// </summary>
public void Image(double x, double y, double w, double h, String src,
bool aspect, bool flipH, bool flipV)
{
if (src != null && w > 0 && h > 0)
{
Image image = LoadImage(src);
if (image != null)
{
GraphicsState previous = graphics.Save();
Rectangle bounds = GetImageBounds(image, x, y, w, h, aspect);
ConfigureImageGraphics(bounds.X, bounds.Y, bounds.Width,
bounds.Height, flipH, flipV);
DrawImage(image, bounds);
graphics.Restore(previous);
}
}
}
/// <summary>
/// Implements the call to the graphics API.
/// </summary>
protected void DrawImage(Image image, Rectangle bounds)
{
graphics.DrawImage(image, bounds);
}
/// <summary>
/// Loads the specified image.
/// </summary>
protected Image LoadImage(String src)
{
return mxUtils.LoadImage(src);
}
/// <summary>
/// Returns the bounds for the given image.
/// </summary>
protected Rectangle GetImageBounds(Image img, double x, double y,
double w, double h, bool aspect)
{
x = (state.dx + x) * state.scale;
y = (state.dy + y) * state.scale;
w *= state.scale;
h *= state.scale;
if (aspect)
{
Size size = GetImageSize(img);
double s = Math.Min(w / size.Width, h / size.Height);
int sw = (int)Math.Round(size.Width * s);
int sh = (int)Math.Round(size.Height * s);
x += (w - sw) / 2;
y += (h - sh) / 2;
w = sw;
h = sh;
}
else
{
w = Math.Round(w);
h = Math.Round(h);
}
return new Rectangle((int) x, (int) y, (int) w, (int) h);
}
/// <summary>
/// Returns the size for the given image.
/// </summary>
protected Size GetImageSize(Image image)
{
return new Size(image.Width, image.Height);
}
/// <summary>
/// Creates a graphic instance for rendering an image.
/// </summary>
protected void ConfigureImageGraphics(double x, double y,
double w, double h, bool flipH, bool flipV)
{
// FIXME: Wrong results
if (flipH || flipV)
{
float cx = (float)(x + w / 2);
float cy = (float)(y + h / 2);
if (flipV && flipH)
{
graphics.TranslateTransform(-cx, -cy, MatrixOrder.Append);
graphics.RotateTransform(180, MatrixOrder.Append);
graphics.TranslateTransform(cx, cy, MatrixOrder.Append);
}
else
{
double tx = (flipH) ? cx : 0;
int sx = (flipH) ? -1 : 1;
double ty = (flipV) ? cy : 0;
int sy = (flipV) ? -1 : 1;
graphics.TranslateTransform((float)-tx, (float)-ty, MatrixOrder.Append);
graphics.ScaleTransform(sx, sy, MatrixOrder.Append);
graphics.TranslateTransform((float)tx, (float)ty, MatrixOrder.Append);
}
}
}
/// <summary>
/// Draws the given text.
/// </summary>
public void Text(double x, double y, double w, double h, string str, string align, string valign,
bool wrap, string format, string overflow, bool clip, double rotation, string dir)
{
bool htmlFormat = format != null && format.Equals("html");
if (htmlFormat && !htmlAsPlainText)
{
return;
}
if (state.fontColor == null)
{
state.fontColor = ParseColor(state.fontColorValue);
state.fontBrush = new SolidBrush((Color) state.fontColor);
}
if (state.fontColor != null && state.fontColor != Color.Transparent)
{
// HTML format is currently not supported so all BR are
// replaced with linefeeds and rendered as plain text.
if (format != null && format.Equals("html"))
{
str = str.Replace("<br/>", "\n");
str = str.Replace("<br>", "\n");
}
x = state.dx + x;
y = state.dy + y;
// Uses graphics-based scaling for consistent word wrapping
graphics.ScaleTransform((float)state.scale, (float)state.scale, MatrixOrder.Append);
// Font-metrics needed below this line
GraphicsState previous = graphics.Save();
UpdateFont();
if (rotation != 0)
{
graphics.TranslateTransform((float)-(x * state.scale), (float)-(y * state.scale), MatrixOrder.Append);
graphics.RotateTransform((float) rotation, MatrixOrder.Append);
graphics.TranslateTransform((float)(x * state.scale), (float)(y * state.scale), MatrixOrder.Append);
}
// Workaround for inconsistent word wrapping
if (wrap)
{
w += 5;
}
// Workaround for y-position
y += 1;
PointF margin = GetMargin(align, valign);
StringFormat fmt = CreateStringFormat(align, valign, (htmlFormat || wrapPlainText) && wrap,
!matchHtmlAlignment && clip && w > 0 && h > 0);
SizeF size = graphics.MeasureString(str, lastFont, new SizeF((float)w, (float)h), fmt);
float cw = (w == 0 || (!wrap && !clip)) ? size.Width : (float)Math.Min(size.Width, w);
float ch = (h == 0 || (!wrap && !clip)) ? size.Height : (float)Math.Min(size.Height, h);
float cx = (float)(x + margin.X * cw);
float cy = (float)(y + margin.Y * ch);
RectangleF clipRect = new RectangleF(cx, cy, cw, ch);
if (state.fontBackgroundColorValue != null)
{
if (state.fontBackgroundColor == null)
{
state.fontBackgroundColor = ParseColor(state.fontBackgroundColorValue);
}
if (state.fontBackgroundColor != null && state.fontBackgroundColor != Color.Transparent)
{
RectangleF bg = new RectangleF(clipRect.X + 1, clipRect.Y - 1, clipRect.Width - 2, clipRect.Height - 1);
graphics.FillRectangle(new SolidBrush((Color)state.fontBackgroundColor), bg);
}
}
if (state.fontBorderColorValue != null)
{
if (state.fontBorderColor == null)
{
state.fontBorderColor = ParseColor(state.fontBorderColorValue);
}
if (state.fontBorderColor != null && state.fontBorderColor != Color.Transparent)
{
RectangleF bg = new RectangleF(clipRect.X + 1, clipRect.Y - 1, clipRect.Width - 2, clipRect.Height);
graphics.DrawRectangle(new Pen((Color)state.fontBorderColor), bg.X, bg.Y, bg.Width, bg.Height);
}
}
// Matches clipped vertical and horizontal alignment
if (matchHtmlAlignment)
{
if (clip && w > 0 && h > 0)
{
graphics.Clip = new Region(clipRect);
}
if (clip && size.Height > h && h > 0)
{
y -= margin.Y * (size.Height - h);
}
}
x += margin.X * w;
y += margin.Y * h;
// LATER: Match HTML horizontal alignment
RectangleF bounds = new RectangleF((float)x, (float)y, (float)w, (float)h);
graphics.DrawString(str, lastFont, state.fontBrush, bounds, fmt);
graphics.Restore(previous);
}
}
/**
*
*/
protected PointF GetMargin(String align, String valign)
{
float dx = 0;
float dy = 0;
if (align != null)
{
if (align.Equals(mxConstants.ALIGN_CENTER))
{
dx = -0.5f;
}
else if (align.Equals(mxConstants.ALIGN_RIGHT))
{
dx = -1;
}
}
if (valign != null)
{
if (valign.Equals(mxConstants.ALIGN_MIDDLE))
{
dy = -0.5f;
}
else if (valign.Equals(mxConstants.ALIGN_BOTTOM))
{
dy = -1;
}
}
return new PointF(dx, dy);
}
/// <summary>
/// Creates the specified string format.
/// </summary>
public static StringFormat CreateStringFormat(string align, string valign, bool wrap, bool clip)
{
StringFormat format = new StringFormat();
format.Trimming = StringTrimming.None;
if (!clip)
{
format.FormatFlags |= StringFormatFlags.NoClip;
}
// This is not required as the rectangle for the text will take this flag into account.
// However, we want to avoid any possible word-wrap unless explicitely specified.
if (!wrap)
{
format.FormatFlags |= StringFormatFlags.NoWrap;
}
if (align == null || align.Equals(mxConstants.ALIGN_LEFT))
{
format.Alignment = StringAlignment.Near;
}
else if (align.Equals(mxConstants.ALIGN_CENTER))
{
format.Alignment = StringAlignment.Center;
}
else if (align.Equals(mxConstants.ALIGN_RIGHT))
{
format.Alignment = StringAlignment.Far;
}
if (valign == null || valign.Equals(mxConstants.ALIGN_TOP))
{
format.LineAlignment = StringAlignment.Near;
}
else if (valign.Equals(mxConstants.ALIGN_MIDDLE))
{
format.LineAlignment = StringAlignment.Center;
}
else if (valign.Equals(mxConstants.ALIGN_BOTTOM))
{
format.LineAlignment = StringAlignment.Far;
}
return format;
}
/// <summary>
///
/// </summary>
public void Begin()
{
currentPath = new GraphicsPath();
lastPoint = null;
}
/// <summary>
///
/// </summary>
public void MoveTo(double x, double y)
{
if (currentPath != null)
{
// StartFigure avoids connection between last figure and new figure
currentPath.StartFigure();
lastPoint = new mxPoint((state.dx + x) * state.scale, (state.dy + y) * state.scale);
}
}
/// <summary>
///
/// </summary>
public void LineTo(double x, double y)
{
if (currentPath != null)
{
mxPoint nextPoint = new mxPoint((state.dx + x) * state.scale, (state.dy + y) * state.scale);
if (lastPoint != null)
{
currentPath.AddLine((float) lastPoint.X, (float) lastPoint.Y,
(float) nextPoint.X, (float) nextPoint.Y);
}
lastPoint = nextPoint;
}
}
/// <summary>
///
/// </summary>
public void QuadTo(double x1, double y1, double x2, double y2)
{
if (currentPath != null)
{
mxPoint nextPoint = new mxPoint((state.dx + x2) * state.scale,
(state.dy + y2) * state.scale);
if (lastPoint != null)
{
double cpx0 = lastPoint.X;
double cpy0 = lastPoint.Y;
double qpx1 = (state.dx + x1) * state.scale;
double qpy1 = (state.dy + y1) * state.scale;
double cpx1 = cpx0 + 2f/3f * (qpx1 - cpx0);
double cpy1 = cpy0 + 2f/3f * (qpy1 - cpy0);
double cpx2 = nextPoint.X + 2f/3f * (qpx1 - nextPoint.X);
double cpy2 = nextPoint.Y + 2f/3f * (qpy1 - nextPoint.Y);
currentPath.AddBezier((float)cpx0, (float)cpy0,
(float)cpx1, (float)cpy1, (float)cpx2, (float)cpy2,
(float)nextPoint.X, (float)nextPoint.Y);
}
lastPoint = nextPoint;
}
}
/// <summary>
///
/// </summary>
public void CurveTo(double x1, double y1, double x2, double y2, double x3,
double y3)
{
if (currentPath != null)
{
mxPoint nextPoint = new mxPoint((state.dx + x3) * state.scale, (state.dy + y3) * state.scale);
if (lastPoint != null)
{
currentPath.AddBezier((float)lastPoint.X, (float)lastPoint.Y,
(float)((state.dx + x1) * state.scale),
(float)((state.dy + y1) * state.scale),
(float)((state.dx + x2) * state.scale),
(float)((state.dy + y2) * state.scale),
(float)nextPoint.X, (float)nextPoint.Y);
}
lastPoint = nextPoint;
}
}
/// <summary>
/// Closes the current path.
/// </summary>
public void Close()
{
if (currentPath != null)
{
currentPath.CloseFigure();
}
}
/// <summary>
///
/// </summary>
public void Stroke()
{
PaintCurrentPath(false, true);
}
/// <summary>
///
/// </summary>
public void Fill()
{
PaintCurrentPath(true, false);
}
/// <summary>
///
/// </summary>
public void FillAndStroke()
{
PaintCurrentPath(true, true);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
protected void PaintCurrentPath(bool filled, bool stroked)
{
if (currentPath != null)
{
if (stroked)
{
if (state.strokeColor == null)
{
state.strokeColor = ParseColor(state.strokeColorValue, state.strokeAlpha);
}
}
if (state.shadow)
{
PaintShadow(filled, stroked);
}
if (filled && state.brush != null)
{
graphics.FillPath(state.brush, currentPath);
}
if (stroked && state.strokeColor != null && state.strokeColor != Color.Transparent)
{
UpdatePen();
graphics.DrawPath(state.pen, currentPath);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
protected void PaintShadow(bool filled, bool stroked)
{
if (state.shadowColor == null)
{
state.shadowColor = ParseColor(state.shadowColorValue);
if (state.shadowAlpha != 1)
{
Color c = (Color)state.shadowColor;
state.shadowColor = Color.FromArgb((int)(state.shadowAlpha * 255), c.R, c.G, c.B);
}
}
if (state.shadowColor != null && state.shadowColor != Color.Transparent)
{
double dx = state.shadowOffsetX * state.scale;
double dy = state.shadowOffsetY * state.scale;
float tx = (float) dx;
float ty = (float) dy;
graphics.TranslateTransform(tx, ty, MatrixOrder.Append);
// LATER: Cache shadowPen and shadowBrush
if (filled && state.brush != null)
{
Brush shadowBrush = new SolidBrush((Color)state.shadowColor);
graphics.FillPath(shadowBrush, currentPath);
}
if (stroked && state.strokeColor != null && state.strokeColor != Color.Transparent)
{
Pen shadowPen = new Pen((Color)state.shadowColor, (float)state.strokeWidth);
graphics.DrawPath(shadowPen, currentPath);
}
graphics.TranslateTransform(-tx, -ty, MatrixOrder.Append);
}
}
/// <summary>
///
/// </summary>
protected void UpdateFont()
{
float size = (float)(state.fontSize * mxConstants.FONT_SIZEFACTOR);
FontStyle style = ((state.fontStyle & mxConstants.FONT_BOLD) == mxConstants.FONT_BOLD) ?
System.Drawing.FontStyle.Bold : System.Drawing.FontStyle.Regular;
style |= ((state.fontStyle & mxConstants.FONT_ITALIC) == mxConstants.FONT_ITALIC) ?
System.Drawing.FontStyle.Italic : System.Drawing.FontStyle.Regular;
style |= ((state.fontStyle & mxConstants.FONT_UNDERLINE) == mxConstants.FONT_UNDERLINE) ?
System.Drawing.FontStyle.Underline : System.Drawing.FontStyle.Regular;
if (lastFont == null || !lastFontFamily.Equals(state.fontFamily) || size != lastFontSize || style != lastFontStyle)
{
lastFont = CreateFont(state.fontFamily, style, size);
lastFontFamily = state.fontFamily;
lastFontStyle = style;
lastFontSize = size;
}
}
/// <summary>
/// Hook for subclassers to implement font caching.
/// </summary>
protected Font CreateFont(String family, FontStyle style, float size)
{
return new Font(GetFontName(family), size, style);
}
/// <summary>
/// Returns a font name for the given font family.
/// </summary>
protected String GetFontName(String family)
{
if (family != null)
{
int comma = family.IndexOf(',');
if (comma >= 0)
{
family = family.Substring(0, comma);
}
}
return family;
}
/// <summary>
///
/// </summary>
protected void UpdatePen()
{
if (state.pen == null)
{
float sw = (float)(state.strokeWidth * state.scale);
state.pen = new Pen((Color)state.strokeColor, sw);
System.Drawing.Drawing2D.LineCap cap = System.Drawing.Drawing2D.LineCap.Flat;
if (state.lineCap.Equals("round"))
{
cap = System.Drawing.Drawing2D.LineCap.Round;
}
else if (state.lineCap.Equals("square"))
{
cap = System.Drawing.Drawing2D.LineCap.Square;
}
state.pen.StartCap = cap;
state.pen.EndCap = cap;
System.Drawing.Drawing2D.LineJoin join = System.Drawing.Drawing2D.LineJoin.Miter;
if (state.lineJoin.Equals("round"))
{
join = System.Drawing.Drawing2D.LineJoin.Round;
}
else if (state.lineJoin.Equals("bevel"))
{
join = System.Drawing.Drawing2D.LineJoin.Bevel;
}
state.pen.LineJoin = join;
state.pen.MiterLimit = (float) state.miterLimit;
if (state.dashed)
{
float[] dash = new float[state.dashPattern.Length];
for (int i = 0; i < dash.Length; i++)
{
dash[i] = (float)(state.dashPattern[i] * ((state.fixDash) ? 1 : state.strokeWidth));
}
state.pen.DashPattern = dash;
}
}
}
/// <summary>
///
/// </summary>
protected class CanvasState : ICloneable
{
/// <summary>
///
/// </summary>
internal double alpha = 1;
/// <summary>
///
/// </summary>
internal double fillAlpha = 1;
/// <summary>
///
/// </summary>
internal double strokeAlpha = 1;
/// <summary>
///
/// </summary>
internal double scale = 1;
/// <summary>
///
/// </summary>
internal double dx = 0;
/// <summary>
///
/// </summary>
internal double dy = 0;
/// <summary>
///
/// </summary>
internal double miterLimit = 10;
/// <summary>
///
/// </summary>
internal int fontStyle = 0;
/// <summary>
///
/// </summary>
internal double fontSize = mxConstants.DEFAULT_FONTSIZE;
/// <summary>
///
/// </summary>
internal string fontFamily = mxConstants.DEFAULT_FONTFAMILIES;
/// <summary>
///
/// </summary>
internal string fontColorValue = "#000000";
/// <summary>
///
/// </summary>
internal Color? fontColor;
/// <summary>
///
/// </summary>
internal Brush fontBrush = new SolidBrush(Color.Black);
/// <summary>
///
/// </summary>
internal string fontBackgroundColorValue = mxConstants.NONE;
/// <summary>
///
/// </summary>
internal Color? fontBackgroundColor;
/// <summary>
///
/// </summary>
internal string fontBorderColorValue = mxConstants.NONE;
/// <summary>
///
/// </summary>
internal Color? fontBorderColor;
/// <summary>
///
/// </summary>
internal string lineCap = "flat";
/// <summary>
///
/// </summary>
internal string lineJoin = "miter";
/// <summary>
///
/// </summary>
internal double strokeWidth = 1;
/// <summary>
///
/// </summary>
internal string strokeColorValue = mxConstants.NONE;
/// <summary>
///
/// </summary>
internal Color? strokeColor;
/// <summary>
///
/// </summary>
internal string fillColorValue = mxConstants.NONE;
/// <summary>
///
/// </summary>
internal Brush brush;
/// <summary>
///
/// </summary>
internal Pen pen;
/// <summary>
///
/// </summary>
internal bool dashed = false;
/// <summary>
///
/// </summary>
internal bool fixDash = false;
/// <summary>
///
/// </summary>
internal float[] dashPattern = { 3, 3 };
/// <summary>
///
/// </summary>
internal bool shadow = false;
/// <summary>
///
/// </summary>
internal string shadowColorValue = mxConstants.NONE;
/// <summary>
///
/// </summary>
internal Color? shadowColor;
/// <summary>
///
/// </summary>
internal double shadowAlpha = 1;
/// <summary>
///
/// </summary>
internal double shadowOffsetX = mxConstants.SHADOW_OFFSETX;
/// <summary>
///
/// </summary>
internal double shadowOffsetY = mxConstants.SHADOW_OFFSETY;
/// <summary>
///
/// </summary>
internal GraphicsState state;
/// <summary>
///
/// </summary>
public Object Clone()
{
return MemberwiseClone();
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
[Export(typeof(ExternalErrorDiagnosticUpdateSource))]
internal class ExternalErrorDiagnosticUpdateSource : IDiagnosticUpdateSource
{
private readonly Workspace _workspace;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly IGlobalOperationNotificationService _notificationService;
private readonly SimpleTaskQueue _taskQueue;
private readonly IAsynchronousOperationListener _listener;
private readonly object _gate;
private InprogressState _stateDoNotAccessDirectly = null;
private ImmutableArray<DiagnosticData> _lastBuiltResult = ImmutableArray<DiagnosticData>.Empty;
[ImportingConstructor]
public ExternalErrorDiagnosticUpdateSource(
VisualStudioWorkspaceImpl workspace,
IDiagnosticAnalyzerService diagnosticService,
IDiagnosticUpdateSourceRegistrationService registrationService,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) :
this(workspace, diagnosticService, registrationService, new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.ErrorList))
{
Contract.Requires(!KnownUIContexts.SolutionBuildingContext.IsActive);
KnownUIContexts.SolutionBuildingContext.UIContextChanged += OnSolutionBuild;
}
/// <summary>
/// internal for testing
/// </summary>
internal ExternalErrorDiagnosticUpdateSource(
Workspace workspace,
IDiagnosticAnalyzerService diagnosticService,
IDiagnosticUpdateSourceRegistrationService registrationService,
IAsynchronousOperationListener listener)
{
// use queue to serialize work. no lock needed
_taskQueue = new SimpleTaskQueue(TaskScheduler.Default);
_listener = listener;
_workspace = workspace;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
_diagnosticService = diagnosticService;
_notificationService = _workspace.Services.GetService<IGlobalOperationNotificationService>();
_gate = new object();
registrationService.Register(this);
}
public event EventHandler<bool> BuildStarted;
public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated;
public bool IsInProgress => BuildInprogressState != null;
public ImmutableArray<DiagnosticData> GetBuildErrors()
{
return _lastBuiltResult;
}
public bool SupportedDiagnosticId(ProjectId projectId, string id)
{
return BuildInprogressState?.SupportedDiagnosticId(projectId, id) ?? false;
}
public void ClearErrors(ProjectId projectId)
{
// capture state if it exists
var state = BuildInprogressState;
var asyncToken = _listener.BeginAsyncOperation("ClearErrors");
_taskQueue.ScheduleTask(() =>
{
// record the project as built only if we are in build.
// otherwise (such as closing solution or removing project), no need to record it
state?.Built(projectId);
ClearProjectErrors(state?.Solution ?? _workspace.CurrentSolution, projectId);
}).CompletesAsyncOperation(asyncToken);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
case WorkspaceChangeKind.SolutionReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnSolutionChanged");
_taskQueue.ScheduleTask(() => e.OldSolution.ProjectIds.Do(p => ClearProjectErrors(e.OldSolution, p))).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.ProjectRemoved:
case WorkspaceChangeKind.ProjectReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectChanged");
_taskQueue.ScheduleTask(() => ClearProjectErrors(e.OldSolution, e.ProjectId)).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.DocumentReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentRemoved");
_taskQueue.ScheduleTask(() => ClearDocumentErrors(e.OldSolution, e.ProjectId, e.DocumentId)).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AdditionalDocumentChanged:
break;
default:
Contract.Fail("Unknown workspace events");
break;
}
}
internal void OnSolutionBuild(object sender, UIContextChangedEventArgs e)
{
if (e.Activated)
{
// build just started, create the state and fire build in progress event.
var state = GetOrCreateInprogressState();
return;
}
// building is done. reset the state
// and get local copy of inprogress state
var inprogressState = ClearInprogressState();
// enqueue build/live sync in the queue.
var asyncToken = _listener.BeginAsyncOperation("OnSolutionBuild");
_taskQueue.ScheduleTask(async () =>
{
// nothing to do
if (inprogressState == null)
{
return;
}
_lastBuiltResult = inprogressState.GetBuildDiagnostics();
// we are about to update live analyzer data using one from build.
// pause live analyzer
using (var operation = _notificationService.Start("BuildDone"))
{
Func<DiagnosticData, bool> liveDiagnosticChecker = d =>
{
// REVIEW: we probably need a better design on de-duplicating live and build errors. or don't de-dup at all.
// for now, we are special casing compiler error case.
var project = inprogressState.Solution.GetProject(d.ProjectId);
if (project == null)
{
// project doesn't exist
return false;
}
// REVIEW: current design is that we special case compiler analyzer case and we accept only document level
// diagnostic as live. otherwise, we let them be build errors. we changed compiler analyzer accordingly as well
// so that it doesn't report project level diagnostic as live errors.
if (_diagnosticService.IsCompilerDiagnostic(project.Language, d) && d.DocumentId == null)
{
// compiler error but project level error
return false;
}
if (inprogressState.SupportedDiagnosticId(d.ProjectId, d.Id))
{
return true;
}
return false;
};
var diagnosticService = _diagnosticService as DiagnosticAnalyzerService;
if (diagnosticService != null)
{
await CleanupAllLiveErrors(diagnosticService, inprogressState.GetProjectsWithoutErrors(inprogressState.Solution)).ConfigureAwait(false);
await SyncBuildErrorsAndReportAsync(diagnosticService, inprogressState.Solution, inprogressState.GetLiveDiagnosticsPerProject(liveDiagnosticChecker)).ConfigureAwait(false);
}
inprogressState.Done();
}
}).CompletesAsyncOperation(asyncToken);
}
private System.Threading.Tasks.Task CleanupAllLiveErrors(DiagnosticAnalyzerService diagnosticService, IEnumerable<ProjectId> projects)
{
var map = projects.ToImmutableDictionary(p => p, _ => ImmutableArray<DiagnosticData>.Empty);
return diagnosticService.SynchronizeWithBuildAsync(_workspace, map);
}
private async System.Threading.Tasks.Task SyncBuildErrorsAndReportAsync(
DiagnosticAnalyzerService diagnosticService, Solution solution, ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>> map)
{
// make those errors live errors
await diagnosticService.SynchronizeWithBuildAsync(_workspace, map).ConfigureAwait(false);
// raise events for ones left-out
var buildErrors = GetBuildErrors().Except(map.Values.SelectMany(v => v)).GroupBy(k => k.DocumentId);
foreach (var group in buildErrors)
{
if (group.Key == null)
{
foreach (var projectGroup in group.GroupBy(g => g.ProjectId))
{
Contract.ThrowIfNull(projectGroup.Key);
ReportBuildErrors(projectGroup.Key, solution, projectGroup.ToImmutableArray());
}
continue;
}
ReportBuildErrors(group.Key, solution, group.ToImmutableArray());
}
}
private void ReportBuildErrors<T>(T item, Solution solution, ImmutableArray<DiagnosticData> buildErrors)
{
var projectId = item as ProjectId;
if (projectId != null)
{
RaiseDiagnosticsCreated(projectId, solution, projectId, null, buildErrors);
return;
}
// must be not null
var documentId = item as DocumentId;
RaiseDiagnosticsCreated(documentId, solution, documentId.ProjectId, documentId, buildErrors);
}
private void ClearProjectErrors(Solution solution, ProjectId projectId)
{
// remove all project errors
RaiseDiagnosticsRemoved(projectId, solution, projectId, documentId: null);
var project = solution.GetProject(projectId);
if (project == null)
{
return;
}
// remove all document errors
foreach (var documentId in project.DocumentIds)
{
ClearDocumentErrors(solution, projectId, documentId);
}
}
private void ClearDocumentErrors(Solution solution, ProjectId projectId, DocumentId documentId)
{
RaiseDiagnosticsRemoved(documentId, solution, projectId, documentId);
}
public void AddNewErrors(ProjectId projectId, DiagnosticData diagnostic)
{
// capture state that will be processed in background thread.
var state = GetOrCreateInprogressState();
var asyncToken = _listener.BeginAsyncOperation("Project New Errors");
_taskQueue.ScheduleTask(() =>
{
state.AddError(projectId, diagnostic);
}).CompletesAsyncOperation(asyncToken);
}
public void AddNewErrors(DocumentId documentId, DiagnosticData diagnostic)
{
// capture state that will be processed in background thread.
var state = GetOrCreateInprogressState();
var asyncToken = _listener.BeginAsyncOperation("Document New Errors");
_taskQueue.ScheduleTask(() =>
{
state.AddError(documentId, diagnostic);
}).CompletesAsyncOperation(asyncToken);
}
public void AddNewErrors(
ProjectId projectId, HashSet<DiagnosticData> projectErrors, Dictionary<DocumentId, HashSet<DiagnosticData>> documentErrorMap)
{
// capture state that will be processed in background thread
var state = GetOrCreateInprogressState();
var asyncToken = _listener.BeginAsyncOperation("Project New Errors");
_taskQueue.ScheduleTask(() =>
{
foreach (var kv in documentErrorMap)
{
state.AddErrors(kv.Key, kv.Value);
}
state.AddErrors(projectId, projectErrors);
}).CompletesAsyncOperation(asyncToken);
}
private InprogressState BuildInprogressState
{
get
{
lock (_gate)
{
return _stateDoNotAccessDirectly;
}
}
}
private InprogressState ClearInprogressState()
{
lock (_gate)
{
var state = _stateDoNotAccessDirectly;
_stateDoNotAccessDirectly = null;
return state;
}
}
private InprogressState GetOrCreateInprogressState()
{
lock (_gate)
{
if (_stateDoNotAccessDirectly == null)
{
// here, we take current snapshot of solution when the state is first created. and through out this code, we use this snapshot.
// since we have no idea what actual snapshot of solution the out of proc build has picked up, it doesn't remove the race we can have
// between build and diagnostic service, but this at least make us to consistent inside of our code.
_stateDoNotAccessDirectly = new InprogressState(this, _workspace.CurrentSolution);
}
return _stateDoNotAccessDirectly;
}
}
private void RaiseDiagnosticsCreated(object id, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> items)
{
DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated(
CreateArgumentKey(id), _workspace, solution, projectId, documentId, items));
}
private void RaiseDiagnosticsRemoved(object id, Solution solution, ProjectId projectId, DocumentId documentId)
{
DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved(
CreateArgumentKey(id), _workspace, solution, projectId, documentId));
}
private static ArgumentKey CreateArgumentKey(object id) => new ArgumentKey(id);
private void RaiseBuildStarted(bool started)
{
BuildStarted?.Invoke(this, started);
}
#region not supported
public bool SupportGetDiagnostics { get { return false; } }
public ImmutableArray<DiagnosticData> GetDiagnostics(
Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
return ImmutableArray<DiagnosticData>.Empty;
}
#endregion
private class InprogressState
{
private readonly ExternalErrorDiagnosticUpdateSource _owner;
private readonly Solution _solution;
private readonly HashSet<ProjectId> _builtProjects = new HashSet<ProjectId>();
private readonly Dictionary<ProjectId, HashSet<DiagnosticData>> _projectMap = new Dictionary<ProjectId, HashSet<DiagnosticData>>();
private readonly Dictionary<DocumentId, HashSet<DiagnosticData>> _documentMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>();
private readonly Dictionary<ProjectId, HashSet<string>> _diagnosticIdMap = new Dictionary<ProjectId, HashSet<string>>();
public InprogressState(ExternalErrorDiagnosticUpdateSource owner, Solution solution)
{
_owner = owner;
_solution = solution;
// let people know build has started
_owner.RaiseBuildStarted(started: true);
}
public Solution Solution => _solution;
public void Done()
{
_owner.RaiseBuildStarted(started: false);
}
public bool SupportedDiagnosticId(ProjectId projectId, string id)
{
if (_diagnosticIdMap.TryGetValue(projectId, out var ids))
{
return ids.Contains(id);
}
// set ids set
var map = new HashSet<string>();
_diagnosticIdMap.Add(projectId, map);
var project = _solution.GetProject(projectId);
if (project == null)
{
// projectId no longer exist, return false;
return false;
}
var descriptorMap = _owner._diagnosticService.GetDiagnosticDescriptors(project);
map.UnionWith(descriptorMap.Values.SelectMany(v => v.Select(d => d.Id)));
return map.Contains(id);
}
public ImmutableArray<DiagnosticData> GetBuildDiagnostics()
{
return ImmutableArray.CreateRange(_projectMap.Values.SelectMany(d => d).Concat(_documentMap.Values.SelectMany(d => d)));
}
public void Built(ProjectId projectId)
{
_builtProjects.Add(projectId);
}
public IEnumerable<ProjectId> GetProjectsBuilt(Solution solution)
{
return solution.ProjectIds.Where(p => _builtProjects.Contains(p));
}
public IEnumerable<ProjectId> GetProjectsWithErrors(Solution solution)
{
return GetProjectIds().Where(p => solution.GetProject(p) != null);
}
public IEnumerable<ProjectId> GetProjectsWithoutErrors(Solution solution)
{
return GetProjectsBuilt(solution).Except(GetProjectsWithErrors(solution));
}
public ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>> GetLiveDiagnosticsPerProject(Func<DiagnosticData, bool> liveDiagnosticChecker)
{
var builder = ImmutableDictionary.CreateBuilder<ProjectId, ImmutableArray<DiagnosticData>>();
foreach (var projectId in GetProjectIds())
{
var diagnostics = ImmutableArray.CreateRange(
_projectMap.Where(kv => kv.Key == projectId).SelectMany(kv => kv.Value).Concat(
_documentMap.Where(kv => kv.Key.ProjectId == projectId).SelectMany(kv => kv.Value)).Where(liveDiagnosticChecker));
builder.Add(projectId, diagnostics);
}
return builder.ToImmutable();
}
public void AddErrors(DocumentId key, HashSet<DiagnosticData> diagnostics)
{
AddErrors(_documentMap, key, diagnostics);
}
public void AddErrors(ProjectId key, HashSet<DiagnosticData> diagnostics)
{
AddErrors(_projectMap, key, diagnostics);
}
public void AddError(DocumentId key, DiagnosticData diagnostic)
{
AddError(_documentMap, key, diagnostic);
}
public void AddError(ProjectId key, DiagnosticData diagnostic)
{
AddError(_projectMap, key, diagnostic);
}
private void AddErrors<T>(Dictionary<T, HashSet<DiagnosticData>> map, T key, HashSet<DiagnosticData> diagnostics)
{
var errors = GetErrorSet(map, key);
errors.UnionWith(diagnostics);
}
private void AddError<T>(Dictionary<T, HashSet<DiagnosticData>> map, T key, DiagnosticData diagnostic)
{
var errors = GetErrorSet(map, key);
errors.Add(diagnostic);
}
private IEnumerable<ProjectId> GetProjectIds()
{
return _documentMap.Keys.Select(k => k.ProjectId).Concat(_projectMap.Keys).Distinct();
}
private HashSet<DiagnosticData> GetErrorSet<T>(Dictionary<T, HashSet<DiagnosticData>> map, T key)
{
return map.GetOrAdd(key, _ => new HashSet<DiagnosticData>(DiagnosticDataComparer.Instance));
}
}
private class ArgumentKey : BuildToolId.Base<object>
{
public ArgumentKey(object key) : base(key)
{
}
public override string BuildTool
{
get { return PredefinedBuildTools.Build; }
}
public override bool Equals(object obj)
{
var other = obj as ArgumentKey;
if (other == null)
{
return false;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
private class DiagnosticDataComparer : IEqualityComparer<DiagnosticData>
{
public static readonly DiagnosticDataComparer Instance = new DiagnosticDataComparer();
public bool Equals(DiagnosticData item1, DiagnosticData item2)
{
// crash if any one of them is NULL
if ((IsNull(item1.DocumentId) ^ IsNull(item2.DocumentId)) ||
(IsNull(item1.ProjectId) ^ IsNull(item2.ProjectId)))
{
return false;
}
var lineColumn1 = GetOriginalOrMappedLineColumn(item1);
var lineColumn2 = GetOriginalOrMappedLineColumn(item2);
if (item1.DocumentId != null && item2.DocumentId != null)
{
return item1.Id == item2.Id &&
item1.Message == item2.Message &&
item1.ProjectId == item2.ProjectId &&
item1.DocumentId == item2.DocumentId &&
lineColumn1.Item1 == lineColumn2.Item1 &&
lineColumn1.Item2 == lineColumn2.Item2 &&
item1.Severity == item2.Severity;
}
return item1.Id == item2.Id &&
item1.Message == item2.Message &&
item1.ProjectId == item2.ProjectId &&
item1.DataLocation?.OriginalFilePath == item2.DataLocation?.OriginalFilePath &&
lineColumn1.Item1 == lineColumn2.Item1 &&
lineColumn1.Item2 == lineColumn2.Item2 &&
item1.Severity == item2.Severity;
}
public int GetHashCode(DiagnosticData obj)
{
var lineColumn = GetOriginalOrMappedLineColumn(obj);
if (obj.DocumentId != null)
{
return Hash.Combine(obj.Id,
Hash.Combine(obj.Message,
Hash.Combine(obj.ProjectId,
Hash.Combine(obj.DocumentId,
Hash.Combine(lineColumn.Item1,
Hash.Combine(lineColumn.Item2, (int)obj.Severity))))));
}
return Hash.Combine(obj.Id,
Hash.Combine(obj.Message,
Hash.Combine(obj.ProjectId,
Hash.Combine(obj.DataLocation?.OriginalFilePath?.GetHashCode() ?? 0,
Hash.Combine(lineColumn.Item1,
Hash.Combine(lineColumn.Item2, (int)obj.Severity))))));
}
private static ValueTuple<int, int> GetOriginalOrMappedLineColumn(DiagnosticData data)
{
var workspace = data.Workspace as VisualStudioWorkspaceImpl;
if (workspace == null)
{
return ValueTuple.Create(data.DataLocation?.MappedStartLine ?? 0, data.DataLocation?.MappedStartColumn ?? 0);
}
if (data.DocumentId == null)
{
return ValueTuple.Create(data.DataLocation?.MappedStartLine ?? 0, data.DataLocation?.MappedStartColumn ?? 0);
}
var containedDocument = workspace.GetHostDocument(data.DocumentId) as ContainedDocument;
if (containedDocument == null)
{
return ValueTuple.Create(data.DataLocation?.MappedStartLine ?? 0, data.DataLocation?.MappedStartColumn ?? 0);
}
return ValueTuple.Create(data.DataLocation?.OriginalStartLine ?? 0, data.DataLocation?.OriginalStartColumn ?? 0);
}
private bool IsNull<T>(T item) where T : class
{
return item == null;
}
}
}
}
| |
// ~/Controllers/EntityController.cs
using System;
using System.Linq;
using System.Web.Mvc;
using Project.Models;
namespace Project.Controllers
{
[ValidateInput(false)]
public class EntityController : Controller
{
//
// GET: INDEX
[HttpGet]
[Route("")]
public ActionResult Index()
{
using (var database = new EntityDbContext())
{
var entities = database.Entities.ToList();
return View(entities);
}
}
//
// GET: CREATE
[HttpGet]
[Route("create")]
public ActionResult Create()
{
return View();
}
//
// POST: CREATE
[HttpPost]
[Route("create")]
[ValidateAntiForgeryToken]
public ActionResult Create(Entity entity)
{
if (ModelState.IsValid)
{
using (var database = new EntityDbContext())
{
if (database.Entities.Any(e => e.Property == entity.Property))
{
return View();
}
database.Entities.Add(entity);
database.SaveChanges();
return RedirectToAction("Index");
}
}
return RedirectToAction("Index");
}
//
// GET: READ/5
[HttpGet]
[Route("read/{id}")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var database = new EntityDbContext())
{
var entity = database.Entities.Find(id);
// var entities = database.Entities.ToList();
// var entity = entities.FirstOrDefault(e => e.Id == id);
if (entity == null)
{
return HttpNotFound();
}
return View(entity);
}
}
//
// GET: EDIT/5
[HttpGet]
[Route("edit/{id}")]
public ActionResult Edit(int id)
{
using (var database = new EntityDbContext())
{
var entity = database.Entities.Find(id);
// var entities = database.Entities.ToList();
// var entity = entities.FirstOrDefault(e => e.Id == id);
if (entity == null)
{
return HttpNotFound();
}
return View(entity);
}
}
//
// POST: EDIT/5
[HttpPost]
[Route("edit/{id}")]
[ValidateAntiForgeryToken]
public ActionResult EditConfirm(int id, Entity entityViewModel)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (ModelState.IsValid)
{
using (var database = new EntityDbContext())
{
var entity = database.Entities.Find(id);
if (entity == null)
{
return HttpNotFound();
}
entity = entityViewModel;
database.SaveChanges();
return RedirectToAction("Index");
}
}
return View(entityViewModel);
}
//
// GET: DELETE/5
[HttpGet]
[Route("delete/{id}")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var database = new EntitybContext())
{
var entity = database.Entities.Find(id);
// var entities = database.Entities.ToList();
// var entity = entities.FirstOrDefault(e => e.Id == id);
if (entity == null)
{
return HttpNotFound();
}
return View(entity);
}
}
//
// POST: DELETE/5
[HttpPost]
[Route("delete/{id}")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirm(int? id, Entity entityViewModel)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var database = new EntityDbContext())
{
var entity = database.Entities.Find(id);
// var entities = database.Entities.ToList();
// var entity = entities.FirstOrDefault(e => e.Id == id);
if (entity == null)
{
return HttpNotFound();
}
database.Entities.Remove(entity);
database.SaveChanges();
return RedirectToAction("Index");
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.NohauLPC3180
{
using System;
using RT = Microsoft.Zelig.Runtime;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
public sealed class Storage : RT.Storage
{
const uint DRAMSize = 1 * 8 * 1024 * 1024;
const uint DRAMBase = 0x80000000 + DRAMSize;
const uint DRAMEnd = DRAMBase + DRAMSize;
const uint DRAMMask = ~(DRAMSize - 1);
const byte ErasedValueByte = (byte)0xFFu;
const ushort ErasedValue = (ushort)0xFFFFu;
const uint ErasedValuePair = 0xFFFFFFFFu;
//
// State
//
//
// Helper Methods
//
public override unsafe void InitializeStorage()
{
EraseSectors( new UIntPtr( DRAMBase ), new UIntPtr( DRAMEnd ) );
}
//--//
public override unsafe bool EraseSectors( UIntPtr addressStart ,
UIntPtr addressEnd )
{
if(ValidateAddress ( addressStart ) &&
ValidateAddressPlus1( addressEnd ) )
{
Memory.Fill( addressStart, addressEnd, ErasedValuePair );
return true;
}
return false;
}
public override unsafe bool WriteByte( UIntPtr address ,
byte val )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
*ptr = val;
return true;
}
return false;
}
public override unsafe bool WriteShort( UIntPtr address ,
ushort val )
{
if(IsOddAddress( address ))
{
return WriteByte( address, (byte) val ) &&
WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ;
}
else
{
if(ValidateAddress( address ))
{
ushort* wordAddress = (ushort*)address.ToPointer();
*wordAddress = val;
return true;
}
return false;
}
}
public override bool WriteWord( UIntPtr address ,
uint val )
{
if(IsOddAddress( address ))
{
return WriteByte ( address, (byte ) val ) &&
WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) &&
WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ;
}
else
{
return WriteShort( address, (ushort) val ) &&
WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ;
}
}
public override bool Write( UIntPtr address ,
byte[] buffer ,
uint offset ,
uint numBytes )
{
if(numBytes > 0)
{
if(IsOddAddress( address ))
{
if(WriteByte( address, buffer[offset] ) == false)
{
return false;
}
address = Microsoft.Zelig.AddressMath.Increment( address, 1 );
offset += 1;
numBytes -= 1;
}
while(numBytes >= 2)
{
uint val;
val = (uint)buffer[ offset++ ];
val |= (uint)buffer[ offset++ ] << 8;
if(WriteShort( address, (ushort)val ) == false)
{
return false;
}
address = Microsoft.Zelig.AddressMath.Increment( address, 2 );
numBytes -= 2;
}
if(numBytes != 0)
{
if(WriteByte( address, buffer[offset] ) == false)
{
return false;
}
}
}
return true;
}
//--//
public override unsafe byte ReadByte( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return ptr[0];
}
return ErasedValueByte;
}
public override unsafe ushort ReadShort( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return (ushort)((uint)ptr[0] |
(uint)ptr[1] << 8 );
}
return ErasedValue;
}
public override unsafe uint ReadWord( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return ((uint)ptr[0] |
(uint)ptr[1] << 8 |
(uint)ptr[2] << 16 |
(uint)ptr[3] << 24 );
}
return ErasedValuePair;
}
public override void Read( UIntPtr address ,
byte[] buffer ,
uint offset ,
uint numBytes )
{
while(numBytes != 0)
{
buffer[offset++] = ReadByte( address );
address = Microsoft.Zelig.AddressMath.Increment( address, 1 );
numBytes--;
}
}
public override void SubstituteFirmware( UIntPtr addressDestination ,
UIntPtr addressSource ,
uint numBytes )
{
throw new NotImplementedException();
}
public override void RebootDevice()
{
throw new System.NotImplementedException();
}
//--//
[RT.Inline]
static bool ValidateAddress( UIntPtr address )
{
if(Zelig.AddressMath.IsLessThan( address, new UIntPtr( DRAMBase ) ))
{
return false;
}
if(Zelig.AddressMath.IsGreaterThanOrEqual( address, new UIntPtr( DRAMEnd ) ))
{
return false;
}
return true;
}
[RT.Inline]
static bool ValidateAddressPlus1( UIntPtr address )
{
if(Zelig.AddressMath.IsLessThanOrEqual( address, new UIntPtr( DRAMBase ) ))
{
return false;
}
if(Zelig.AddressMath.IsGreaterThan( address, new UIntPtr( DRAMEnd ) ))
{
return false;
}
return true;
}
[RT.Inline]
static bool IsOddAddress( UIntPtr address )
{
return Zelig.AddressMath.IsAlignedTo16bits( address ) == false;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using Newtonsoft.Json;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.IO.Serialization.Converters;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Rooms.RoomStatuses;
namespace osu.Game.Online.Rooms
{
[JsonObject(MemberSerialization.OptIn)]
public class Room
{
[Cached]
[JsonProperty("id")]
public readonly Bindable<long?> RoomID = new Bindable<long?>();
[Cached]
[JsonProperty("name")]
public readonly Bindable<string> Name = new Bindable<string>();
[Cached]
[JsonProperty("host")]
public readonly Bindable<APIUser> Host = new Bindable<APIUser>();
[Cached]
[JsonProperty("playlist")]
public readonly BindableList<PlaylistItem> Playlist = new BindableList<PlaylistItem>();
[Cached]
[JsonProperty("channel_id")]
public readonly Bindable<int> ChannelId = new Bindable<int>();
[JsonProperty("current_playlist_item")]
[Cached]
public readonly Bindable<PlaylistItem> CurrentPlaylistItem = new Bindable<PlaylistItem>();
[JsonProperty("playlist_item_stats")]
[Cached]
public readonly Bindable<RoomPlaylistItemStats> PlaylistItemStats = new Bindable<RoomPlaylistItemStats>();
[JsonProperty("difficulty_range")]
[Cached]
public readonly Bindable<RoomDifficultyRange> DifficultyRange = new Bindable<RoomDifficultyRange>();
[Cached]
public readonly Bindable<RoomCategory> Category = new Bindable<RoomCategory>();
// Todo: osu-framework bug (https://github.com/ppy/osu-framework/issues/4106)
[JsonProperty("category")]
[JsonConverter(typeof(SnakeCaseStringEnumConverter))]
private RoomCategory category
{
get => Category.Value;
set => Category.Value = value;
}
[Cached]
public readonly Bindable<int?> MaxAttempts = new Bindable<int?>();
[Cached]
public readonly Bindable<RoomStatus> Status = new Bindable<RoomStatus>(new RoomStatusOpen());
[Cached]
public readonly Bindable<RoomAvailability> Availability = new Bindable<RoomAvailability>();
[Cached]
public readonly Bindable<MatchType> Type = new Bindable<MatchType>();
// Todo: osu-framework bug (https://github.com/ppy/osu-framework/issues/4106)
[JsonConverter(typeof(SnakeCaseStringEnumConverter))]
[JsonProperty("type")]
private MatchType type
{
get => Type.Value;
set => Type.Value = value;
}
[Cached]
public readonly Bindable<QueueMode> QueueMode = new Bindable<QueueMode>();
[JsonConverter(typeof(SnakeCaseStringEnumConverter))]
[JsonProperty("queue_mode")]
private QueueMode queueMode
{
get => QueueMode.Value;
set => QueueMode.Value = value;
}
[Cached]
public readonly Bindable<int?> MaxParticipants = new Bindable<int?>();
[Cached]
[JsonProperty("current_user_score")]
public readonly Bindable<PlaylistAggregateScore> UserScore = new Bindable<PlaylistAggregateScore>();
[JsonProperty("has_password")]
public readonly BindableBool HasPassword = new BindableBool();
[Cached]
[JsonProperty("recent_participants")]
public readonly BindableList<APIUser> RecentParticipants = new BindableList<APIUser>();
[Cached]
[JsonProperty("participant_count")]
public readonly Bindable<int> ParticipantCount = new Bindable<int>();
#region Properties only used for room creation request
[Cached(Name = nameof(Password))]
[JsonProperty("password")]
public readonly Bindable<string> Password = new Bindable<string>();
[Cached]
public readonly Bindable<TimeSpan?> Duration = new Bindable<TimeSpan?>();
[JsonProperty("duration")]
private int? duration
{
get => (int?)Duration.Value?.TotalMinutes;
set
{
if (value == null)
Duration.Value = null;
else
Duration.Value = TimeSpan.FromMinutes(value.Value);
}
}
#endregion
// Only supports retrieval for now
[Cached]
[JsonProperty("ends_at")]
public readonly Bindable<DateTimeOffset?> EndDate = new Bindable<DateTimeOffset?>();
// Todo: Find a better way to do this (https://github.com/ppy/osu-framework/issues/1930)
[JsonProperty("max_attempts", DefaultValueHandling = DefaultValueHandling.Ignore)]
private int? maxAttempts
{
get => MaxAttempts.Value;
set => MaxAttempts.Value = value;
}
public Room()
{
Password.BindValueChanged(p => HasPassword.Value = !string.IsNullOrEmpty(p.NewValue));
}
public void CopyFrom(Room other)
{
RoomID.Value = other.RoomID.Value;
Name.Value = other.Name.Value;
Category.Value = other.Category.Value;
if (other.Host.Value != null && Host.Value?.Id != other.Host.Value.Id)
Host.Value = other.Host.Value;
ChannelId.Value = other.ChannelId.Value;
Status.Value = other.Status.Value;
Availability.Value = other.Availability.Value;
HasPassword.Value = other.HasPassword.Value;
Type.Value = other.Type.Value;
MaxParticipants.Value = other.MaxParticipants.Value;
ParticipantCount.Value = other.ParticipantCount.Value;
EndDate.Value = other.EndDate.Value;
UserScore.Value = other.UserScore.Value;
QueueMode.Value = other.QueueMode.Value;
DifficultyRange.Value = other.DifficultyRange.Value;
PlaylistItemStats.Value = other.PlaylistItemStats.Value;
CurrentPlaylistItem.Value = other.CurrentPlaylistItem.Value;
if (EndDate.Value != null && DateTimeOffset.Now >= EndDate.Value)
Status.Value = new RoomStatusEnded();
other.RemoveExpiredPlaylistItems();
if (!Playlist.SequenceEqual(other.Playlist))
{
Playlist.Clear();
Playlist.AddRange(other.Playlist);
}
if (!RecentParticipants.SequenceEqual(other.RecentParticipants))
{
RecentParticipants.Clear();
RecentParticipants.AddRange(other.RecentParticipants);
}
}
public void RemoveExpiredPlaylistItems()
{
// Todo: This is not the best way/place to do this, but the intention is to display all playlist items when the room has ended,
// and display only the non-expired playlist items while the room is still active. In order to achieve this, all expired items are removed from the source Room.
// More refactoring is required before this can be done locally instead - DrawableRoomPlaylist is currently directly bound to the playlist to display items in the room.
if (!(Status.Value is RoomStatusEnded))
Playlist.RemoveAll(i => i.Expired);
}
[JsonObject(MemberSerialization.OptIn)]
public class RoomPlaylistItemStats
{
[JsonProperty("count_active")]
public int CountActive;
[JsonProperty("count_total")]
public int CountTotal;
[JsonProperty("ruleset_ids")]
public int[] RulesetIDs;
}
[JsonObject(MemberSerialization.OptIn)]
public class RoomDifficultyRange
{
[JsonProperty("min")]
public double Min;
[JsonProperty("max")]
public double Max;
}
}
}
| |
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 GitHubHookApi.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;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2008 June 13
**
** 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 definitions of global variables and contants.
*************************************************************************
** 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-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
/* An array to map all upper-case characters into their corresponding
** lower-case character.
**
** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
** handle case conversions for the UTF character set since the tables
** involved are nearly as big or bigger than SQLite itself.
*/
/* An array to map all upper-case characters into their corresponding
** lower-case character.
*/
//
// Replaced in C# with sqlite3UpperToLower class
// static int[] sqlite3UpperToLower = new int[] {
//#if SQLITE_ASCII
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
//18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
//36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
//54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
//104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
//122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
//108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
//126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
//144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
//162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
//180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
//198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
//216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
//234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
//252,253,254,255
//#endif
//#if SQLITE_EBCDIC
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
//16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
//32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
//48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
//64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
//80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
//96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
//112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
//128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
//144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
//160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
//176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
//192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
//208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
//224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
//239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
//#endif
//};
/*
** The following 256 byte lookup table is used to support SQLites built-in
** equivalents to the following standard library functions:
**
** isspace() 0x01
** isalpha() 0x02
** isdigit() 0x04
** isalnum() 0x06
** isxdigit() 0x08
** toupper() 0x20
** SQLite identifier character 0x40
**
** Bit 0x20 is set if the mapped character requires translation to upper
** case. i.e. if the character is a lower-case ASCII character.
** If x is a lower-case ASCII character, then its upper-case equivalent
** is (x - 0x20). Therefore toupper() can be implemented as:
**
** (x & ~(map[x]&0x20))
**
** Standard function tolower() is implemented using the sqlite3UpperToLower[]
** array. tolower() is used more often than toupper() by SQLite.
**
** Bit 0x40 is set if the character non-alphanumeric and can be used in an
** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
** non-ASCII UTF character. Hence the test for whether or not a character is
** part of an identifier is 0x46.
**
** SQLite's versions are identical to the standard versions assuming a
** locale of "C". They are implemented as macros in sqliteInt.h.
*/
#if !NO_SQLITE_ASCII
static byte[] sqlite3CtypeMap = new byte[] {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
};
#endif
#if SQLITE_USE_URI
const bool SQLITE_USE_URI = true;
#else
//# define SQLITE_USE_URI 0
const bool SQLITE_USE_URI = false;
#endif
/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
static Sqlite3Config sqlite3Config = new Sqlite3Config(
SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
1, /* bCoreMutex */
SQLITE_THREADSAFE != 0, /* bFullMutex */
SQLITE_USE_URI, /* bOpenUri */
0x7ffffffe, /* mxStrlen */
100, /* szLookaside */
500, /* nLookaside */
new sqlite3_mem_methods(), /* m */
new sqlite3_mutex_methods( null, null, null, null, null, null, null, null, null ), /* mutex */
new sqlite3_pcache_methods(),/* pcache */
null, /* pHeap */
0, /* nHeap */
0, 0, /* mnHeap, mxHeap */
null, /* pScratch */
0, /* szScratch */
0, /* nScratch */
null, /* pPage */
SQLITE_DEFAULT_PAGE_SIZE, /* szPage */
0, /* nPage */
0, /* mxParserStack */
false, /* sharedCacheEnabled */
/* All the rest should always be initialized to zero */
0, /* isInit */
0, /* inProgress */
0, /* isMutexInit */
0, /* isMallocInit */
0, /* isPCacheInit */
null, /* pInitMutex */
0, /* nRefInitMutex */
null, /* xLog */
0, /* pLogArg */
false /* bLocaltimeFault */
);
/*
** Hash table for global functions - functions common to all
** database connections. After initialization, this table is
** read-only.
*/
static FuncDefHash sqlite3GlobalFunctions;
/*
** Constant tokens for values 0 and 1.
*/
static Token[] sqlite3IntTokens = {
new Token( "0", 1 ),
new Token( "1", 1 )
};
/*
** The value of the "pending" byte must be 0x40000000 (1 byte past the
** 1-gibabyte boundary) in a compatible database. SQLite never uses
** the database page that contains the pending byte. It never attempts
** to read or write that page. The pending byte page is set assign
** for use by the VFS layers as space for managing file locks.
**
** During testing, it is often desirable to move the pending byte to
** a different position in the file. This allows code that has to
** deal with the pending byte to run on files that are much smaller
** than 1 GiB. The sqlite3_test_control() interface can be used to
** move the pending byte.
**
** IMPORTANT: Changing the pending byte to any value other than
** 0x40000000 results in an incompatible database file format!
** Changing the pending byte during operating results in undefined
** and dileterious behavior.
*/
#if !SQLITE_OMIT_WSD
static int sqlite3PendingByte = 0x40000000;
#endif
//#include "opcodes.h"
/*
** Properties of opcodes. The OPFLG_INITIALIZER macro is
** created by mkopcodeh.awk during compilation. Data is obtained
** from the comments following the "case OP_xxxx:" statements in
** the vdbe.c file.
*/
public static int[] sqlite3OpcodeProperty;
}
}
| |
// 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.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
using System.Security;
namespace System
{
[Serializable]
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class Attribute
{
#region Private Statics
#region PropertyInfo
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
{
Debug.Assert(element != null);
Debug.Assert(type != null);
Debug.Assert(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (!inherit)
return attributes;
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
attributes = GetCustomAttributes(baseProp, type, false);
AddAttributesToList(attributeList, attributes, types);
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
if (baseProp.IsDefined(attributeType, false))
return true;
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
}
return false;
}
private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
{
Debug.Assert(property != null);
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
MethodInfo propAccessor = property.GetGetMethod(true);
if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;
if (rtPropAccessor != null)
{
rtPropAccessor = rtPropAccessor.GetParentDefinition();
if (rtPropAccessor != null)
{
// There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
// However, we cannot use that because it doesn't accept null for "types".
return rtPropAccessor.DeclaringType.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
null, //will use default binder
property.PropertyType,
propertyParameters, //used for index properties
null);
}
}
return null;
}
#endregion
#region EventInfo
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
Debug.Assert(element != null);
Debug.Assert(type != null);
Debug.Assert(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit)
{
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
attributes = GetCustomAttributes(baseEvent, type, false);
AddAttributesToList(attributeList, attributes, types);
baseEvent = GetParentDefinition(baseEvent);
}
Array array = CreateAttributeArrayHelper(type, attributeList.Count);
Array.Copy(attributeList.ToArray(), 0, array, 0, attributeList.Count);
return (Attribute[])array;
}
else
return attributes;
}
private static EventInfo GetParentDefinition(EventInfo ev)
{
Debug.Assert(ev != null);
// note that this only works for RuntimeMethodInfo
MethodInfo add = ev.GetAddMethod(true);
RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo;
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
if (rtAdd != null)
return rtAdd.DeclaringType.GetEvent(ev.Name);
}
return null;
}
private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit)
{
Debug.Assert(element != null);
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
EventInfo baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
if (baseEvent.IsDefined(attributeType, false))
return true;
baseEvent = GetParentDefinition(baseEvent);
}
}
return false;
}
#endregion
#region ParameterInfo
private static ParameterInfo GetParentDefinition(ParameterInfo param)
{
Debug.Assert(param != null);
// note that this only works for RuntimeMethodInfo
RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo;
if (rtMethod != null)
{
rtMethod = rtMethod.GetParentDefinition();
if (rtMethod != null)
{
// Find the ParameterInfo on this method
int position = param.Position;
if (position == -1)
{
return rtMethod.ReturnParameter;
}
else
{
ParameterInfo[] parameters = rtMethod.GetParameters();
return parameters[position]; // Point to the correct ParameterInfo of the method
}
}
}
return null;
}
private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
{
Debug.Assert(param != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
// have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
Object[] objAttr;
if (type == null)
type = typeof(Attribute);
objAttr = param.GetCustomAttributes(type, false);
for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
Attribute[] ret = null;
if (objAttr.Length == 0)
ret = CreateAttributeArrayHelper(type, 0);
else
ret = (Attribute[])objAttr;
if (param.Member.DeclaringType == null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
objAttr = baseParam.GetCustomAttributes(type, false);
int count = 0;
for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
{
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
count++;
}
else
objAttr[i] = null;
}
// Get all the attributes that have Attribute as the base class
Attribute[] attributes = CreateAttributeArrayHelper(type, count);
count = 0;
for (int i = 0; i < objAttr.Length; i++)
{
if (objAttr[i] != null)
{
attributes[count] = (Attribute)objAttr[i];
count++;
}
}
Attribute[] temp = ret;
ret = CreateAttributeArrayHelper(type, temp.Length + count);
Array.Copy(temp, ret, temp.Length);
int offset = temp.Length;
for (int i = 0; i < attributes.Length; i++)
ret[offset + i] = attributes[i];
baseParam = GetParentDefinition(baseParam);
}
return ret;
}
private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
{
Debug.Assert(param != null);
Debug.Assert(type != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
// We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.
if (param.IsDefined(type, false))
return true;
if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
return false;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
Object[] objAttr = baseParam.GetCustomAttributes(type, false);
for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
return true;
}
baseParam = GetParentDefinition(baseParam);
}
return false;
}
#endregion
#region Utility
private static void CopyToArrayList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
if (!types.ContainsKey(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
private static Type[] GetIndexParameterTypes(PropertyInfo element)
{
ParameterInfo[] indexParams = element.GetIndexParameters();
if (indexParams.Length > 0)
{
Type[] indexParamTypes = new Type[indexParams.Length];
for (int i = 0; i < indexParams.Length; i++)
{
indexParamTypes[i] = indexParams[i].ParameterType;
}
return indexParamTypes;
}
return Array.Empty<Type>();
}
private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
AttributeUsageAttribute usage = null;
types.TryGetValue(attrType, out usage);
if (usage == null)
{
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
{
// we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
}
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
// Check if the custom attributes is Inheritable
Object[] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
if (obj.Length == 1)
return (AttributeUsageAttribute)obj[0];
if (obj.Length == 0)
return AttributeUsageAttribute.Default;
throw new FormatException(
SR.Format(SR.Format_AttributeUsage, type));
}
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
}
#endregion
#endregion
#region Public Statics
#region MemberInfo
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
{
return GetCustomAttributes(element, type, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (type == null)
throw new ArgumentNullException(nameof(type));
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
return element.GetCustomAttributes(type, inherit) as Attribute[];
}
}
public static Attribute[] GetCustomAttributes(MemberInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit);
case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);
default:
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
}
public static bool IsDefined(MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
{
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
switch (element.MemberType)
{
case MemberTypes.Property:
return InternalIsDefined((PropertyInfo)element, attributeType, inherit);
case MemberTypes.Event:
return InternalIsDefined((EventInfo)element, attributeType, inherit);
default:
return element.IsDefined(attributeType, inherit);
}
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#region ParameterInfo
public static Attribute[] GetCustomAttributes(ParameterInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
return (Attribute[])GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];
return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
public static bool IsDefined(ParameterInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
MemberInfo member = element.Member;
switch (member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
case MemberTypes.Constructor:
return element.IsDefined(attributeType, false);
case MemberTypes.Property:
return element.IsDefined(attributeType, false);
default:
Debug.Fail("Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(SR.Argument_InvalidParamInfo);
}
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#region Module
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Module element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static bool IsDefined(Module element, Type attributeType)
{
return IsDefined(element, attributeType, false);
}
public static bool IsDefined(Module element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return element.IsDefined(attributeType, false);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#region Assembly
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(Assembly element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static bool IsDefined(Assembly element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(Assembly element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return element.IsDefined(attributeType, false);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#endregion
#region Constructor
protected Attribute() { }
#endregion
#region Object Overrides
public override bool Equals(Object obj)
{
if (obj == null)
return false;
Type thisType = this.GetType();
Type thatType = obj.GetType();
if (thatType != thisType)
return false;
Object thisObj = this;
Object thisResult, thatResult;
while (thisType != typeof(Attribute))
{
FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
for (int i = 0; i < thisFields.Length; i++)
{
// Visibility check and consistency check are not necessary.
thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
if (!AreFieldValuesEqual(thisResult, thatResult))
{
return false;
}
}
thisType = thisType.BaseType;
}
return true;
}
// Compares values of custom-attribute fields.
private static bool AreFieldValuesEqual(Object thisValue, Object thatValue)
{
if (thisValue == null && thatValue == null)
return true;
if (thisValue == null || thatValue == null)
return false;
if (thisValue.GetType().IsArray)
{
// Ensure both are arrays of the same type.
if (!thisValue.GetType().Equals(thatValue.GetType()))
{
return false;
}
Array thisValueArray = thisValue as Array;
Array thatValueArray = thatValue as Array;
if (thisValueArray.Length != thatValueArray.Length)
{
return false;
}
// Attributes can only contain single-dimension arrays, so we don't need to worry about
// multidimensional arrays.
Debug.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
for (int j = 0; j < thisValueArray.Length; j++)
{
if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
{
return false;
}
}
}
else
{
// An object of type Attribute will cause a stack overflow.
// However, this should never happen because custom attributes cannot contain values other than
// constants, single-dimensional arrays and typeof expressions.
Debug.Assert(!(thisValue is Attribute));
if (!thisValue.Equals(thatValue))
return false;
}
return true;
}
public override int GetHashCode()
{
Type type = GetType();
while (type != typeof(Attribute))
{
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
Object vThis = null;
for (int i = 0; i < fields.Length; i++)
{
// Visibility check and consistency check are not necessary.
Object fieldValue = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
// The hashcode of an array ignores the contents of the array, so it can produce
// different hashcodes for arrays with the same contents.
// Since we do deep comparisons of arrays in Equals(), this means Equals and GetHashCode will
// be inconsistent for arrays. Therefore, we ignore hashes of arrays.
if (fieldValue != null && !fieldValue.GetType().IsArray)
vThis = fieldValue;
if (vThis != null)
break;
}
if (vThis != null)
return vThis.GetHashCode();
type = type.BaseType;
}
return type.GetHashCode();
}
#endregion
#region Public Virtual Members
public virtual Object TypeId { get { return GetType(); } }
public virtual bool Match(Object obj) { return Equals(obj); }
#endregion
#region Public Members
public virtual bool IsDefaultAttribute() { return false; }
#endregion
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version (unit test)
// 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.Generic;
using Encog.Engine.Network.Activation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Encog.ML.Data.Temporal
{
[TestClass]
public class TestTemporal
{
[TestMethod]
public void BasicTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.Generate();
Assert.AreEqual(10, temporal.InputNeuronCount);
Assert.AreEqual(1, temporal.OutputNeuronCount);
Assert.AreEqual(10, temporal.CalculateActualSetSize());
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
itr.MoveNext();
// set 0
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(1.0, pair.Input[0]);
Assert.AreEqual(2.0, pair.Input[1]);
Assert.AreEqual(4.0, pair.Input[2]);
Assert.AreEqual(5.0, pair.Input[3]);
Assert.AreEqual(7.0, pair.Input[4]);
Assert.AreEqual(8.0, pair.Input[5]);
Assert.AreEqual(10.0, pair.Input[6]);
Assert.AreEqual(11.0, pair.Input[7]);
Assert.AreEqual(13.0, pair.Input[8]);
Assert.AreEqual(14.0, pair.Input[9]);
Assert.AreEqual(18.0, pair.Ideal[0]);
// set 1
itr.MoveNext();
pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(4.0, pair.Input[0]);
Assert.AreEqual(5.0, pair.Input[1]);
Assert.AreEqual(7.0, pair.Input[2]);
Assert.AreEqual(8.0, pair.Input[3]);
Assert.AreEqual(10.0, pair.Input[4]);
Assert.AreEqual(11.0, pair.Input[5]);
Assert.AreEqual(13.0, pair.Input[6]);
Assert.AreEqual(14.0, pair.Input[7]);
Assert.AreEqual(16.0, pair.Input[8]);
Assert.AreEqual(17.0, pair.Input[9]);
Assert.AreEqual(21.0, pair.Ideal[0]);
// set 2
itr.MoveNext();
pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(7.0, pair.Input[0]);
Assert.AreEqual(8.0, pair.Input[1]);
Assert.AreEqual(10.0, pair.Input[2]);
Assert.AreEqual(11.0, pair.Input[3]);
Assert.AreEqual(13.0, pair.Input[4]);
Assert.AreEqual(14.0, pair.Input[5]);
Assert.AreEqual(16.0, pair.Input[6]);
Assert.AreEqual(17.0, pair.Input[7]);
Assert.AreEqual(19.0, pair.Input[8]);
Assert.AreEqual(20.0, pair.Input[9]);
Assert.AreEqual(24.0, pair.Ideal[0]);
// set 3
itr.MoveNext();
pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(10.0, pair.Input[0]);
Assert.AreEqual(11.0, pair.Input[1]);
Assert.AreEqual(13.0, pair.Input[2]);
Assert.AreEqual(14.0, pair.Input[3]);
Assert.AreEqual(16.0, pair.Input[4]);
Assert.AreEqual(17.0, pair.Input[5]);
Assert.AreEqual(19.0, pair.Input[6]);
Assert.AreEqual(20.0, pair.Input[7]);
Assert.AreEqual(22.0, pair.Input[8]);
Assert.AreEqual(23.0, pair.Input[9]);
Assert.AreEqual(27.0, pair.Ideal[0]);
}
[TestMethod]
public void HiLowTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.HighSequence = 8;
temporal.LowSequence = 2;
temporal.Generate();
Assert.AreEqual(10, temporal.InputNeuronCount);
Assert.AreEqual(1, temporal.OutputNeuronCount);
Assert.AreEqual(7, temporal.CalculateActualSetSize());
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
itr.MoveNext();
// set 0
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(7.0, pair.Input[0]);
Assert.AreEqual(8.0, pair.Input[1]);
Assert.AreEqual(10.0, pair.Input[2]);
Assert.AreEqual(11.0, pair.Input[3]);
Assert.AreEqual(13.0, pair.Input[4]);
Assert.AreEqual(14.0, pair.Input[5]);
Assert.AreEqual(16.0, pair.Input[6]);
Assert.AreEqual(17.0, pair.Input[7]);
Assert.AreEqual(19.0, pair.Input[8]);
Assert.AreEqual(20.0, pair.Input[9]);
Assert.AreEqual(24.0, pair.Ideal[0]);
}
[TestMethod]
public void FormatTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.DeltaChange, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.PercentChange, true, false));
temporal.AddDescription(new TemporalDataDescription(TemporalDataDescription.Type.Raw, false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.Generate();
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
itr.MoveNext();
// set 0
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(3.0, pair.Input[0]);
Assert.AreEqual(1.5, pair.Input[1]);
Assert.AreEqual(3.0, pair.Input[2]);
Assert.AreEqual(0.6, pair.Input[3]);
Assert.AreEqual(3.0, pair.Input[4]);
Assert.AreEqual(0.375, pair.Input[5]);
Assert.AreEqual(3.0, pair.Input[6]);
Assert.AreEqual(0.25, Math.Round(pair.Input[7]*4.0)/4.0);
Assert.AreEqual(3.0, pair.Input[8]);
Assert.AreEqual(0.25, Math.Round(pair.Input[9]*4.0)/4.0);
Assert.AreEqual(18.0, pair.Ideal[0]);
}
[TestMethod]
public void ActivationTemporal()
{
var temporal = new TemporalMLDataSet(5, 1);
temporal.AddDescription(new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.Raw,
true, false));
temporal.AddDescription(new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.Raw,
true, false));
temporal.AddDescription(new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.Raw,
false, true));
for (int i = 0; i < 10; i++)
{
TemporalPoint tp = temporal.CreatePoint(i);
tp[0] = 1.0 + (i*3);
tp[1] = 2.0 + (i*3);
tp[2] = 3.0 + (i*3);
}
temporal.Generate();
IEnumerator<IMLDataPair> itr = temporal.GetEnumerator();
// set 0
itr.MoveNext();
IMLDataPair pair = itr.Current;
Assert.AreEqual(10, pair.Input.Count);
Assert.AreEqual(1, pair.Ideal.Count);
Assert.AreEqual(0.75, Math.Round(pair.Input[0]*4.0)/4.0);
Assert.AreEqual(1.0, Math.Round(pair.Input[1]*4.0)/4.0);
Assert.AreEqual(1.0, Math.Round(pair.Input[2]*4.0)/4.0);
Assert.AreEqual(1.0, Math.Round(pair.Input[3]*4.0)/4.0);
}
}
}
| |
//
// Booter.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// 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.
//
//
// Crazy Banshee Boot Procedure
//
// [Exec or DBus Activation] <---------------------------------------------------------.
// | |
// v |
// [Bootloader (Banshee.exe)] |
// | |
// v yes |
// <org.bansheeproject.Banshee?> -------> [Load DBus Proxy Client (Halie.exe)] -----. |
// |no | |
// v yes | |
// <org.bansheeproject.CollectionIndexer?> -------> [Tell Indexer to Reboot] -----/IPC/'
// |no |
// v yes |
// <command line contains --indexer?> -------> [Load Indexer Client (Beroe.exe)] |
// |no |
// v yes |
// <command line contains --client=XYZ> -------> [Load XYZ Client] |
// |no |
// v |
// [Load Primary Interface Client (Nereid.exe)] <-----------------------------------'
//
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Mono.Unix;
using NDesk.DBus;
using Hyena;
using Hyena.CommandLine;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Collection.Indexer;
namespace Booter
{
public static class Booter
{
public static void Main ()
{
Paths.ApplicationName = Application.InternalName;
if (CheckHelpVersion ()) {
return;
}
if (ApplicationInstance.AlreadyRunning) {
// DBus Command/Query/File Proxy Client
BootClient ("Halie");
NotifyStartupComplete ();
} else if (RemoteServiceManager.ServiceNameHasOwner ("CollectionIndexer")) {
// Tell the existing indexer to start Banshee when it's done
IIndexerClient indexer = RemoteServiceManager.FindInstance<IIndexerClient> ("CollectionIndexer", "/IndexerClient");
try {
indexer.Hello ();
indexer.RebootWhenFinished (Environment.GetCommandLineArgs ());
Log.Warning ("The Banshee indexer is currently running. Banshee will be started when the indexer finishes.");
} catch (Exception e) {
Log.Exception ("CollectionIndexer found on the Bus, but doesn't say Hello", e);
}
} else if (ApplicationContext.CommandLine.Contains ("indexer")) {
// Indexer Client
BootClient ("Beroe");
} else if (ApplicationContext.CommandLine.Contains ("client")) {
BootClient (Path.GetFileNameWithoutExtension (ApplicationContext.CommandLine["client"]));
} else {
if (PlatformDetection.IsMeeGo) {
BootClient ("MeeGo");
} else {
BootClient ("Nereid");
}
}
}
private static void BootClient (string clientName)
{
AppDomain.CurrentDomain.ExecuteAssembly (Path.Combine (Path.GetDirectoryName (
Assembly.GetEntryAssembly ().Location), String.Format ("{0}.exe", clientName)));
}
[DllImport ("libgdk-win32-2.0-0.dll")]
private static extern bool gdk_init_check (IntPtr argc, IntPtr argv);
[DllImport ("libgdk-win32-2.0-0.dll")]
private static extern void gdk_notify_startup_complete ();
private static void NotifyStartupComplete ()
{
try {
if (gdk_init_check (IntPtr.Zero, IntPtr.Zero)) {
gdk_notify_startup_complete ();
}
} catch (Exception e) {
Hyena.Log.Exception ("Problem with NotifyStartupComplete", e);
}
}
private static bool CheckHelpVersion ()
{
if (ApplicationContext.CommandLine.ContainsStart ("help")) {
ShowHelp ();
return true;
} else if (ApplicationContext.CommandLine.Contains ("version")) {
ShowVersion ();
return true;
}
return false;
}
private static void ShowHelp ()
{
Console.WriteLine ("Usage: {0} [options...] [files|URIs...]", "banshee-1");
Console.WriteLine ();
Layout commands = new Layout (
new LayoutGroup ("help", Catalog.GetString ("Help Options"),
new LayoutOption ("help", Catalog.GetString ("Show this help")),
new LayoutOption ("help-playback", Catalog.GetString ("Show options for controlling playback")),
new LayoutOption ("help-query-track", Catalog.GetString ("Show options for querying the playing track")),
new LayoutOption ("help-query-player", Catalog.GetString ("Show options for querying the playing engine")),
new LayoutOption ("help-ui", Catalog.GetString ("Show options for the user interface")),
new LayoutOption ("help-debug", Catalog.GetString ("Show options for developers and debugging")),
new LayoutOption ("help-all", Catalog.GetString ("Show all option groups")),
new LayoutOption ("version", Catalog.GetString ("Show version information"))
),
new LayoutGroup ("playback", Catalog.GetString ("Playback Control Options"),
new LayoutOption ("next", Catalog.GetString ("Play the next track, optionally restarting if the 'restart' value is set")),
new LayoutOption ("previous", Catalog.GetString ("Play the previous track, optionally restarting if the 'restart value is set")),
new LayoutOption ("restart-or-previous", Catalog.GetString ("If the current song has been played longer than 4 seconds then restart it, otherwise the same as --previous")),
new LayoutOption ("play-enqueued", Catalog.GetString ("Automatically start playing any tracks enqueued on the command line")),
new LayoutOption ("play", Catalog.GetString ("Start playback")),
new LayoutOption ("pause", Catalog.GetString ("Pause playback")),
new LayoutOption ("toggle-playing", Catalog.GetString ("Toggle playback")),
new LayoutOption ("stop", Catalog.GetString ("Completely stop playback")),
new LayoutOption ("stop-when-finished", Catalog.GetString (
"Enable or disable playback stopping after the currently playing track (value should be either 'true' or 'false')")),
new LayoutOption ("set-volume=LEVEL", Catalog.GetString ("Set the playback volume (0-100), prefix with +/- for relative values")),
new LayoutOption ("set-position=POS", Catalog.GetString ("Seek to a specific point (seconds, float)")),
new LayoutOption ("set-rating=RATING", Catalog.GetString ("Set the currently played track's rating (0 to 5)"))
),
new LayoutGroup ("query-player", Catalog.GetString ("Player Engine Query Options"),
new LayoutOption ("query-current-state", Catalog.GetString ("Current player state")),
new LayoutOption ("query-last-state", Catalog.GetString ("Last player state")),
new LayoutOption ("query-can-pause", Catalog.GetString ("Query whether the player can be paused")),
new LayoutOption ("query-can-seek", Catalog.GetString ("Query whether the player can seek")),
new LayoutOption ("query-volume", Catalog.GetString ("Player volume")),
new LayoutOption ("query-position", Catalog.GetString ("Player position in currently playing track"))
),
new LayoutGroup ("query-track", Catalog.GetString ("Playing Track Metadata Query Options"),
new LayoutOption ("query-uri", Catalog.GetString ("URI")),
new LayoutOption ("query-artist", Catalog.GetString ("Artist Name")),
new LayoutOption ("query-album", Catalog.GetString ("Album Title")),
new LayoutOption ("query-title", Catalog.GetString ("Track Title")),
new LayoutOption ("query-duration", Catalog.GetString ("Duration")),
new LayoutOption ("query-track-number", Catalog.GetString ("Track Number")),
new LayoutOption ("query-track-count", Catalog.GetString ("Track Count")),
new LayoutOption ("query-disc", Catalog.GetString ("Disc Number")),
new LayoutOption ("query-year", Catalog.GetString ("Year")),
new LayoutOption ("query-rating", Catalog.GetString ("Rating")),
new LayoutOption ("query-score", Catalog.GetString ("Score")),
new LayoutOption ("query-bit-rate", Catalog.GetString ("Bit Rate"))
),
new LayoutGroup ("ui", Catalog.GetString ("User Interface Options"),
new LayoutOption ("show|--present", Catalog.GetString ("Present the user interface on the active workspace")),
new LayoutOption ("fullscreen", Catalog.GetString ("Enter the full-screen mode")),
new LayoutOption ("hide", Catalog.GetString ("Hide the user interface")),
new LayoutOption ("no-present", Catalog.GetString ("Do not present the user interface, regardless of any other options")),
new LayoutOption ("show-import-media", Catalog.GetString ("Present the import media dialog box")),
new LayoutOption ("show-about", Catalog.GetString ("Present the about dialog")),
new LayoutOption ("show-open-location", Catalog.GetString ("Present the open location dialog")),
new LayoutOption ("show-preferences", Catalog.GetString ("Present the preferences dialog"))
),
new LayoutGroup ("debugging", Catalog.GetString ("Debugging and Development Options"),
new LayoutOption ("debug", Catalog.GetString ("Enable general debugging features")),
new LayoutOption ("debug-sql", Catalog.GetString ("Enable debugging output of SQL queries")),
new LayoutOption ("debug-addins", Catalog.GetString ("Enable debugging output of Mono.Addins")),
new LayoutOption ("db=FILE", Catalog.GetString ("Specify an alternate database to use")),
new LayoutOption ("gconf-base-key=KEY", Catalog.GetString ("Specify an alternate key, default is /apps/banshee-1/")),
new LayoutOption ("uninstalled", Catalog.GetString ("Optimize instance for running uninstalled; " +
"most notably, this will create an alternate Mono.Addins database in the working directory")),
new LayoutOption ("disable-dbus", Catalog.GetString ("Disable DBus support completely")),
new LayoutOption ("no-gtkrc", String.Format (Catalog.GetString (
"Skip loading a custom gtkrc file ({0}) if it exists"),
Path.Combine (Paths.ApplicationData, "gtkrc").Replace (
Environment.GetFolderPath (Environment.SpecialFolder.Personal), "~")))
)
);
if (ApplicationContext.CommandLine.Contains ("help-all")) {
Console.WriteLine (commands);
return;
}
List<string> errors = null;
foreach (KeyValuePair<string, string> argument in ApplicationContext.CommandLine.Arguments) {
switch (argument.Key) {
case "help": Console.WriteLine (commands.ToString ("help")); break;
case "help-debug": Console.WriteLine (commands.ToString ("debugging")); break;
case "help-query-track": Console.WriteLine (commands.ToString ("query-track")); break;
case "help-query-player": Console.WriteLine (commands.ToString ("query-player")); break;
case "help-ui": Console.WriteLine (commands.ToString ("ui")); break;
case "help-playback": Console.WriteLine (commands.ToString ("playback")); break;
default:
if (argument.Key.StartsWith ("help")) {
(errors ?? (errors = new List<string> ())).Add (argument.Key);
}
break;
}
}
if (errors != null) {
Console.WriteLine (commands.LayoutLine (String.Format (Catalog.GetString (
"The following help arguments are invalid: {0}"),
Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", "))));
}
}
private static void ShowVersion ()
{
Console.WriteLine ("Banshee {0} ({1}) http://banshee.fm", Application.DisplayVersion, Application.Version);
Console.WriteLine ("Copyright 2005-{0} Novell, Inc. and Contributors.", DateTime.Now.Year);
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// A priority queue class based on an interval heap data structure.
/// </summary>
/// <typeparam name="T">The item type</typeparam>
[Serializable]
public class IntervalHeap<T> : CollectionValueBase<T>, IPriorityQueue<T>
{
#region Events
/// <summary>
///
/// </summary>
/// <value></value>
public override EventTypeEnum ListenableEvents { get { return EventTypeEnum.Basic; } }
#endregion
#region Fields
[Serializable]
struct Interval
{
internal T first, last; internal Handle firsthandle, lasthandle;
public override string ToString() { return string.Format("[{0}; {1}]", first, last); }
}
int stamp;
SCG.IComparer<T> comparer;
SCG.IEqualityComparer<T> itemequalityComparer;
Interval[] heap;
int size;
#endregion
#region Util
bool heapifyMin(int i)
{
bool swappedroot = false;
int cell = i, currentmin = cell;
T currentitem = heap[cell].first;
Handle currenthandle = heap[cell].firsthandle;
// bug20080222.txt
{
T other = heap[cell].last;
if (2 * cell + 1 < size && comparer.Compare(currentitem, other) > 0)
{
swappedroot = true;
Handle otherhandle = heap[cell].lasthandle;
updateLast(cell, currentitem, currenthandle);
currentitem = other;
currenthandle = otherhandle;
}
}
T minitem = currentitem;
Handle minhandle = currenthandle;
while (true)
{
int l = 2 * cell + 1, r = l + 1;
T lv, rv;
if (2 * l < size && comparer.Compare(lv = heap[l].first, minitem) < 0)
{ currentmin = l; minitem = lv; }
if (2 * r < size && comparer.Compare(rv = heap[r].first, minitem) < 0)
{ currentmin = r; minitem = rv; }
if (currentmin == cell)
break;
minhandle = heap[currentmin].firsthandle;
updateFirst(cell, minitem, minhandle);
cell = currentmin;
//Maybe swap first and last
T other = heap[cell].last;
if (2 * currentmin + 1 < size && comparer.Compare(currentitem, other) > 0)
{
Handle otherhandle = heap[cell].lasthandle;
updateLast(cell, currentitem, currenthandle);
currentitem = other;
currenthandle = otherhandle;
}
minitem = currentitem;
minhandle = currenthandle;
}
if (cell != i || swappedroot)
updateFirst(cell, minitem, minhandle);
return swappedroot;
}
bool heapifyMax(int i)
{
bool swappedroot = false;
int cell = i, currentmax = cell;
T currentitem = heap[cell].last;
Handle currenthandle = heap[cell].lasthandle;
// bug20080222.txt
{
T other = heap[cell].first;
if (2 * cell + 1 < size && comparer.Compare(currentitem, other) < 0)
{
swappedroot = true;
Handle otherhandle = heap[cell].firsthandle;
updateFirst(cell, currentitem, currenthandle);
currentitem = other;
currenthandle = otherhandle;
}
}
T maxitem = currentitem;
Handle maxhandle = currenthandle;
while (true)
{
int l = 2 * cell + 1, r = l + 1;
T lv, rv;
if (2 * l + 1 < size && comparer.Compare(lv = heap[l].last, maxitem) > 0)
{ currentmax = l; maxitem = lv; }
if (2 * r + 1 < size && comparer.Compare(rv = heap[r].last, maxitem) > 0)
{ currentmax = r; maxitem = rv; }
if (currentmax == cell)
break;
maxhandle = heap[currentmax].lasthandle;
updateLast(cell, maxitem, maxhandle);
cell = currentmax;
//Maybe swap first and last
T other = heap[cell].first;
if (comparer.Compare(currentitem, other) < 0)
{
Handle otherhandle = heap[cell].firsthandle;
updateFirst(cell, currentitem, currenthandle);
currentitem = other;
currenthandle = otherhandle;
}
maxitem = currentitem;
maxhandle = currenthandle;
}
if (cell != i || swappedroot) //Check could be better?
updateLast(cell, maxitem, maxhandle);
return swappedroot;
}
void bubbleUpMin(int i)
{
if (i > 0)
{
T min = heap[i].first, iv = min;
Handle minhandle = heap[i].firsthandle;
int p = (i + 1) / 2 - 1;
while (i > 0)
{
if (comparer.Compare(iv, min = heap[p = (i + 1) / 2 - 1].first) < 0)
{
updateFirst(i, min, heap[p].firsthandle);
min = iv;
i = p;
}
else
break;
}
updateFirst(i, iv, minhandle);
}
}
void bubbleUpMax(int i)
{
if (i > 0)
{
T max = heap[i].last, iv = max;
Handle maxhandle = heap[i].lasthandle;
int p = (i + 1) / 2 - 1;
while (i > 0)
{
if (comparer.Compare(iv, max = heap[p = (i + 1) / 2 - 1].last) > 0)
{
updateLast(i, max, heap[p].lasthandle);
max = iv;
i = p;
}
else
break;
}
updateLast(i, iv, maxhandle);
}
}
#endregion
#region Constructors
/// <summary>
/// Create an interval heap with natural item comparer and default initial capacity (16)
/// </summary>
public IntervalHeap() : this(16) { }
/// <summary>
/// Create an interval heap with external item comparer and default initial capacity (16)
/// </summary>
/// <param name="comparer">The external comparer</param>
public IntervalHeap(SCG.IComparer<T> comparer) : this(16, comparer) { }
//TODO: maybe remove
/// <summary>
/// Create an interval heap with natural item comparer and prescribed initial capacity
/// </summary>
/// <param name="capacity">The initial capacity</param>
public IntervalHeap(int capacity) : this(capacity, Comparer<T>.Default, EqualityComparer<T>.Default) { }
/// <summary>
/// Create an interval heap with external item comparer and prescribed initial capacity
/// </summary>
/// <param name="comparer">The external comparer</param>
/// <param name="capacity">The initial capacity</param>
public IntervalHeap(int capacity, SCG.IComparer<T> comparer) : this(capacity, comparer, new ComparerZeroHashCodeEqualityComparer<T>(comparer)) { }
IntervalHeap(int capacity, SCG.IComparer<T> comparer, SCG.IEqualityComparer<T> itemequalityComparer)
{
if (comparer == null)
throw new NullReferenceException("Item comparer cannot be null");
if (itemequalityComparer == null)
throw new NullReferenceException("Item equality comparer cannot be null");
this.comparer = comparer;
this.itemequalityComparer = itemequalityComparer;
int length = 1;
while (length < capacity) length <<= 1;
heap = new Interval[length];
}
#endregion
#region IPriorityQueue<T> Members
/// <summary>
/// Find the current least item of this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The least item.</returns>
public T FindMin()
{
if (size == 0)
throw new NoSuchItemException();
return heap[0].first;
}
/// <summary>
/// Remove the least item from this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The removed item.</returns>
public T DeleteMin()
{
IPriorityQueueHandle<T> handle = null;
return DeleteMin(out handle);
}
/// <summary>
/// Find the current largest item of this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The largest item.</returns>
public T FindMax()
{
if (size == 0)
throw new NoSuchItemException("Heap is empty");
else if (size == 1)
return heap[0].first;
else
return heap[0].last;
}
/// <summary>
/// Remove the largest item from this priority queue.
/// <exception cref="NoSuchItemException"/> if queue is empty
/// </summary>
/// <returns>The removed item.</returns>
public T DeleteMax()
{
IPriorityQueueHandle<T> handle = null;
return DeleteMax(out handle);
}
/// <summary>
/// The comparer object supplied at creation time for this collection
/// </summary>
/// <value>The comparer</value>
public SCG.IComparer<T> Comparer { get { return comparer; } }
#endregion
#region IExtensible<T> Members
/// <summary>
/// If true any call of an updating operation will throw an
/// <code>ReadOnlyCollectionException</code>
/// </summary>
/// <value>True if this collection is read-only.</value>
public bool IsReadOnly { get { return false; } }
/// <summary>
///
/// </summary>
/// <value>True since this collection has bag semantics</value>
public bool AllowsDuplicates { get { return true; } }
/// <summary>
/// Value is null since this collection has no equality concept for its items.
/// </summary>
/// <value></value>
public virtual SCG.IEqualityComparer<T> EqualityComparer { get { return itemequalityComparer; } }
/// <summary>
/// By convention this is true for any collection with set semantics.
/// </summary>
/// <value>True if only one representative of a group of equal items
/// is kept in the collection together with the total count.</value>
public virtual bool DuplicatesByCounting { get { return false; } }
/// <summary>
/// Add an item to this priority queue.
/// </summary>
/// <param name="item">The item to add.</param>
/// <returns>True</returns>
public bool Add(T item)
{
stamp++;
if (add(null, item))
{
raiseItemsAdded(item, 1);
raiseCollectionChanged();
return true;
}
return false;
}
private bool add(Handle itemhandle, T item)
{
if (size == 0)
{
size = 1;
updateFirst(0, item, itemhandle);
return true;
}
if (size == 2 * heap.Length)
{
Interval[] newheap = new Interval[2 * heap.Length];
Array.Copy(heap, newheap, heap.Length);
heap = newheap;
}
if (size % 2 == 0)
{
int i = size / 2, p = (i + 1) / 2 - 1;
T tmp = heap[p].last;
if (comparer.Compare(item, tmp) > 0)
{
updateFirst(i, tmp, heap[p].lasthandle);
updateLast(p, item, itemhandle);
bubbleUpMax(p);
}
else
{
updateFirst(i, item, itemhandle);
if (comparer.Compare(item, heap[p].first) < 0)
bubbleUpMin(i);
}
}
else
{
int i = size / 2;
T other = heap[i].first;
if (comparer.Compare(item, other) < 0)
{
updateLast(i, other, heap[i].firsthandle);
updateFirst(i, item, itemhandle);
bubbleUpMin(i);
}
else
{
updateLast(i, item, itemhandle);
bubbleUpMax(i);
}
}
size++;
return true;
}
private void updateLast(int cell, T item, Handle handle)
{
heap[cell].last = item;
if (handle != null)
handle.index = 2 * cell + 1;
heap[cell].lasthandle = handle;
}
private void updateFirst(int cell, T item, Handle handle)
{
heap[cell].first = item;
if (handle != null)
handle.index = 2 * cell;
heap[cell].firsthandle = handle;
}
/// <summary>
/// Add the elements from another collection with a more specialized item type
/// to this collection.
/// </summary>
/// <param name="items">The items to add</param>
public void AddAll(SCG.IEnumerable<T> items)
{
stamp++;
int oldsize = size;
foreach (T item in items)
add(null, item);
if (size != oldsize)
{
if ((ActiveEvents & EventTypeEnum.Added) != 0)
foreach (T item in items)
raiseItemsAdded(item, 1);
raiseCollectionChanged();
}
}
#endregion
#region ICollection<T> members
/// <summary>
///
/// </summary>
/// <value>True if this collection is empty.</value>
public override bool IsEmpty { get { return size == 0; } }
/// <summary>
///
/// </summary>
/// <value>The size of this collection</value>
public override int Count { get { return size; } }
/// <summary>
/// The value is symbolic indicating the type of asymptotic complexity
/// in terms of the size of this collection (worst-case or amortized as
/// relevant).
/// </summary>
/// <value>A characterization of the speed of the
/// <code>Count</code> property in this collection.</value>
public override Speed CountSpeed { get { return Speed.Constant; } }
/// <summary>
/// Choose some item of this collection.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override T Choose()
{
if (size == 0)
throw new NoSuchItemException("Collection is empty");
return heap[0].first;
}
/// <summary>
/// Create an enumerator for the collection
/// <para>Note: the enumerator does *not* enumerate the items in sorted order,
/// but in the internal table order.</para>
/// </summary>
/// <returns>The enumerator(SIC)</returns>
public override SCG.IEnumerator<T> GetEnumerator()
{
int mystamp = stamp;
for (int i = 0; i < size; i++)
{
if (mystamp != stamp) throw new CollectionModifiedException();
yield return i % 2 == 0 ? heap[i >> 1].first : heap[i >> 1].last;
}
yield break;
}
#endregion
#region Diagnostics
private bool check(int i, T min, T max)
{
bool retval = true;
Interval interval = heap[i];
T first = interval.first, last = interval.last;
if (2 * i + 1 == size)
{
if (comparer.Compare(min, first) > 0)
{
Logger.Log(string.Format("Cell {0}: parent.first({1}) > first({2}) [size={3}]", i, min, first, size));
retval = false;
}
if (comparer.Compare(first, max) > 0)
{
Logger.Log(string.Format("Cell {0}: first({1}) > parent.last({2}) [size={3}]", i, first, max, size));
retval = false;
}
if (interval.firsthandle != null && interval.firsthandle.index != 2 * i)
{
Logger.Log(string.Format("Cell {0}: firsthandle.index({1}) != 2*cell({2}) [size={3}]", i, interval.firsthandle.index, 2 * i, size));
retval = false;
}
return retval;
}
else
{
if (comparer.Compare(min, first) > 0)
{
Logger.Log(string.Format("Cell {0}: parent.first({1}) > first({2}) [size={3}]", i, min, first, size));
retval = false;
}
if (comparer.Compare(first, last) > 0)
{
Logger.Log(string.Format("Cell {0}: first({1}) > last({2}) [size={3}]", i, first, last, size));
retval = false;
}
if (comparer.Compare(last, max) > 0)
{
Logger.Log(string.Format("Cell {0}: last({1}) > parent.last({2}) [size={3}]", i, last, max, size));
retval = false;
}
if (interval.firsthandle != null && interval.firsthandle.index != 2 * i)
{
Logger.Log(string.Format("Cell {0}: firsthandle.index({1}) != 2*cell({2}) [size={3}]", i, interval.firsthandle.index, 2 * i, size));
retval = false;
}
if (interval.lasthandle != null && interval.lasthandle.index != 2 * i + 1)
{
Logger.Log(string.Format("Cell {0}: lasthandle.index({1}) != 2*cell+1({2}) [size={3}]", i, interval.lasthandle.index, 2 * i + 1, size));
retval = false;
}
int l = 2 * i + 1, r = l + 1;
if (2 * l < size)
retval = retval && check(l, first, last);
if (2 * r < size)
retval = retval && check(r, first, last);
}
return retval;
}
/// <summary>
/// Check the integrity of the internal data structures of this collection.
/// Only avaliable in DEBUG builds???
/// </summary>
/// <returns>True if check does not fail.</returns>
public bool Check()
{
if (size == 0)
return true;
if (size == 1)
return (object)(heap[0].first) != null;
return check(0, heap[0].first, heap[0].last);
}
#endregion
#region IPriorityQueue<T> Members
[Serializable]
class Handle : IPriorityQueueHandle<T>
{
/// <summary>
/// To save space, the index is 2*cell for heap[cell].first, and 2*cell+1 for heap[cell].last
/// </summary>
internal int index = -1;
public override string ToString()
{
return string.Format("[{0}]", index);
}
}
/// <summary>
/// Get or set the item corresponding to a handle.
/// </summary>
/// <exception cref="InvalidPriorityQueueHandleException">if the handle is invalid for this queue</exception>
/// <param name="handle">The reference into the heap</param>
/// <returns></returns>
public T this[IPriorityQueueHandle<T> handle]
{
get
{
int cell;
bool isfirst;
checkHandle(handle, out cell, out isfirst);
return isfirst ? heap[cell].first : heap[cell].last;
}
set
{
Replace(handle, value);
}
}
/// <summary>
/// Check safely if a handle is valid for this queue and if so, report the corresponding queue item.
/// </summary>
/// <param name="handle">The handle to check</param>
/// <param name="item">If the handle is valid this will contain the corresponding item on output.</param>
/// <returns>True if the handle is valid.</returns>
public bool Find(IPriorityQueueHandle<T> handle, out T item)
{
Handle myhandle = handle as Handle;
if (myhandle == null)
{
item = default(T);
return false;
}
int toremove = myhandle.index;
int cell = toremove / 2;
bool isfirst = toremove % 2 == 0;
{
if (toremove == -1 || toremove >= size)
{
item = default(T);
return false;
}
Handle actualhandle = isfirst ? heap[cell].firsthandle : heap[cell].lasthandle;
if (actualhandle != myhandle)
{
item = default(T);
return false;
}
}
item = isfirst ? heap[cell].first : heap[cell].last;
return true;
}
/// <summary>
/// Add an item to the priority queue, receiving a
/// handle for the item in the queue,
/// or reusing an already existing handle.
/// </summary>
/// <param name="handle">On output: a handle for the added item.
/// On input: null for allocating a new handle, an invalid handle for reuse.
/// A handle for reuse must be compatible with this priority queue,
/// by being created by a priority queue of the same runtime type, but not
/// necessarily the same priority queue object.</param>
/// <param name="item">The item to add.</param>
/// <returns>True since item will always be added unless the call throws an exception.</returns>
public bool Add(ref IPriorityQueueHandle<T> handle, T item)
{
stamp++;
Handle myhandle = (Handle)handle;
if (myhandle == null)
handle = myhandle = new Handle();
else
if (myhandle.index != -1)
throw new InvalidPriorityQueueHandleException("Handle not valid for reuse");
if (add(myhandle, item))
{
raiseItemsAdded(item, 1);
raiseCollectionChanged();
return true;
}
return false;
}
/// <summary>
/// Delete an item with a handle from a priority queue.
/// </summary>
/// <exception cref="InvalidPriorityQueueHandleException">if the handle is invalid</exception>
/// <param name="handle">The handle for the item. The handle will be invalidated, but reusable.</param>
/// <returns>The deleted item</returns>
public T Delete(IPriorityQueueHandle<T> handle)
{
stamp++;
int cell;
bool isfirst;
Handle myhandle = checkHandle(handle, out cell, out isfirst);
T retval;
myhandle.index = -1;
int lastcell = (size - 1) / 2;
if (cell == lastcell)
{
if (isfirst)
{
retval = heap[cell].first;
if (size % 2 == 0)
{
updateFirst(cell, heap[cell].last, heap[cell].lasthandle);
heap[cell].last = default(T);
heap[cell].lasthandle = null;
}
else
{
heap[cell].first = default(T);
heap[cell].firsthandle = null;
}
}
else
{
retval = heap[cell].last;
heap[cell].last = default(T);
heap[cell].lasthandle = null;
}
size--;
}
else if (isfirst)
{
retval = heap[cell].first;
if (size % 2 == 0)
{
updateFirst(cell, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default(T);
heap[lastcell].lasthandle = null;
}
else
{
updateFirst(cell, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default(T);
heap[lastcell].firsthandle = null;
}
size--;
if (heapifyMin(cell))
bubbleUpMax(cell);
else
bubbleUpMin(cell);
}
else
{
retval = heap[cell].last;
if (size % 2 == 0)
{
updateLast(cell, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default(T);
heap[lastcell].lasthandle = null;
}
else
{
updateLast(cell, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default(T);
heap[lastcell].firsthandle = null;
}
size--;
if (heapifyMax(cell))
bubbleUpMin(cell);
else
bubbleUpMax(cell);
}
raiseItemsRemoved(retval, 1);
raiseCollectionChanged();
return retval;
}
private Handle checkHandle(IPriorityQueueHandle<T> handle, out int cell, out bool isfirst)
{
Handle myhandle = (Handle)handle;
int toremove = myhandle.index;
cell = toremove / 2;
isfirst = toremove % 2 == 0;
{
if (toremove == -1 || toremove >= size)
throw new InvalidPriorityQueueHandleException("Invalid handle, index out of range");
Handle actualhandle = isfirst ? heap[cell].firsthandle : heap[cell].lasthandle;
if (actualhandle != myhandle)
throw new InvalidPriorityQueueHandleException("Invalid handle, doesn't match queue");
}
return myhandle;
}
/// <summary>
/// Replace an item with a handle in a priority queue with a new item.
/// Typically used for changing the priority of some queued object.
/// </summary>
/// <param name="handle">The handle for the old item</param>
/// <param name="item">The new item</param>
/// <returns>The old item</returns>
public T Replace(IPriorityQueueHandle<T> handle, T item)
{
stamp++;
int cell;
bool isfirst;
checkHandle(handle, out cell, out isfirst);
if (size == 0)
throw new NoSuchItemException();
T retval;
if (isfirst)
{
retval = heap[cell].first;
heap[cell].first = item;
if (size == 1)
{
}
else if (size == 2 * cell + 1) // cell == lastcell
{
int p = (cell + 1) / 2 - 1;
if (comparer.Compare(item, heap[p].last) > 0)
{
Handle thehandle = heap[cell].firsthandle;
updateFirst(cell, heap[p].last, heap[p].lasthandle);
updateLast(p, item, thehandle);
bubbleUpMax(p);
}
else
bubbleUpMin(cell);
}
else if (heapifyMin(cell))
bubbleUpMax(cell);
else
bubbleUpMin(cell);
}
else
{
retval = heap[cell].last;
heap[cell].last = item;
if (heapifyMax(cell))
bubbleUpMin(cell);
else
bubbleUpMax(cell);
}
raiseItemsRemoved(retval, 1);
raiseItemsAdded(item, 1);
raiseCollectionChanged();
return retval;
}
/// <summary>
/// Find the current least item of this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the item.</param>
/// <returns>The least item.</returns>
public T FindMin(out IPriorityQueueHandle<T> handle)
{
if (size == 0)
throw new NoSuchItemException();
handle = heap[0].firsthandle;
return heap[0].first;
}
/// <summary>
/// Find the current largest item of this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the item.</param>
/// <returns>The largest item.</returns>
public T FindMax(out IPriorityQueueHandle<T> handle)
{
if (size == 0)
throw new NoSuchItemException();
else if (size == 1)
{
handle = heap[0].firsthandle;
return heap[0].first;
}
else
{
handle = heap[0].lasthandle;
return heap[0].last;
}
}
/// <summary>
/// Remove the least item from this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the removed item.</param>
/// <returns>The removed item.</returns>
public T DeleteMin(out IPriorityQueueHandle<T> handle)
{
stamp++;
if (size == 0)
throw new NoSuchItemException();
T retval = heap[0].first;
Handle myhandle = heap[0].firsthandle;
handle = myhandle;
if (myhandle != null)
myhandle.index = -1;
if (size == 1)
{
size = 0;
heap[0].first = default(T);
heap[0].firsthandle = null;
}
else
{
int lastcell = (size - 1) / 2;
if (size % 2 == 0)
{
updateFirst(0, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default(T);
heap[lastcell].lasthandle = null;
}
else
{
updateFirst(0, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default(T);
heap[lastcell].firsthandle = null;
}
size--;
heapifyMin(0);
}
raiseItemsRemoved(retval, 1);
raiseCollectionChanged();
return retval;
}
/// <summary>
/// Remove the largest item from this priority queue.
/// </summary>
/// <param name="handle">On return: the handle of the removed item.</param>
/// <returns>The removed item.</returns>
public T DeleteMax(out IPriorityQueueHandle<T> handle)
{
stamp++;
if (size == 0)
throw new NoSuchItemException();
T retval;
Handle myhandle;
if (size == 1)
{
size = 0;
retval = heap[0].first;
myhandle = heap[0].firsthandle;
if (myhandle != null)
myhandle.index = -1;
heap[0].first = default(T);
heap[0].firsthandle = null;
}
else
{
retval = heap[0].last;
myhandle = heap[0].lasthandle;
if (myhandle != null)
myhandle.index = -1;
int lastcell = (size - 1) / 2;
if (size % 2 == 0)
{
updateLast(0, heap[lastcell].last, heap[lastcell].lasthandle);
heap[lastcell].last = default(T);
heap[lastcell].lasthandle = null;
}
else
{
updateLast(0, heap[lastcell].first, heap[lastcell].firsthandle);
heap[lastcell].first = default(T);
heap[lastcell].firsthandle = null;
}
size--;
heapifyMax(0);
}
raiseItemsRemoved(retval, 1);
raiseCollectionChanged();
handle = myhandle;
return retval;
}
#endregion
#region ICloneable Members
/// <summary>
/// Make a shallow copy of this IntervalHeap.
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
IntervalHeap<T> clone = new IntervalHeap<T>(size, comparer, itemequalityComparer);
clone.AddAll(this);
return clone;
}
#endregion
}
}
| |
using System;
using NUnit.Framework;
using Whois.Parsers;
namespace Whois.Parsing.Whois.Cctld.Uz.Uz
{
[TestFixture]
public class UzParsingTests : ParsingTests
{
private WhoisParser parser;
[SetUp]
public void SetUp()
{
SerilogConfig.Init();
parser = new WhoisParser();
}
[Test]
public void Test_reserved()
{
var sample = SampleReader.Read("whois.cctld.uz", "uz", "reserved.txt");
var response = parser.Parse("whois.cctld.uz", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Reserved, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cctld.uz/uz/Reserved", response.TemplateName);
Assert.AreEqual("cctld.uz", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("UZINFOCOM", response.Registrar.Name);
Assert.AreEqual("http://www.cctld.uz/", response.Registrar.Url);
Assert.AreEqual("www.whois.uz", response.Registrar.WhoisServer.Value);
Assert.AreEqual(new DateTime(2005, 5, 1, 0, 0, 0), response.Updated);
Assert.AreEqual(new DateTime(2005, 5, 1, 0, 0, 0), response.Registered);
// Registrant Details
Assert.AreEqual("Rakhimov D. K. (info [at] uzinfocom.uz)", response.Registrant.Name);
Assert.AreEqual("not.defined.", response.Registrant.Organization);
// Registrant Address
Assert.AreEqual(4, response.Registrant.Address.Count);
Assert.AreEqual("A.Navoi str., 28 B", response.Registrant.Address[0]);
Assert.AreEqual("Tashkent", response.Registrant.Address[1]);
Assert.AreEqual("Uzbekistan, 100011", response.Registrant.Address[2]);
Assert.AreEqual("UZ", response.Registrant.Address[3]);
Assert.AreEqual("+998 71 238-42-00", response.Registrant.TelephoneNumber);
Assert.AreEqual("+998 71 238-42-48", response.Registrant.FaxNumber);
// AdminContact Details
Assert.AreEqual("Djuraev I.D. (info [at] uzinfocom.uz)", response.AdminContact.Name);
Assert.AreEqual("Center UZINFOCOM", response.AdminContact.Organization);
// AdminContact Address
Assert.AreEqual(4, response.AdminContact.Address.Count);
Assert.AreEqual("A.Navoi str., 28 B", response.AdminContact.Address[0]);
Assert.AreEqual("Tashkent", response.AdminContact.Address[1]);
Assert.AreEqual("Uzbekistan, 100011", response.AdminContact.Address[2]);
Assert.AreEqual("UZ", response.AdminContact.Address[3]);
Assert.AreEqual("+998 71 238-41-48", response.AdminContact.TelephoneNumber);
Assert.AreEqual("+998 71 238-42-48", response.AdminContact.FaxNumber);
// BillingContact Details
Assert.AreEqual("Karnaushevskaya A.K. (info [at] uzinfocom.uz)", response.BillingContact.Name);
Assert.AreEqual("Center UZINFOCOM", response.BillingContact.Organization);
// BillingContact Address
Assert.AreEqual(4, response.BillingContact.Address.Count);
Assert.AreEqual("A.Navoi str., 28 B", response.BillingContact.Address[0]);
Assert.AreEqual("Tashkent", response.BillingContact.Address[1]);
Assert.AreEqual("Uzbekistan, 100011", response.BillingContact.Address[2]);
Assert.AreEqual("UZ", response.BillingContact.Address[3]);
Assert.AreEqual("+998 71 238-42-00", response.BillingContact.TelephoneNumber);
Assert.AreEqual("+998 71 238-42-48", response.BillingContact.FaxNumber);
// TechnicalContact Details
Assert.AreEqual("Deykhin V.V. (info [at] uzinfocom.uz)", response.TechnicalContact.Name);
Assert.AreEqual("Center UZINFOCOM", response.TechnicalContact.Organization);
// TechnicalContact Address
Assert.AreEqual(4, response.TechnicalContact.Address.Count);
Assert.AreEqual("A.Navoi str., 28 B", response.TechnicalContact.Address[0]);
Assert.AreEqual("Tashkent", response.TechnicalContact.Address[1]);
Assert.AreEqual("Uzbekistan, 100011", response.TechnicalContact.Address[2]);
Assert.AreEqual("UZ", response.TechnicalContact.Address[3]);
Assert.AreEqual("+998 71 238-42-45", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("+998 71 238-42-48", response.TechnicalContact.FaxNumber);
// Nameservers
Assert.AreEqual(2, response.NameServers.Count);
Assert.AreEqual("ns.uz", response.NameServers[0]);
Assert.AreEqual("ns2.uz", response.NameServers[1]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("RESERVED", response.DomainStatus[0]);
Assert.AreEqual(42, response.FieldsParsed);
AssertWriter.Write(response);
}
[Test]
public void Test_not_found()
{
var sample = SampleReader.Read("whois.cctld.uz", "uz", "not_found.txt");
var response = parser.Parse("whois.cctld.uz", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.NotFound, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cctld.uz/uz/NotFound", response.TemplateName);
Assert.AreEqual("u34jedzcq.uz", response.DomainName.ToString());
Assert.AreEqual(2, response.FieldsParsed);
}
[Test]
public void Test_found_status_registered()
{
var sample = SampleReader.Read("whois.cctld.uz", "uz", "found_status_registered.txt");
var response = parser.Parse("whois.cctld.uz", sample);
Assert.Greater(sample.Length, 0);
Assert.AreEqual(WhoisStatus.Found, response.Status);
Assert.AreEqual(0, response.ParsingErrors);
Assert.AreEqual("whois.cctld.uz/uz/Found", response.TemplateName);
Assert.AreEqual("google.uz", response.DomainName.ToString());
// Registrar Details
Assert.AreEqual("TOMAS", response.Registrar.Name);
Assert.AreEqual("http://www.cctld.uz/", response.Registrar.Url);
Assert.AreEqual("www.whois.uz", response.Registrar.WhoisServer.Value);
Assert.AreEqual(new DateTime(2010, 3, 26, 0, 0, 0), response.Updated);
Assert.AreEqual(new DateTime(2006, 4, 13, 0, 0, 0), response.Registered);
Assert.AreEqual(new DateTime(2011, 5, 1, 0, 0, 0), response.Expiration);
// Registrant Details
Assert.AreEqual("DNS Admin (dns-admin [at] google.com)", response.Registrant.Name);
Assert.AreEqual("Google Inc", response.Registrant.Organization);
// Registrant Address
Assert.AreEqual(4, response.Registrant.Address.Count);
Assert.AreEqual("2400 E Bayshore Pkwy", response.Registrant.Address[0]);
Assert.AreEqual("Mountain View", response.Registrant.Address[1]);
Assert.AreEqual("US, 94043", response.Registrant.Address[2]);
Assert.AreEqual("US", response.Registrant.Address[3]);
Assert.AreEqual("+1 6503300100", response.Registrant.TelephoneNumber);
Assert.AreEqual("+1 6506181499", response.Registrant.FaxNumber);
// AdminContact Details
Assert.AreEqual("DNS Admin (dns-admin [at] google.com)", response.AdminContact.Name);
Assert.AreEqual("Google Inc", response.AdminContact.Organization);
// AdminContact Address
Assert.AreEqual(4, response.AdminContact.Address.Count);
Assert.AreEqual("2400 E Bayshore Pkwy", response.AdminContact.Address[0]);
Assert.AreEqual("Mountain View", response.AdminContact.Address[1]);
Assert.AreEqual("US, 94043", response.AdminContact.Address[2]);
Assert.AreEqual("US", response.AdminContact.Address[3]);
Assert.AreEqual("+1 6503300100", response.AdminContact.TelephoneNumber);
Assert.AreEqual("+1 6506181499", response.AdminContact.FaxNumber);
// BillingContact Details
Assert.AreEqual("Kevin Pearl (ccops [at] markmonitor.com)", response.BillingContact.Name);
Assert.AreEqual("MarkMonitor", response.BillingContact.Organization);
// BillingContact Address
Assert.AreEqual(4, response.BillingContact.Address.Count);
Assert.AreEqual("10400 Overland Road PMB 155", response.BillingContact.Address[0]);
Assert.AreEqual("Boise", response.BillingContact.Address[1]);
Assert.AreEqual("US, 83709", response.BillingContact.Address[2]);
Assert.AreEqual("US", response.BillingContact.Address[3]);
Assert.AreEqual("+1 208 389 5798", response.BillingContact.TelephoneNumber);
Assert.AreEqual("+1 208 389 5771", response.BillingContact.FaxNumber);
// TechnicalContact Details
Assert.AreEqual("DNS Admin (dns-admin [at] google.com)", response.TechnicalContact.Name);
Assert.AreEqual("Google Inc", response.TechnicalContact.Organization);
// TechnicalContact Address
Assert.AreEqual(4, response.TechnicalContact.Address.Count);
Assert.AreEqual("2400 E Bayshore Pkwy", response.TechnicalContact.Address[0]);
Assert.AreEqual("Mountain View", response.TechnicalContact.Address[1]);
Assert.AreEqual("US, 94043", response.TechnicalContact.Address[2]);
Assert.AreEqual("US", response.TechnicalContact.Address[3]);
Assert.AreEqual("+1 6503300100", response.TechnicalContact.TelephoneNumber);
Assert.AreEqual("+1 6506181499", response.TechnicalContact.FaxNumber);
// Nameservers
Assert.AreEqual(2, response.NameServers.Count);
Assert.AreEqual("ns1.google.com", response.NameServers[0]);
Assert.AreEqual("ns2.google.com", response.NameServers[1]);
// Domain Status
Assert.AreEqual(1, response.DomainStatus.Count);
Assert.AreEqual("ACTIVE", response.DomainStatus[0]);
Assert.AreEqual(43, response.FieldsParsed);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stride.Core.Mathematics;
namespace StrideToolkit.Mathematics
{
/// <summary>
/// A collection of easing functions.
/// </summary>
/// <remarks>
/// These easing functions are based on Robert Penner's easing functions in C# http://www.robertpenner.com/easing/
/// </remarks>
public static partial class Easing
{
/// <summary>
/// Performs easing using the specified function.
/// </summary>
/// <param name="amount">The amount.</param>
/// <param name="function">The easing function to use.</param>
/// <returns>The amount eased using the specified function.</returns>
public static float Ease(float amount, EasingFunction function)
{
switch (function)
{
default:
case EasingFunction.Linear: return Linear(amount);
case EasingFunction.QuadraticEaseOut: return QuadraticEaseOut(amount);
case EasingFunction.QuadraticEaseIn: return QuadraticEaseIn(amount);
case EasingFunction.QuadraticEaseInOut: return QuadraticEaseInOut(amount);
case EasingFunction.CubicEaseIn: return CubicEaseIn(amount);
case EasingFunction.CubicEaseOut: return CubicEaseOut(amount);
case EasingFunction.CubicEaseInOut: return CubicEaseInOut(amount);
case EasingFunction.QuarticEaseIn: return QuarticEaseIn(amount);
case EasingFunction.QuarticEaseOut: return QuarticEaseOut(amount);
case EasingFunction.QuarticEaseInOut: return QuarticEaseInOut(amount);
case EasingFunction.QuinticEaseIn: return QuinticEaseIn(amount);
case EasingFunction.QuinticEaseOut: return QuinticEaseOut(amount);
case EasingFunction.QuinticEaseInOut: return QuinticEaseInOut(amount);
case EasingFunction.SineEaseIn: return SineEaseIn(amount);
case EasingFunction.SineEaseOut: return SineEaseOut(amount);
case EasingFunction.SineEaseInOut: return SineEaseInOut(amount);
case EasingFunction.CircularEaseIn: return CircularEaseIn(amount);
case EasingFunction.CircularEaseOut: return CircularEaseOut(amount);
case EasingFunction.CircularEaseInOut: return CircularEaseInOut(amount);
case EasingFunction.ExponentialEaseIn: return ExponentialEaseIn(amount);
case EasingFunction.ExponentialEaseOut: return ExponentialEaseOut(amount);
case EasingFunction.ExponentialEaseInOut: return ExponentialEaseInOut(amount);
case EasingFunction.ElasticEaseIn: return ElasticEaseIn(amount);
case EasingFunction.ElasticEaseOut: return ElasticEaseOut(amount);
case EasingFunction.ElasticEaseInOut: return ElasticEaseInOut(amount);
case EasingFunction.BackEaseIn: return BackEaseIn(amount);
case EasingFunction.BackEaseOut: return BackEaseOut(amount);
case EasingFunction.BackEaseInOut: return BackEaseInOut(amount);
case EasingFunction.BounceEaseIn: return BounceEaseIn(amount);
case EasingFunction.BounceEaseOut: return BounceEaseOut(amount);
case EasingFunction.BounceEaseInOut: return BounceEaseInOut(amount);
}
}
/// <summary>
/// Performs a linear easing.
/// </summary>
/// <param name="amount">The amount.</param>
/// <returns>The amount eased.</returns>
/// <remarks>
/// Modeled after the line y = x
/// </remarks>
public static float Linear(float amount)
{
return amount;
}
/// <remarks>
/// Modeled after the parabola y = x^2
/// </remarks>
public static float QuadraticEaseIn(float amount)
{
return amount * amount;
}
/// <remarks>
/// Modeled after the parabola y = -x^2 + 2x
/// </remarks>
public static float QuadraticEaseOut(float amount)
{
return -(amount * (amount - 2));
}
/// <remarks>
/// Modeled after the piecewise quadratic
/// y = (1/2)((2x)^2) ; [0, 0.5]
/// y = -(1/2)((2x-1)*(2x-3) - 1) ; [0.5, 1]
/// </remarks>
public static float QuadraticEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 2 * amount * amount;
}
else
{
return (-2 * amount * amount) + (4 * amount) - 1;
}
}
/// <remarks>
/// Modeled after the cubic y = x^3
/// </remarks>
public static float CubicEaseIn(float amount)
{
return amount * amount * amount;
}
/// <remarks>
/// Modeled after the cubic y = (x - 1)^3 + 1
/// </remarks>
public static float CubicEaseOut(float amount)
{
float f = (amount - 1);
return f * f * f + 1;
}
/// <remarks>
/// Modeled after the piecewise cubic
/// y = (1/2)((2x)^3) ; [0, 0.5]
/// y = (1/2)((2x-2)^3 + 2) ; [0.5, 1]
/// </remarks>
public static float CubicEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 4 * amount * amount * amount;
}
else
{
float f = ((2 * amount) - 2);
return 0.5f * f * f * f + 1;
}
}
/// <remarks>
/// Modeled after the quartic x^4
/// </remarks>
public static float QuarticEaseIn(float amount)
{
return amount * amount * amount * amount;
}
/// <remarks>
/// Modeled after the quartic y = 1 - (x - 1)^4
/// </remarks>
public static float QuarticEaseOut(float amount)
{
float f = (amount - 1);
return f * f * f * (1 - amount) + 1;
}
/// <remarks>
/// Modeled after the piecewise quartic
/// y = (1/2)((2x)^4) ; [0, 0.5]
/// y = -(1/2)((2x-2)^4 - 2) ; [0.5, 1]
/// </remarks>
public static float QuarticEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 8 * amount * amount * amount * amount;
}
else
{
float f = (amount - 1);
return -8 * f * f * f * f + 1;
}
}
/// <remarks>
/// Modeled after the quintic y = x^5
/// </remarks>
public static float QuinticEaseIn(float amount)
{
return amount * amount * amount * amount * amount;
}
/// <remarks>
/// Modeled after the quintic y = (x - 1)^5 + 1
/// </remarks>
public static float QuinticEaseOut(float amount)
{
float f = (amount - 1);
return f * f * f * f * f + 1;
}
/// <remarks>
/// Modeled after the piecewise quintic
/// y = (1/2)((2x)^5) ; [0, 0.5]
/// y = (1/2)((2x-2)^5 + 2) ; [0.5, 1]
/// </remarks>
public static float QuinticEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 16 * amount * amount * amount * amount * amount;
}
else
{
float f = ((2 * amount) - 2);
return 0.5f * f * f * f * f * f + 1;
}
}
/// <remarks>
/// Modeled after quarter-cycle of sine wave
/// </remarks>
public static float SineEaseIn(float amount)
{
return (float)Math.Sin((amount - 1) * MathUtil.PiOverTwo) + 1;
}
/// <remarks>
/// Modeled after quarter-cycle of sine wave (different phase)
/// </remarks>
public static float SineEaseOut(float amount)
{
return (float)Math.Sin(amount * MathUtil.PiOverTwo);
}
/// <remarks>
/// Modeled after half sine wave
/// </remarks>
public static float SineEaseInOut(float amount)
{
return 0.5f * (1 - (float)Math.Cos(amount * MathUtil.Pi));
}
/// <remarks>
/// Modeled after shifted quadrant IV of unit circle
/// </remarks>
public static float CircularEaseIn(float amount)
{
return 1 - (float)Math.Sqrt(1 - (amount * amount));
}
/// <remarks>
/// Modeled after shifted quadrant II of unit circle
/// </remarks>
public static float CircularEaseOut(float amount)
{
return (float)Math.Sqrt((2 - amount) * amount);
}
/// <remarks>
/// Modeled after the piecewise circular function
/// y = (1/2)(1 - Math.Sqrt(1 - 4x^2)) ; [0, 0.5]
/// y = (1/2)(Math.Sqrt(-(2x - 3)*(2x - 1)) + 1) ; [0.5, 1]
/// </remarks>
public static float CircularEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 0.5f * (1 - (float)Math.Sqrt(1 - 4 * (amount * amount)));
}
else
{
return 0.5f * ((float)Math.Sqrt(-((2 * amount) - 3) * ((2 * amount) - 1)) + 1);
}
}
/// <remarks>
/// Modeled after the exponential function y = 2^(10(x - 1))
/// </remarks>
public static float ExponentialEaseIn(float amount)
{
return (amount == 0.0f) ? amount : (float)Math.Pow(2, 10 * (amount - 1));
}
/// <remarks>
/// Modeled after the exponential function y = -2^(-10x) + 1
/// </remarks>
public static float ExponentialEaseOut(float amount)
{
return (amount == 1.0f) ? amount : 1 - (float)Math.Pow(2, -10 * amount);
}
/// <remarks>
/// Modeled after the piecewise exponential
/// y = (1/2)2^(10(2x - 1)) ; [0,0.5]
/// y = -(1/2)*2^(-10(2x - 1))) + 1 ; [0.5,1]
/// </remarks>
public static float ExponentialEaseInOut(float amount)
{
if (amount == 0.0 || amount == 1.0) return amount;
if (amount < 0.5f)
{
return 0.5f * (float)Math.Pow(2, (20 * amount) - 10);
}
else
{
return -0.5f * (float)Math.Pow(2, (-20 * amount) + 10) + 1;
}
}
/// <remarks>
/// Modeled after the damped sine wave y = sin(13pi/2*x)*Math.Pow(2, 10 * (x - 1))
/// </remarks>
public static float ElasticEaseIn(float amount)
{
return (float)Math.Sin(13 * MathUtil.PiOverTwo * amount) * (float)Math.Pow(2, 10 * (amount - 1));
}
/// <remarks>
/// Modeled after the damped sine wave y = sin(-13pi/2*(x + 1))*Math.Pow(2, -10x) + 1
/// </remarks>
public static float ElasticEaseOut(float amount)
{
return (float)Math.Sin(-13 * MathUtil.PiOverTwo * (amount + 1)) * (float)Math.Pow(2, -10 * amount) + 1;
}
/// <remarks>
/// Modeled after the piecewise exponentially-damped sine wave:
/// y = (1/2)*sin(13pi/2*(2*x))*Math.Pow(2, 10 * ((2*x) - 1)) ; [0,0.5]
/// y = (1/2)*(sin(-13pi/2*((2x-1)+1))*Math.Pow(2,-10(2*x-1)) + 2) ; [0.5, 1]
/// </remarks>
public static float ElasticEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 0.5f * (float)Math.Sin(13 * MathUtil.PiOverTwo * (2 * amount)) * (float)Math.Pow(2, 10 * ((2 * amount) - 1));
}
else
{
return 0.5f * ((float)Math.Sin(-13 * MathUtil.PiOverTwo * ((2 * amount - 1) + 1)) * (float)Math.Pow(2, -10 * (2 * amount - 1)) + 2);
}
}
/// <remarks>
/// Modeled after the overshooting cubic y = x^3-x*sin(x*pi)
/// </remarks>
public static float BackEaseIn(float amount)
{
return amount * amount * amount - amount * (float)Math.Sin(amount * MathUtil.Pi);
}
/// <remarks>
/// Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi))
/// </remarks>
public static float BackEaseOut(float amount)
{
float f = (1 - amount);
return 1 - (f * f * f - f * (float)Math.Sin(f * MathUtil.Pi));
}
/// <remarks>
/// Modeled after the piecewise overshooting cubic function:
/// y = (1/2)*((2x)^3-(2x)*sin(2*x*pi)) ; [0, 0.5]
/// y = (1/2)*(1-((1-x)^3-(1-x)*sin((1-x)*pi))+1) ; [0.5, 1]
/// </remarks>
public static float BackEaseInOut(float amount)
{
if (amount < 0.5f)
{
float f = 2 * amount;
return 0.5f * (f * f * f - f * (float)Math.Sin(f * MathUtil.Pi));
}
else
{
float f = (1 - (2 * amount - 1));
return 0.5f * (1 - (f * f * f - f * (float)Math.Sin(f * MathUtil.Pi))) + 0.5f;
}
}
/// <remarks>
/// </remarks>
public static float BounceEaseIn(float amount)
{
return 1 - BounceEaseOut(1 - amount);
}
/// <remarks>
/// </remarks>
public static float BounceEaseOut(float amount)
{
if (amount < 4 / 11.0f)
{
return (121 * amount * amount) / 16.0f;
}
else if (amount < 8 / 11.0f)
{
return (363 / 40.0f * amount * amount) - (99 / 10.0f * amount) + 17 / 5.0f;
}
else if (amount < 9 / 10.0f)
{
return (4356 / 361.0f * amount * amount) - (35442 / 1805.0f * amount) + 16061 / 1805.0f;
}
else
{
return (54 / 5.0f * amount * amount) - (513 / 25.0f * amount) + 268 / 25.0f;
}
}
/// <remarks>
/// </remarks>
public static float BounceEaseInOut(float amount)
{
if (amount < 0.5f)
{
return 0.5f * BounceEaseIn(amount * 2);
}
else
{
return 0.5f * BounceEaseOut(amount * 2 - 1) + 0.5f;
}
}
}
}
| |
/*******************************************************************************
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved.
*******************************************************************************/
using UnityEngine;
using System.Collections;
using RSUnityToolkit;
public class CameraARCalibation : MonoBehaviour
{
#region Public Fields
public Camera CameraObj = null;
public float MaxDepthThreshold = 65;
#endregion
#region Private Fields
private bool init = false;
private float[] _depthArray = null;
#endregion
// Use this for initialization
void Start ()
{
if ( CameraObj == null )
{
CameraObj = this.gameObject.camera;
}
}
void OnEnable()
{
if (SenseToolkitManager.Instance != null)
{
SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.VideoDepthStream);
SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.VideoColorStream);
init = true;
}
}
void OnDisable()
{
SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.VideoDepthStream);
SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.VideoColorStream);
}
// Update is called once per frame
void Update ()
{
if (!init)
{
OnEnable();
}
if (SenseToolkitManager.Instance.Initialized &&
SenseToolkitManager.Instance.ImageRgbOutput != null &&
SenseToolkitManager.Instance.ImageDepthOutput != null)
{
PXCMImage.ImageData depthData;
int width = SenseToolkitManager.Instance.ImageDepthOutput.info.width;
int height = SenseToolkitManager.Instance.ImageDepthOutput.info.height;
// 1. Get the depth image
SenseToolkitManager.Instance.ImageDepthOutput.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_DEPTH_F32, out depthData);
if (_depthArray == null)
{
_depthArray = new float[width * height];
}
depthData.ToFloatArray(0,_depthArray);
PXCMPoint3DF32[] pos_uvz = new PXCMPoint3DF32[1]{new PXCMPoint3DF32(){x = 0, y= 0 , z = 0}};
// 2. Find a "good" pixel (not too far)
int x = width / 4;
int y = height / 4;
int xx = 5;
int yy = 5;
while (pos_uvz[0].z == 0 || (pos_uvz[0].z / 10) > MaxDepthThreshold)
{
x += xx;
if ( x >= 3 * width / 4 )
{
x = width / 4 ;
y += yy;
if (y >= 3 * height / 4)
{
SenseToolkitManager.Instance.ImageDepthOutput.ReleaseAccess(depthData);
return;
}
}
pos_uvz[0].x = x;
pos_uvz[0].y = y;
pos_uvz[0].z = _depthArray[x + y * width];
}
SenseToolkitManager.Instance.ImageDepthOutput.ReleaseAccess(depthData);
// 3. Projet it to the color image
PXCMPointF32[] pos_ij = new PXCMPointF32[1]{new PXCMPointF32()};
var sts = SenseToolkitManager.Instance.Projection.MapDepthToColor( pos_uvz, pos_ij);
if (sts < pxcmStatus.PXCM_STATUS_NO_ERROR)
{
return;
}
// 4. Project it to the Real World coordinates
PXCMPoint3DF32[] pos3d = new PXCMPoint3DF32[1]{new PXCMPoint3DF32()};
sts = SenseToolkitManager.Instance.Projection.ProjectDepthToCamera( pos_uvz, pos3d );
pos3d[0].x /= -10;
pos3d[0].y /= 10;
pos3d[0].z /= 10;
if (sts < pxcmStatus.PXCM_STATUS_NO_ERROR || pos3d[0].x == 0 || pos3d[0].y == 0)
{
return;
}
Vector3 vec = new Vector3();
vec.x = pos3d[0].x;
vec.y = pos3d[0].y;
vec.z = pos3d[0].z;
// 5. Normalize the color pixel location
Vector3 vecScreen = new Vector3();
vecScreen.x = (SenseToolkitManager.Instance.ImageRgbOutput.info.width - pos_ij[0].x) / SenseToolkitManager.Instance.ImageRgbOutput.info.width;
vecScreen.y = (SenseToolkitManager.Instance.ImageRgbOutput.info.height - pos_ij[0].y) / SenseToolkitManager.Instance.ImageRgbOutput.info.height;
// 6. Calibrate the world point to the screen point
Calibrate(vec, vecScreen);
}
}
/// <summary>
/// Calibrate the CameraObj so the worldPoint and the screenPoint are aligned
/// </summary>
/// <param name='worldPoint'>
/// World point.
/// </param>
/// <param name='screenPoint'>
/// Screen point.
/// </param>
public void Calibrate(Vector3 worldPoint, Vector2 screenPoint)
{
screenPoint.x = screenPoint.x * CameraObj.pixelWidth;
screenPoint.y = screenPoint.y * CameraObj.pixelHeight;
Vector3 calculatedScreenPoint = CameraObj.WorldToScreenPoint(worldPoint);
//Calibrate X axis
int safetyCounter = 0;
while (Mathf.Abs(calculatedScreenPoint.x - screenPoint.x) > 1f)
{
if (calculatedScreenPoint.x > screenPoint.x)
{
Vector3 pos = CameraObj.transform.position;
pos.x+= 1 - screenPoint.x/calculatedScreenPoint.x;
CameraObj.transform.position = pos;
}
else
{
Vector3 pos = CameraObj.transform.position;
pos.x-= 1 - calculatedScreenPoint.x/screenPoint.x;
CameraObj.transform.position = pos;
}
calculatedScreenPoint = CameraObj.WorldToScreenPoint(worldPoint);
safetyCounter++;
if (safetyCounter>100)
{
return;
}
}
//Calibrate Y axis
safetyCounter = 0;
while (Mathf.Abs(calculatedScreenPoint.y - screenPoint.y) > 1f)
{
if (calculatedScreenPoint.y > screenPoint.y)
{
Vector3 pos = CameraObj.transform.position;
pos.y+= 1 - screenPoint.y/calculatedScreenPoint.y;
CameraObj.transform.position = pos;
}
else
{
Vector3 pos = CameraObj.transform.position;
pos.y-= 1 - calculatedScreenPoint.y/screenPoint.y;
CameraObj.transform.position = pos;
}
calculatedScreenPoint = CameraObj.WorldToScreenPoint(worldPoint);
safetyCounter++;
if (safetyCounter>100)
{
return;
}
}
// If we are done, disable this scrupt. No need to do this for every frame.
if (Mathf.Abs(calculatedScreenPoint.x - screenPoint.x) < 1f)
{
if (Mathf.Abs(calculatedScreenPoint.y - screenPoint.y) < 1f)
{
this.enabled = false;
}
}
return;
}
}
| |
//ybzuo-dena
using UnityEngine;
using System.Collections.Generic;
public enum EHitState
{
EBeforeHitBegin,
EBetweenHitBeginEnd,
EAfterHitEnd,
}
public class N2Ani
{
public N2Ani(N2AniData _data, Animation _ani, GameObject _root, Transform _ball_trans)
{
m_data = _data;
m_ani = _ani;
m_root = _root;
m_ball_trans = _ball_trans;
// m_ani_state = m_ani[m_data.base_info.name];
//
// m_num = m_data.base_info.frame;
ResetHitPosLimit();
m_current_index = 0;
if (m_data.extern_info != null)
{
for (int i = 0; i < m_data.extern_info.ball_list.Count; ++i)
{
m_ball_list.Add(m_data.extern_info.ball_list[i]);
}
for (int i = 0; i < m_data.extern_info.shift_list.Count; ++i)
{
m_shift_list.Add(m_data.extern_info.shift_list[i]);
}
}
else
{
ResetExternInfo();
}
}
void ResetExternInfo()
{
}
public void Adjust(string _ani_name)
{
// JDAniData _data = NewStaticDataExtern.GetSingle().m_AniData_dic[_ani_name];
// m_data.base_info = _data;
// ResetExternInfo();
// ResetHitPosLimit();
}
public N2AniData get_raw_data()
{
return m_data;
}
public void set_info()
{
// for (int i = 0; i < m_data.base_info.frame; ++i)
{
m_ball_list.Add(Vector3.zero);
}
}
public void ReadyToPlay(bool _imp)
{
m_imp = _imp;
}
public void bound_ball(GameObject _ball)
{
m_HitState = EHitState.EBeforeHitBegin;
m_ball = _ball;
}
public EHitState GetHitState()
{
return m_HitState;
}
public string get_name()
{
return "";//m_data.base_info.name;
}
public int get_current_index()
{
return m_current_index;
}
public int get_max_index()
{
return m_num;
}
public void update(float _dtime,float scale = 1.0f)
{
if (m_step_mode)
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
step(false);
Debug.Log("Index:" + m_current_index);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
step(true);
Debug.Log("Index:" + m_current_index);
}
}
else
{
if (m_ani_state.time + _dtime >= m_ani_state.length)
{
m_ani_state.time = m_ani_state.length;
}
//else
// m_ani_state.time += _dtime;
m_TimeDelta += _dtime;
bool needStep = false;
while (m_TimeDelta > mc_step_inv)
{
m_TimeDelta -= mc_step_inv;
step(true);
needStep = true;
}
if (!needStep)
{
m_ani_state.time += _dtime;
if (m_current_index < m_num - 1)
{
int nextIndex = m_current_index + 1;
Vector3 _bp = m_shift_list[m_current_index];
Vector3 _ep = m_shift_list[nextIndex];
float lerp = m_TimeDelta / mc_step_inv;
SetShiftPos(Vector3.Lerp(_bp, _ep, lerp));
if (m_ball!=null)
{
if (m_imp)
{
// if (m_data.base_info.ball == 1)
{
if (m_current_index >= m_hit_min && m_current_index <= m_hit_max)
{
Vector3 _bpos = m_ball_list[m_current_index];
Vector3 _epos = m_ball_list[nextIndex];
m_ball.transform.localPosition = Vector3.Lerp(_bpos, _epos, lerp);
m_ball.transform.rotation = m_ball_trans.rotation;
}
}
}
else
{
m_ball.transform.rotation = m_ball_trans.parent.rotation;
m_ball.transform.position = m_ball_trans.parent.position;
}
}
}
}
//float frameCount = m_ani_state.time / mc_step_inv;
//m_current_index = (int)frameCount - 1;
//if (m_current_index<0)
//{
// m_current_index = 0;
//}
//if (m_current_index < m_hit_min)
// m_HitState = EHitState.EBeforeHitBegin;
//else if (m_current_index >= m_hit_min && m_current_index < m_hit_max)
// m_HitState = EHitState.EBetweenHitBeginEnd;
//else
// m_HitState = EHitState.EAfterHitEnd;
//if (m_current_index < m_num - 1)
//{
// int nextIndex = m_current_index + 1;
// Vector3 _bp = m_shift_list[m_current_index];
// Vector3 _ep = m_shift_list[nextIndex];
// float timeDelta = m_ani_state.time - (int)frameCount * mc_step_inv;
// if (timeDelta < 0.0f)
// timeDelta = 0.0f;
// if (timeDelta > mc_step_inv)
// timeDelta = mc_step_inv;
// float lerp = timeDelta / mc_step_inv;
// SetShiftPos(Vector3.Lerp(_bp, _ep, lerp));
// if (m_ball != null)
// {
// if (m_imp)
// {
// if (m_data.base_info.ball == 1)
// {
// if (m_current_index >= m_hit_min && m_current_index <= m_hit_max)
// {
// Vector3 _bpos = m_ball_list[m_current_index];
// Vector3 _epos = m_ball_list[nextIndex];
// m_ball.transform.localPosition = Vector3.Lerp(_bpos, _epos, lerp);
// m_ball.transform.rotation = m_ball_trans.rotation;
// }
// }
// }
// else
// {
// m_ball.transform.rotation = m_ball_trans.parent.rotation;
// m_ball.transform.position = m_ball_trans.parent.position;
// }
// }
//}
}
}
public void ResetPosNow()
{
m_root.transform.localPosition = Vector3.zero;
}
void SetShiftPos(Vector3 _pos)
{
//Debug.Log(m_root);
if ((m_root.transform.localPosition != Vector3.zero) && (_pos == Vector3.zero))
{
Vector3 _tpos = m_root.transform.position;
_tpos.y = 0;
m_root.transform.localPosition = Vector3.zero;
m_root.transform.parent.position = _tpos;
}
else
{
m_root.transform.localPosition = _pos;
}
}
public bool GetStepMode()
{
return m_step_mode;
}
public bool step(bool forward, bool _loop = false)
{
if (forward)
{
if (m_current_index < m_num - 1)
{
m_current_index++;
m_ani_state.time = mc_step_inv * m_current_index;
if (m_ani_state.time > m_ani_state.length)
{
m_ani_state.time = m_ani_state.length;
return true;
}
}
else
{
//if ((m_data.base_info.loop == 1) || _loop)
{
m_current_index = 0;
m_ani_state.time = 0;
}
}
}
else
{
if (m_current_index > 0)
{
m_current_index--;
m_ani_state.time = mc_step_inv * m_current_index;
if (m_ani_state.time < 0.0f)
{
m_ani_state.time = 0.0f;
}
}
else
{
// if ((m_data.base_info.loop == 1) || _loop)
{
m_current_index = m_num - 1;
m_ani_state.time = mc_step_inv * m_current_index;
}
}
}
if (m_imp)
{
ResetBallPosFromData();
}
else
{
if (m_ball != null)
{
m_ball.transform.rotation = m_ball_trans.parent.rotation;
m_ball.transform.position = m_ball_trans.parent.position;
}
}
SetShiftPos(m_shift_list[m_current_index]);
return false;
}
public void reset_pos_info(Vector3 _pos)
{
m_ball_list[m_current_index] = _pos;
}
public void reset_shift_info(Vector3 _pos)
{
Vector3 _vec = _pos - m_shift_list[m_current_index];
m_shift_list[m_current_index] = _pos;
m_ball_list[m_current_index] += _vec;
ResetBallPosFromData();
}
public void QuickSetHeight()
{
if (((m_hit_min == 0) || (m_hit_min == -1)) && ((m_hit_max == m_num - 1) || (m_hit_max == -1)))
{
m_current_index = m_num / 2;
}
else if ((m_hit_min == 0) || (m_hit_min == -1))
{
m_current_index = m_hit_max;
}
else
{
m_current_index = m_hit_min;
}
m_shift_list[m_current_index] = new Vector3(m_shift_list[m_current_index].x, 3, m_shift_list[m_current_index].z);
LerpShiftPos(0);
m_current_index = 10;
ZeroShiftPos(0);
m_current_index = m_num - 11;
ZeroShiftPos(1);
}
public void ZeroShiftPos(int _mode)
{
//0 5 9
if (_mode == 0)
{
for (int i = 0; i <= m_current_index; ++i)
{
Vector3 _tpos = Vector3.zero;
Vector3 _dir = _tpos - m_shift_list[i];
m_shift_list[i] = _tpos;
m_ball_list[i] += _dir;
}
}
if (_mode == 1)
{
for (int i = m_current_index; i < m_shift_list.Count - 1; ++i)
{
Vector3 _tpos = Vector3.zero;
Vector3 _dir = _tpos - m_shift_list[i];
m_shift_list[i] = _tpos;
m_ball_list[i] += _dir;
}
}
SetShiftPos(m_shift_list[m_current_index]);
ResetBallPosFromData();
}
public void LerpShiftPos(int _mode)
{
Vector3 _cpos = m_shift_list[m_current_index];
//0 5 9
if (_mode == 0 || _mode == 1)
{
for (int i = 0; i < m_current_index; ++i)
{
Vector3 _tpos = Vector3.Lerp(Vector3.zero, _cpos, (float)i / m_current_index);
Vector3 _dir = _tpos - m_shift_list[i];
m_shift_list[i] = _tpos;
m_ball_list[i] += _dir;
}
}
if (_mode == 0 || _mode == 2)
{
for (int i = m_current_index + 1; i < m_shift_list.Count - 1; ++i)
{
Vector3 _tpos = Vector3.Lerp(_cpos, Vector3.zero, (float)(i - m_current_index) / (m_shift_list.Count - m_current_index));
Vector3 _dir = _tpos - m_shift_list[i];
m_shift_list[i] = _tpos;
m_ball_list[i] += _dir;
}
}
}
public void clone_front_pos()
{
if (m_current_index > 0)
{
m_ball_list[m_current_index] = m_ball_list[m_current_index - 1];
m_ball.transform.localPosition = m_ball_list[m_current_index];
m_ball.transform.rotation = m_ball_trans.rotation;
}
}
public void clone_front_shift()
{
if (m_current_index > 0)
{
m_shift_list[m_current_index] = m_shift_list[m_current_index - 1];
SetShiftPos(m_shift_list[m_current_index]);
}
ResetBallPosFromData();
}
void ResetBallPosFromData()
{
// if ((m_ball != null) && (m_data.base_info.ball == 1))
{
if ((m_current_index >= m_hit_min) && (m_current_index <= m_hit_max))
{
m_ball.transform.localPosition = m_ball_list[m_current_index];
m_ball.transform.rotation = m_ball_trans.rotation;
}
}
}
public void switch_step_mode(bool _mode)
{
m_step_mode = _mode;
m_ani_state.time = 0.0f;
m_TimeDelta = 0.0f;
m_current_index = 0;
m_ani_state.speed = 0.0f;
if (m_step_mode)
{
// if (m_data.base_info.ball == 1 && m_ball != null)
{
if (m_current_index < 0)
{
m_current_index = 0;
}
if (m_current_index >= m_ball_list.Count)
{
m_current_index = m_ball_list.Count - 1;
}
m_ball.transform.localPosition = m_ball_list[m_current_index];
m_ball.transform.rotation = m_ball_trans.rotation;
}
}
}
public N2AniExternInfo BuildEiInfo()
{
m_data.extern_info = new N2AniExternInfo();
// m_data.extern_info.name = m_data.base_info.name;
m_data.extern_info.pos_info = "";
m_data.extern_info.shift_info = "";
foreach (Vector3 _p in m_ball_list)
{
m_data.extern_info.pos_info += (_p.x + "," + _p.y + "," + _p.z + "|");
}
foreach (Vector3 _p in m_shift_list)
{
m_data.extern_info.shift_info += (_p.x + "," + _p.y + "," + _p.z + "|");
}
return m_data.extern_info;
}
public void set_scale(Vector3 _scale)
{
m_scale = _scale;
for (int i = 0; i < m_shift_list.Count; ++i)
{
Vector3 _temp = new Vector3();
_temp.x = m_shift_list[i].x / m_scale.x;
_temp.y = m_shift_list[i].y / m_scale.y;
_temp.z = m_shift_list[i].z / m_scale.z;
m_shift_list[i] = _temp;
}
}
public void ResetHitPosLimit()
{
}
bool m_imp = true;
int m_hit_min = 0;
int m_hit_max = 1;
GameObject m_root;
Transform m_ball_trans;
Animation m_ani;
N2AniData m_data;
AnimationState m_ani_state;
GameObject m_ball;
bool m_step_mode = false;
public const float mc_step_inv = 0.033f;
public const float mc_speed_offset = 0.1f;
int m_current_index = 0;
float m_TimeDelta = 0.0f;
int m_num = 0;
Vector3 m_scale = Vector3.one;
List<Vector3> m_ball_list = new List<Vector3>();
List<Vector3> m_shift_list = new List<Vector3>();
EHitState m_HitState = EHitState.EBeforeHitBegin;
}
| |
/*
* 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.Text;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Scripting;
using OpenSim.Region.Framework.Scenes.Serialization;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.Framework.Scenes
{
public class SceneObjectPartInventory : IEntityInventory
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private byte[] m_inventoryFileData = new byte[0];
private byte[] m_inventoryFileNameBytes = new byte[0];
private string m_inventoryFileName = "";
private uint m_inventoryFileNameSerial = 0;
private bool m_inventoryPrivileged = false;
private object m_inventoryFileLock = new object();
private Dictionary<UUID, ArrayList> m_scriptErrors = new Dictionary<UUID, ArrayList>();
/// <value>
/// The part to which the inventory belongs.
/// </value>
private SceneObjectPart m_part;
/// <summary>
/// Serial count for inventory file , used to tell if inventory has changed
/// no need for this to be part of Database backup
/// </summary>
protected uint m_inventorySerial = 0;
/// <summary>
/// Holds in memory prim inventory
/// </summary>
protected TaskInventoryDictionary m_items = new TaskInventoryDictionary();
/// <summary>
/// Tracks whether inventory has changed since the last persistent backup
/// </summary>
internal bool HasInventoryChanged;
/// <value>
/// Inventory serial number
/// </value>
protected internal uint Serial
{
get { return m_inventorySerial; }
set { m_inventorySerial = value; }
}
/// <value>
/// Raw inventory data
/// </value>
protected internal TaskInventoryDictionary Items
{
get {
return m_items;
}
set
{
m_items = value;
m_inventorySerial++;
QueryScriptStates();
}
}
public int Count
{
get
{
lock (m_items)
return m_items.Count;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="part">
/// A <see cref="SceneObjectPart"/>
/// </param>
public SceneObjectPartInventory(SceneObjectPart part)
{
m_part = part;
}
/// <summary>
/// Force the task inventory of this prim to persist at the next update sweep
/// </summary>
public void ForceInventoryPersistence()
{
HasInventoryChanged = true;
}
/// <summary>
/// Reset UUIDs for all the items in the prim's inventory.
/// </summary>
/// <remarks>
/// This involves either generating
/// new ones or setting existing UUIDs to the correct parent UUIDs.
///
/// If this method is called and there are inventory items, then we regard the inventory as having changed.
/// </remarks>
public void ResetInventoryIDs()
{
if (null == m_part)
m_items.LockItemsForWrite(true);
if (Items.Count == 0)
{
m_items.LockItemsForWrite(false);
return;
}
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
Items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ResetIDs(m_part.UUID);
Items.Add(item.ItemID, item);
}
m_items.LockItemsForWrite(false);
}
public void ResetObjectID()
{
m_items.LockItemsForWrite(true);
if (Items.Count == 0)
{
m_items.LockItemsForWrite(false);
return;
}
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
Items.Clear();
foreach (TaskInventoryItem item in items)
{
item.ParentPartID = m_part.UUID;
item.ParentID = m_part.UUID;
Items.Add(item.ItemID, item);
}
m_items.LockItemsForWrite(false);
}
/// <summary>
/// Change every item in this inventory to a new owner.
/// </summary>
/// <param name="ownerId"></param>
public void ChangeInventoryOwner(UUID ownerId)
{
List<TaskInventoryItem> items = GetInventoryItems();
if (items.Count == 0)
return;
m_items.LockItemsForWrite(true);
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
foreach (TaskInventoryItem item in items)
{
if (ownerId != item.OwnerID)
item.LastOwnerID = item.OwnerID;
item.OwnerID = ownerId;
item.PermsMask = 0;
item.PermsGranter = UUID.Zero;
item.OwnerChanged = true;
}
m_inventorySerial++;
m_items.LockItemsForWrite(false);
}
/// <summary>
/// Change every item in this inventory to a new group.
/// </summary>
/// <param name="groupID"></param>
public void ChangeInventoryGroup(UUID groupID)
{
m_items.LockItemsForWrite(true);
if (0 == Items.Count)
{
m_items.LockItemsForWrite(false);
return;
}
m_inventorySerial++;
// Don't let this set the HasGroupChanged flag for attachments
// as this happens during rez and we don't want a new asset
// for each attachment each time
if (!m_part.ParentGroup.IsAttachment)
{
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
foreach (TaskInventoryItem item in items)
{
item.GroupID = groupID;
}
m_items.LockItemsForWrite(false);
}
private void QueryScriptStates()
{
if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null)
return;
Items.LockItemsForRead(true);
foreach (TaskInventoryItem item in Items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
bool running;
if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running))
item.ScriptRunning = running;
}
}
Items.LockItemsForRead(false);
}
public bool TryGetScriptInstanceRunning(UUID itemId, out bool running)
{
running = false;
TaskInventoryItem item = GetInventoryItem(itemId);
if (item == null)
return false;
return TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running);
}
public static bool TryGetScriptInstanceRunning(Scene scene, TaskInventoryItem item, out bool running)
{
running = false;
if (item.InvType != (int)InventoryType.LSL)
return false;
IScriptModule[] engines = scene.RequestModuleInterfaces<IScriptModule>();
if (engines == null) // No engine at all
return false;
foreach (IScriptModule e in engines)
{
if (e.HasScript(item.ItemID, out running))
return true;
}
return false;
}
public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
{
int scriptsValidForStarting = 0;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
if (CreateScriptInstance(item, startParam, postOnRez, engine, stateSource))
scriptsValidForStarting++;
return scriptsValidForStarting;
}
public ArrayList GetScriptErrors(UUID itemID)
{
ArrayList ret = new ArrayList();
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
foreach (IScriptModule e in engines)
{
if (e != null)
{
ArrayList errors = e.GetScriptErrors(itemID);
foreach (Object line in errors)
ret.Add(line);
}
}
return ret;
}
/// <summary>
/// Stop and remove all the scripts in this prim.
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
{
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
m_part.RemoveScriptEvents(item.ItemID);
}
}
/// <summary>
/// Stop all the scripts in this prim.
/// </summary>
public void StopScriptInstances()
{
GetInventoryItems(InventoryType.LSL).ForEach(i => StopScriptInstance(i));
}
/// <summary>
/// Start a script which is in this prim's inventory.
/// </summary>
/// <param name="item"></param>
/// <returns>true if the script instance was created, false otherwise</returns>
public bool CreateScriptInstance(TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource)
{
// m_log.DebugFormat("[PRIM INVENTORY]: Starting script {0} {1} in prim {2} {3} in {4}",
// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item, m_part))
{
StoreScriptError(item.ItemID, "no permission");
return false;
}
m_part.AddFlag(PrimFlags.Scripted);
if (m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts)
return false;
if (stateSource == 2 && // Prim crossing
m_part.ParentGroup.Scene.m_trustBinaries)
{
m_items.LockItemsForWrite(true);
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
m_items.LockItemsForWrite(false);
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
StoreScriptErrors(item.ItemID, null);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return true;
}
AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
if (null == asset)
{
string msg = String.Format("asset ID {0} could not be found", item.AssetID);
StoreScriptError(item.ItemID, msg);
m_log.ErrorFormat(
"[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
item.Name, item.ItemID, m_part.AbsolutePosition,
m_part.ParentGroup.Scene.RegionInfo.RegionName, item.AssetID);
return false;
}
else
{
if (m_part.ParentGroup.m_savedScriptState != null)
item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
m_items.LockItemsForWrite(true);
m_items[item.ItemID].OldItemID = item.OldItemID;
m_items[item.ItemID].PermsMask = 0;
m_items[item.ItemID].PermsGranter = UUID.Zero;
m_items.LockItemsForWrite(false);
string script = Utils.BytesToString(asset.Data);
m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
StoreScriptErrors(item.ItemID, null);
if (!item.ScriptRunning)
m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
m_part.LocalId, item.ItemID);
m_part.ParentGroup.AddActiveScriptCount(1);
m_part.ScheduleFullUpdate();
return true;
}
}
private UUID RestoreSavedScriptState(UUID loadedID, UUID oldID, UUID newID)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Restoring scripted state for item {0}, oldID {1}, loadedID {2}",
// newID, oldID, loadedID);
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0) // No engine at all
return oldID;
UUID stateID = oldID;
if (!m_part.ParentGroup.m_savedScriptState.ContainsKey(oldID))
stateID = loadedID;
if (m_part.ParentGroup.m_savedScriptState.ContainsKey(stateID))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(m_part.ParentGroup.m_savedScriptState[stateID]);
////////// CRUFT WARNING ///////////////////////////////////
//
// Old objects will have <ScriptState><State> ...
// This format is XEngine ONLY
//
// New objects have <State Engine="...." ...><ScriptState>...
// This can be passed to any engine
//
XmlNode n = doc.SelectSingleNode("ScriptState");
if (n != null) // Old format data
{
XmlDocument newDoc = new XmlDocument();
XmlElement rootN = newDoc.CreateElement("", "State", "");
XmlAttribute uuidA = newDoc.CreateAttribute("", "UUID", "");
uuidA.Value = stateID.ToString();
rootN.Attributes.Append(uuidA);
XmlAttribute engineA = newDoc.CreateAttribute("", "Engine", "");
engineA.Value = "XEngine";
rootN.Attributes.Append(engineA);
newDoc.AppendChild(rootN);
XmlNode stateN = newDoc.ImportNode(n, true);
rootN.AppendChild(stateN);
// This created document has only the minimun data
// necessary for XEngine to parse it successfully
// m_log.DebugFormat("[PRIM INVENTORY]: Adding legacy state {0} in {1}", stateID, newID);
m_part.ParentGroup.m_savedScriptState[stateID] = newDoc.OuterXml;
}
foreach (IScriptModule e in engines)
{
if (e != null)
{
if (e.SetXMLState(newID, m_part.ParentGroup.m_savedScriptState[stateID]))
break;
}
}
m_part.ParentGroup.m_savedScriptState.Remove(stateID);
}
return stateID;
}
/// <summary>
/// Start a script which is in this prim's inventory.
/// Some processing may occur in the background, but this routine returns asap.
/// </summary>
/// <param name="itemId">
/// A <see cref="UUID"/>
/// </param>
public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
{
lock (m_scriptErrors)
{
// Indicate to CreateScriptInstanceInternal() we don't want it to wait for completion
m_scriptErrors.Remove(itemId);
}
CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
return true;
}
private void CreateScriptInstanceInternal(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
{
m_items.LockItemsForRead(true);
if (m_items.ContainsKey(itemId))
{
TaskInventoryItem it = m_items[itemId];
m_items.LockItemsForRead(false);
CreateScriptInstance(it, startParam, postOnRez, engine, stateSource);
}
else
{
m_items.LockItemsForRead(false);
string msg = String.Format("couldn't be found for prim {0}, {1} at {2} in {3}", m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
StoreScriptError(itemId, msg);
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't start script with ID {0} since it {1}", itemId, msg);
}
}
/// <summary>
/// Start a script which is in this prim's inventory and return any compilation error messages.
/// </summary>
/// <param name="itemId">
/// A <see cref="UUID"/>
/// </param>
public ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
{
ArrayList errors;
// Indicate to CreateScriptInstanceInternal() we want it to
// post any compilation/loading error messages
lock (m_scriptErrors)
{
m_scriptErrors[itemId] = null;
}
// Perform compilation/loading
CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
// Wait for and retrieve any errors
lock (m_scriptErrors)
{
while ((errors = m_scriptErrors[itemId]) == null)
{
if (!System.Threading.Monitor.Wait(m_scriptErrors, 15000))
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"timedout waiting for script {0} errors", itemId);
errors = m_scriptErrors[itemId];
if (errors == null)
{
errors = new ArrayList(1);
errors.Add("timedout waiting for errors");
}
break;
}
}
m_scriptErrors.Remove(itemId);
}
return errors;
}
// Signal to CreateScriptInstanceEr() that compilation/loading is complete
private void StoreScriptErrors(UUID itemId, ArrayList errors)
{
lock (m_scriptErrors)
{
// If compilation/loading initiated via CreateScriptInstance(),
// it does not want the errors, so just get out
if (!m_scriptErrors.ContainsKey(itemId))
{
return;
}
// Initiated via CreateScriptInstanceEr(), if we know what the
// errors are, save them and wake CreateScriptInstanceEr().
if (errors != null)
{
m_scriptErrors[itemId] = errors;
System.Threading.Monitor.PulseAll(m_scriptErrors);
return;
}
}
// Initiated via CreateScriptInstanceEr() but we don't know what
// the errors are yet, so retrieve them from the script engine.
// This may involve some waiting internal to GetScriptErrors().
errors = GetScriptErrors(itemId);
// Get a default non-null value to indicate success.
if (errors == null)
{
errors = new ArrayList();
}
// Post to CreateScriptInstanceEr() and wake it up
lock (m_scriptErrors)
{
m_scriptErrors[itemId] = errors;
System.Threading.Monitor.PulseAll(m_scriptErrors);
}
}
// Like StoreScriptErrors(), but just posts a single string message
private void StoreScriptError(UUID itemId, string message)
{
ArrayList errors = new ArrayList(1);
errors.Add(message);
StoreScriptErrors(itemId, errors);
}
/// <summary>
/// Stop and remove a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
{
if (m_items.ContainsKey(itemId))
{
if (!sceneObjectBeingDeleted)
m_part.RemoveScriptEvents(itemId);
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId);
m_part.ParentGroup.AddActiveScriptCount(-1);
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void StopScriptInstance(UUID itemId)
{
TaskInventoryItem scriptItem;
lock (m_items)
m_items.TryGetValue(itemId, out scriptItem);
if (scriptItem != null)
{
StopScriptInstance(scriptItem);
}
else
{
m_log.WarnFormat(
"[PRIM INVENTORY]: " +
"Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
itemId, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
}
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if this script is being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void StopScriptInstance(TaskInventoryItem item)
{
if (m_part.ParentGroup.Scene != null)
m_part.ParentGroup.Scene.EventManager.TriggerStopScript(m_part.LocalId, item.ItemID);
// At the moment, even stopped scripts are counted as active, which is probably wrong.
// m_part.ParentGroup.AddActiveScriptCount(-1);
}
/// <summary>
/// Check if the inventory holds an item with a given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private bool InventoryContainsName(string name)
{
m_items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
{
m_items.LockItemsForRead(false);
return true;
}
}
m_items.LockItemsForRead(false);
return false;
}
/// <summary>
/// For a given item name, return that name if it is available. Otherwise, return the next available
/// similar name (which is currently the original name with the next available numeric suffix).
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private string FindAvailableInventoryName(string name)
{
if (!InventoryContainsName(name))
return name;
int suffix=1;
while (suffix < 256)
{
string tryName=String.Format("{0} {1}", name, suffix);
if (!InventoryContainsName(tryName))
return tryName;
suffix++;
}
return String.Empty;
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative
/// name is chosen.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop)
{
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced.
/// </summary>
/// <param name="item"></param>
public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
{
m_items.LockItemsForRead(true);
List<TaskInventoryItem> il = new List<TaskInventoryItem>(m_items.Values);
m_items.LockItemsForRead(false);
foreach (TaskInventoryItem i in il)
{
if (i.Name == item.Name)
{
if (i.InvType == (int)InventoryType.LSL)
RemoveScriptInstance(i.ItemID, false);
RemoveInventoryItem(i.ItemID);
break;
}
}
AddInventoryItem(item.Name, item, allowedDrop);
}
/// <summary>
/// Add an item to this prim's inventory.
/// </summary>
/// <param name="name">The name that the new item should have.</param>
/// <param name="item">
/// The item itself. The name within this structure is ignored in favour of the name
/// given in this method's arguments
/// </param>
/// <param name="allowedDrop">
/// Item was only added to inventory because AllowedDrop is set
/// </param>
protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop)
{
name = FindAvailableInventoryName(name);
if (name == String.Empty)
return;
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
item.Name = name;
item.GroupID = m_part.GroupID;
m_items.LockItemsForWrite(true);
m_items.Add(item.ItemID, item);
m_items.LockItemsForWrite(false);
if (allowedDrop)
m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
else
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
m_part.AggregateInnerPerms();
m_inventorySerial++;
//m_inventorySerial += 2;
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
/// <summary>
/// Restore a whole collection of items to the prim's inventory at once.
/// We assume that the items already have all their fields correctly filled out.
/// The items are not flagged for persistence to the database, since they are being restored
/// from persistence rather than being newly added.
/// </summary>
/// <param name="items"></param>
public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
{
m_items.LockItemsForWrite(true);
foreach (TaskInventoryItem item in items)
{
m_items.Add(item.ItemID, item);
// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
}
m_items.LockItemsForWrite(false);
m_part.AggregateInnerPerms();
m_inventorySerial++;
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(UUID itemId)
{
TaskInventoryItem item;
m_items.LockItemsForRead(true);
m_items.TryGetValue(itemId, out item);
m_items.LockItemsForRead(false);
return item;
}
public TaskInventoryItem GetInventoryItem(string name)
{
m_items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
{
m_items.LockItemsForRead(false);
return item;
}
}
m_items.LockItemsForRead(false);
return null;
}
public List<TaskInventoryItem> GetInventoryItems(string name)
{
List<TaskInventoryItem> items = new List<TaskInventoryItem>();
m_items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Name == name)
items.Add(item);
}
m_items.LockItemsForRead(false);
return items;
}
public bool GetRezReadySceneObjects(TaskInventoryItem item, out List<SceneObjectGroup> objlist, out List<Vector3> veclist, out Vector3 bbox, out float offsetHeight)
{
AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
if (null == rezAsset)
{
m_log.WarnFormat(
"[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}",
item.AssetID, item.Name, m_part.Name);
objlist = null;
veclist = null;
bbox = Vector3.Zero;
offsetHeight = 0;
return false;
}
bool single = m_part.ParentGroup.Scene.GetObjectsToRez(rezAsset.Data, false, out objlist, out veclist, out bbox, out offsetHeight);
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup group = objlist[i];
/*
group.RootPart.AttachPoint = group.RootPart.Shape.State;
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.AttachRotation = group.GroupRotation;
*/
group.ResetIDs();
SceneObjectPart rootPart = group.GetPart(group.UUID);
// Since renaming the item in the inventory does not affect the name stored
// in the serialization, transfer the correct name from the inventory to the
// object itself before we rez.
// Only do these for the first object if we are rezzing a coalescence.
// nahh dont mess with coalescence objects,
// the name in inventory can be change for inventory purpuses only
if (objlist.Count == 1)
{
rootPart.Name = item.Name;
rootPart.Description = item.Description;
}
/* reverted to old code till part.ApplyPermissionsOnRez is better reviewed/fixed
group.SetGroup(m_part.GroupID, null);
foreach (SceneObjectPart part in group.Parts)
{
// Convert between InventoryItem classes. You can never have too many similar but slightly different classes :)
InventoryItemBase dest = new InventoryItemBase(item.ItemID, item.OwnerID);
dest.BasePermissions = item.BasePermissions;
dest.CurrentPermissions = item.CurrentPermissions;
dest.EveryOnePermissions = item.EveryonePermissions;
dest.GroupPermissions = item.GroupPermissions;
dest.NextPermissions = item.NextPermissions;
dest.Flags = item.Flags;
part.ApplyPermissionsOnRez(dest, false, m_part.ParentGroup.Scene);
}
*/
// old code start
SceneObjectPart[] partList = group.Parts;
group.SetGroup(m_part.GroupID, null);
if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & (uint)PermissionMask.Slam) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0)
{
if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions())
{
foreach (SceneObjectPart part in partList)
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
part.EveryoneMask = item.EveryonePermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
part.NextOwnerMask = item.NextPermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0)
part.GroupMask = item.GroupPermissions;
}
group.ApplyNextOwnerPermissions();
}
}
foreach (SceneObjectPart part in partList)
{
if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & (uint)PermissionMask.Slam) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0)
{
if(part.GroupID != part.OwnerID)
part.LastOwnerID = part.OwnerID;
part.OwnerID = item.OwnerID;
part.Inventory.ChangeInventoryOwner(item.OwnerID);
}
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
part.EveryoneMask = item.EveryonePermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
part.NextOwnerMask = item.NextPermissions;
if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0)
part.GroupMask = item.GroupPermissions;
}
// old code end
rootPart.TrimPermissions();
group.InvalidateDeepEffectivePerms();
}
return true;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory.</param>
/// <returns>false if the item did not exist, true if the update occurred successfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
return UpdateInventoryItem(item, true, true);
}
public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents)
{
return UpdateInventoryItem(item, fireScriptEvents, true);
}
public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
{
m_items.LockItemsForWrite(true);
if (m_items.ContainsKey(item.ItemID))
{
// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
item.ParentID = m_part.UUID;
item.ParentPartID = m_part.UUID;
// If group permissions have been set on, check that the groupID is up to date in case it has
// changed since permissions were last set.
if (item.GroupPermissions != (uint)PermissionMask.None)
item.GroupID = m_part.GroupID;
if(item.OwnerID == UUID.Zero) // viewer to internal enconding of group owned
item.OwnerID = item.GroupID;
if (item.AssetID == UUID.Zero)
item.AssetID = m_items[item.ItemID].AssetID;
m_items[item.ItemID] = item;
m_inventorySerial++;
if (fireScriptEvents)
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
if (considerChanged)
{
m_part.ParentGroup.InvalidateDeepEffectivePerms();
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
}
m_items.LockItemsForWrite(false);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory",
item.ItemID, m_part.Name, m_part.UUID,
m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
}
m_items.LockItemsForWrite(false);
return false;
}
/// <summary>
/// Remove an item from this prim's inventory
/// </summary>
/// <param name="itemID"></param>
/// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist
/// in this prim's inventory.</returns>
public int RemoveInventoryItem(UUID itemID)
{
m_items.LockItemsForRead(true);
if (m_items.ContainsKey(itemID))
{
int type = m_items[itemID].InvType;
m_items.LockItemsForRead(false);
if (type == 10) // Script
{
m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
}
m_items.LockItemsForWrite(true);
m_items.Remove(itemID);
m_items.LockItemsForWrite(false);
m_part.ParentGroup.InvalidateDeepEffectivePerms();
m_inventorySerial++;
m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
HasInventoryChanged = true;
m_part.ParentGroup.HasGroupChanged = true;
int scriptcount = 0;
m_items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.Type == 10)
{
scriptcount++;
}
}
m_items.LockItemsForRead(false);
if (scriptcount <= 0)
{
m_part.RemFlag(PrimFlags.Scripted);
}
m_part.ScheduleFullUpdate();
return type;
}
else
{
m_items.LockItemsForRead(false);
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Tried to remove item ID {0} from prim {1}, {2} but the item does not exist in this inventory",
itemID, m_part.Name, m_part.UUID);
}
return -1;
}
/// <summary>
/// Serialize all the metadata for the items in this prim's inventory ready for sending to the client
/// </summary>
/// <param name="xferManager"></param>
public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
{
lock (m_inventoryFileLock)
{
bool changed = false;
Items.LockItemsForRead(true);
if (m_inventorySerial == 0) // No inventory
{
Items.LockItemsForRead(false);
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return;
}
if (m_items.Count == 0) // No inventory
{
Items.LockItemsForRead(false);
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
return;
}
if (m_inventoryFileNameSerial != m_inventorySerial)
{
m_inventoryFileNameSerial = m_inventorySerial;
changed = true;
}
Items.LockItemsForRead(false);
if (m_inventoryFileData.Length < 2)
changed = true;
bool includeAssets = false;
if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId))
includeAssets = true;
if (m_inventoryPrivileged != includeAssets)
changed = true;
if (!changed)
{
xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
client.SendTaskInventory(m_part.UUID, (short)m_inventoryFileNameSerial,
m_inventoryFileNameBytes);
return;
}
m_inventoryPrivileged = includeAssets;
InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
Items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
UUID ownerID = item.OwnerID;
UUID groupID = item.GroupID;
uint everyoneMask = item.EveryonePermissions;
uint baseMask = item.BasePermissions;
uint ownerMask = item.CurrentPermissions;
uint groupMask = item.GroupPermissions;
invString.AddItemStart();
invString.AddNameValueLine("item_id", item.ItemID.ToString());
invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
invString.AddPermissionsStart();
invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
invString.AddNameValueLine("group_id",groupID.ToString());
if(groupID != UUID.Zero && ownerID == groupID)
{
invString.AddNameValueLine("owner_id", UUID.Zero.ToString());
invString.AddNameValueLine("group_owned","1");
}
else
{
invString.AddNameValueLine("owner_id", ownerID.ToString());
invString.AddNameValueLine("group_owned","0");
}
invString.AddSectionEnd();
if (includeAssets)
invString.AddNameValueLine("asset_id", item.AssetID.ToString());
else
invString.AddNameValueLine("asset_id", UUID.Zero.ToString());
invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
invString.AddSaleStart();
invString.AddNameValueLine("sale_type", "not");
invString.AddNameValueLine("sale_price", "0");
invString.AddSectionEnd();
invString.AddNameValueLine("name", item.Name + "|");
invString.AddNameValueLine("desc", item.Description + "|");
invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
invString.AddSectionEnd();
}
Items.LockItemsForRead(false);
m_inventoryFileData = Utils.StringToBytes(invString.GetString());
if (m_inventoryFileData.Length > 2)
{
m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
m_inventoryFileNameBytes = Util.StringToBytes256(m_inventoryFileName);
xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
client.SendTaskInventory(m_part.UUID, (short)m_inventoryFileNameSerial,m_inventoryFileNameBytes);
return;
}
client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
}
}
/// <summary>
/// Process inventory backup
/// </summary>
/// <param name="datastore"></param>
public void ProcessInventoryBackup(ISimulationDataService datastore)
{
// Removed this because linking will cause an immediate delete of the new
// child prim from the database and the subsequent storing of the prim sees
// the inventory of it as unchanged and doesn't store it at all. The overhead
// of storing prim inventory needlessly is much less than the aggravation
// of prim inventory loss.
// if (HasInventoryChanged)
// {
Items.LockItemsForRead(true);
ICollection<TaskInventoryItem> itemsvalues = Items.Values;
HasInventoryChanged = false;
Items.LockItemsForRead(false);
try
{
datastore.StorePrimInventory(m_part.UUID, itemsvalues);
}
catch {}
// }
}
public class InventoryStringBuilder
{
private StringBuilder BuildString = new StringBuilder(1024);
public InventoryStringBuilder(UUID folderID, UUID parentID)
{
BuildString.Append("\tinv_object\t0\n\t{\n");
AddNameValueLine("obj_id", folderID.ToString());
AddNameValueLine("parent_id", parentID.ToString());
AddNameValueLine("type", "category");
AddNameValueLine("name", "Contents|\n\t}");
}
public void AddItemStart()
{
BuildString.Append("\tinv_item\t0\n\t{\n");
}
public void AddPermissionsStart()
{
BuildString.Append("\tpermissions 0\n\t{\n");
}
public void AddSaleStart()
{
BuildString.Append("\tsale_info\t0\n\t{\n");
}
protected void AddSectionStart()
{
BuildString.Append("\t{\n");
}
public void AddSectionEnd()
{
BuildString.Append("\t}\n");
}
public void AddLine(string addLine)
{
BuildString.Append(addLine);
}
public void AddNameValueLine(string name, string value)
{
BuildString.Append("\t\t");
BuildString.Append(name);
BuildString.Append("\t");
BuildString.Append(value);
BuildString.Append("\n");
}
public String GetString()
{
return BuildString.ToString();
}
public void Close()
{
}
}
public void AggregateInnerPerms(ref uint owner, ref uint group, ref uint everyone)
{
foreach (TaskInventoryItem item in m_items.Values)
{
if(item.InvType == (sbyte)InventoryType.Landmark)
continue;
owner &= item.CurrentPermissions;
group &= item.GroupPermissions;
everyone &= item.EveryonePermissions;
}
}
public uint MaskEffectivePermissions()
{
// used to propagate permissions restrictions outwards
// Modify does not propagate outwards.
uint mask=0x7fffffff;
foreach (TaskInventoryItem item in m_items.Values)
{
if(item.InvType == (sbyte)InventoryType.Landmark)
continue;
// apply current to normal permission bits
uint newperms = item.CurrentPermissions;
if ((newperms & (uint)PermissionMask.Copy) == 0)
mask &= ~(uint)PermissionMask.Copy;
if ((newperms & (uint)PermissionMask.Transfer) == 0)
mask &= ~(uint)PermissionMask.Transfer;
if ((newperms & (uint)PermissionMask.Export) == 0)
mask &= ~((uint)PermissionMask.Export);
// apply next owner restricted by current to folded bits
newperms &= item.NextPermissions;
if ((newperms & (uint)PermissionMask.Copy) == 0)
mask &= ~((uint)PermissionMask.FoldedCopy);
if ((newperms & (uint)PermissionMask.Transfer) == 0)
mask &= ~((uint)PermissionMask.FoldedTransfer);
if ((newperms & (uint)PermissionMask.Export) == 0)
mask &= ~((uint)PermissionMask.FoldedExport);
}
return mask;
}
public void ApplyNextOwnerPermissions()
{
foreach (TaskInventoryItem item in m_items.Values)
{
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryonePermissions &= item.NextPermissions;
item.OwnerChanged = true;
item.PermsMask = 0;
item.PermsGranter = UUID.Zero;
}
}
public void ApplyGodPermissions(uint perms)
{
foreach (TaskInventoryItem item in m_items.Values)
{
item.CurrentPermissions = perms;
item.BasePermissions = perms;
}
m_inventorySerial++;
HasInventoryChanged = true;
}
/// <summary>
/// Returns true if this part inventory contains any scripts. False otherwise.
/// </summary>
/// <returns></returns>
public bool ContainsScripts()
{
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the count of scripts in this parts inventory.
/// </summary>
/// <returns></returns>
public int ScriptCount()
{
int count = 0;
Items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
{
if (item.InvType == (int)InventoryType.LSL)
{
count++;
}
}
Items.LockItemsForRead(false);
return count;
}
/// <summary>
/// Returns the count of running scripts in this parts inventory.
/// </summary>
/// <returns></returns>
public int RunningScriptCount()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0)
return 0;
int count = 0;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
if (engine.GetScriptState(item.ItemID))
{
count++;
}
}
}
}
return count;
}
public List<UUID> GetInventoryList()
{
List<UUID> ret = new List<UUID>();
foreach (TaskInventoryItem item in m_items.Values)
ret.Add(item.ItemID);
return ret;
}
public List<TaskInventoryItem> GetInventoryItems()
{
List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
Items.LockItemsForRead(true);
ret = new List<TaskInventoryItem>(m_items.Values);
Items.LockItemsForRead(false);
return ret;
}
public List<TaskInventoryItem> GetInventoryItems(InventoryType type)
{
List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
Items.LockItemsForRead(true);
foreach (TaskInventoryItem item in m_items.Values)
if (item.InvType == (int)type)
ret.Add(item);
Items.LockItemsForRead(false);
return ret;
}
public Dictionary<UUID, string> GetScriptStates()
{
return GetScriptStates(false);
}
public Dictionary<UUID, string> GetScriptStates(bool oldIDs)
{
Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
if (m_part.ParentGroup.Scene == null) // Group not in a scene
return ret;
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0) // No engine at all
return ret;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule e in engines)
{
if (e != null)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Getting script state from engine {0} for {1} in part {2} in group {3} in {4}",
// e.Name, item.Name, m_part.Name, m_part.ParentGroup.Name, m_part.ParentGroup.Scene.Name);
string n = e.GetXMLState(item.ItemID);
if (n != String.Empty)
{
if (oldIDs)
{
if (!ret.ContainsKey(item.OldItemID))
ret[item.OldItemID] = n;
}
else
{
if (!ret.ContainsKey(item.ItemID))
ret[item.ItemID] = n;
}
break;
}
}
}
}
return ret;
}
public void ResumeScripts()
{
IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>();
if (engines.Length == 0)
return;
List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
foreach (TaskInventoryItem item in scripts)
{
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Resuming script {0} {1} for {2}, OwnerChanged {3}",
// item.Name, item.ItemID, item.OwnerID, item.OwnerChanged);
engine.ResumeScript(item.ItemID);
if (item.OwnerChanged)
engine.PostScriptEvent(item.ItemID, "changed", new Object[] { (int)Changed.OWNER });
item.OwnerChanged = false;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class libproc
{
// Constants from sys\param.h
private const int MAXCOMLEN = 16;
private const int MAXPATHLEN = 1024;
// Constants from proc_info.h
private const int MAXTHREADNAMESIZE = 64;
private const int PROC_PIDLISTFDS = 1;
private const int PROC_PIDTASKALLINFO = 2;
private const int PROC_PIDTHREADINFO = 5;
private const int PROC_PIDLISTTHREADS = 6;
private const int PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN;
private static int PROC_PIDLISTFD_SIZE = Marshal.SizeOf<proc_fdinfo>();
private static int PROC_PIDLISTTHREADS_SIZE = (Marshal.SizeOf<uint>() * 2);
// Constants from sys\resource.h
private const int RUSAGE_SELF = 0;
// Defines from proc_info.h
internal enum ThreadRunState
{
TH_STATE_RUNNING = 1,
TH_STATE_STOPPED = 2,
TH_STATE_WAITING = 3,
TH_STATE_UNINTERRUPTIBLE = 4,
TH_STATE_HALTED = 5
}
// Defines in proc_info.h
[Flags]
internal enum ThreadFlags
{
TH_FLAGS_SWAPPED = 0x1,
TH_FLAGS_IDLE = 0x2
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct proc_bsdinfo
{
internal uint pbi_flags;
internal uint pbi_status;
internal uint pbi_xstatus;
internal uint pbi_pid;
internal uint pbi_ppid;
internal uint pbi_uid;
internal uint pbi_gid;
internal uint pbi_ruid;
internal uint pbi_rgid;
internal uint pbi_svuid;
internal uint pbi_svgid;
internal uint reserved;
internal fixed byte pbi_comm[MAXCOMLEN];
internal fixed byte pbi_name[MAXCOMLEN * 2];
internal uint pbi_nfiles;
internal uint pbi_pgid;
internal uint pbi_pjobc;
internal uint e_tdev;
internal uint e_tpgid;
internal int pbi_nice;
internal ulong pbi_start_tvsec;
internal ulong pbi_start_tvusec;
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct proc_taskinfo
{
internal ulong pti_virtual_size;
internal ulong pti_resident_size;
internal ulong pti_total_user;
internal ulong pti_total_system;
internal ulong pti_threads_user;
internal ulong pti_threads_system;
internal int pti_policy;
internal int pti_faults;
internal int pti_pageins;
internal int pti_cow_faults;
internal int pti_messages_sent;
internal int pti_messages_received;
internal int pti_syscalls_mach;
internal int pti_syscalls_unix;
internal int pti_csw;
internal int pti_threadnum;
internal int pti_numrunning;
internal int pti_priority;
};
// from sys\resource.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct rusage_info_v3
{
internal fixed byte ri_uuid[16];
internal ulong ri_user_time;
internal ulong ri_system_time;
internal ulong ri_pkg_idle_wkups;
internal ulong ri_interrupt_wkups;
internal ulong ri_pageins;
internal ulong ri_wired_size;
internal ulong ri_resident_size;
internal ulong ri_phys_footprint;
internal ulong ri_proc_start_abstime;
internal ulong ri_proc_exit_abstime;
internal ulong ri_child_user_time;
internal ulong ri_child_system_time;
internal ulong ri_child_pkg_idle_wkups;
internal ulong ri_child_interrupt_wkups;
internal ulong ri_child_pageins;
internal ulong ri_child_elapsed_abstime;
internal ulong ri_diskio_bytesread;
internal ulong ri_diskio_byteswritten;
internal ulong ri_cpu_time_qos_default;
internal ulong ri_cpu_time_qos_maintenance;
internal ulong ri_cpu_time_qos_background;
internal ulong ri_cpu_time_qos_utility;
internal ulong ri_cpu_time_qos_legacy;
internal ulong ri_cpu_time_qos_user_initiated;
internal ulong ri_cpu_time_qos_user_interactive;
internal ulong ri_billed_system_time;
internal ulong ri_serviced_system_time;
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
internal unsafe struct proc_taskallinfo
{
internal proc_bsdinfo pbsd;
internal proc_taskinfo ptinfo;
}
// From proc_info.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct proc_threadinfo
{
internal ulong pth_user_time;
internal ulong pth_system_time;
internal int pth_cpu_usage;
internal int pth_policy;
internal int pth_run_state;
internal int pth_flags;
internal int pth_sleep_time;
internal int pth_curpri;
internal int pth_priority;
internal int pth_maxpriority;
internal fixed byte pth_name[MAXTHREADNAMESIZE];
}
[StructLayout(LayoutKind.Sequential)]
internal struct proc_fdinfo
{
internal int proc_fd;
internal uint proc_fdtype;
}
/// <summary>
/// Queries the OS for the PIDs for all running processes
/// </summary>
/// <param name="buffer">A pointer to the memory block where the PID array will start</param>
/// <param name="buffersize">The length of the block of memory allocated for the PID array</param>
/// <returns>Returns the number of elements (PIDs) in the buffer</returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_listallpids(
int* pBuffer,
int buffersize);
/// <summary>
/// Queries the OS for the list of all running processes and returns the PID for each
/// </summary>
/// <returns>Returns a list of PIDs corresponding to all running processes</returns>
internal static unsafe int[] proc_listallpids()
{
// Get the number of processes currently running to know how much data to allocate
int numProcesses = proc_listallpids(null, 0);
if (numProcesses <= 0)
{
throw new Win32Exception(SR.CantGetAllPids);
}
int[] processes;
do
{
// Create a new array for the processes (plus a 10% buffer in case new processes have spawned)
// Since we don't know how many threads there could be, if result == size, that could mean two things
// 1) We guessed exactly how many processes there are
// 2) There are more processes that we didn't get since our buffer is too small
// To make sure it isn't #2, when the result == size, increase the buffer and try again
processes = new int[(int)(numProcesses * 1.10)];
fixed (int* pBuffer = processes)
{
numProcesses = proc_listallpids(pBuffer, processes.Length * Marshal.SizeOf<int>());
if (numProcesses <= 0)
{
throw new Win32Exception(SR.CantGetAllPids);
}
}
}
while (numProcesses == processes.Length);
// Remove extra elements
Array.Resize<int>(ref processes, numProcesses);
return processes;
}
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDTASKALLINFO</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size proc_taskallinfo) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
proc_taskallinfo* buffer,
int bufferSize);
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDTHREADINFO</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size proc_threadinfo) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
proc_threadinfo* buffer,
int bufferSize);
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDLISTFDS</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size proc_fdinfo) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
proc_fdinfo* buffer,
int bufferSize);
/// <summary>
/// Gets information about a process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
/// <param name="flavor">Should be PROC_PIDTASKALLINFO</param>
/// <param name="arg">Flavor dependent value</param>
/// <param name="buffer">A pointer to a block of memory (of size ulong[]) allocated that will contain the data</param>
/// <param name="bufferSize">The size of the allocated block above</param>
/// <returns>
/// The amount of data actually returned. If this size matches the bufferSize parameter then
/// the data is valid. If the sizes do not match then the data is invalid, most likely due
/// to not having enough permissions to query for the data of that specific process
/// </returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidinfo(
int pid,
int flavor,
ulong arg,
ulong* buffer,
int bufferSize);
/// <summary>
/// Gets the process information for a given process
/// </summary>
/// <param name="pid">The PID (process ID) of the process</param>
/// <returns>
/// Returns a valid proc_taskallinfo struct for valid processes that the caller
/// has permission to access; otherwise, returns null
/// </returns>
internal static unsafe proc_taskallinfo? GetProcessInfoById(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException("pid");
}
// Get the process information for the specified pid
int size = Marshal.SizeOf<proc_taskallinfo>();
proc_taskallinfo info = default(proc_taskallinfo);
int result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, size);
return (result == size ? new proc_taskallinfo?(info) : null);
}
/// <summary>
/// Gets the thread information for the given thread
/// </summary>
/// <param name="thread">The ID of the thread to query for information</param>
/// <returns>
/// Returns a valid proc_threadinfo struct for valid threads that the caller
/// has permissions to access; otherwise, returns null
/// </returns>
internal static unsafe proc_threadinfo? GetThreadInfoById(int pid, ulong thread)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException("pid");
}
// Negative TIDs are invalid
if (thread < 0)
{
throw new ArgumentOutOfRangeException("thread");
}
// Get the thread information for the specified thread in the specified process
int size = Marshal.SizeOf<proc_threadinfo>();
proc_threadinfo info = default(proc_threadinfo);
int result = proc_pidinfo(pid, PROC_PIDTHREADINFO, (ulong)thread, &info, size);
return (result == size ? new proc_threadinfo?(info) : null);
}
internal static unsafe List<KeyValuePair<ulong, proc_threadinfo?>> GetAllThreadsInProcess(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException("pid");
}
int result = 0;
int size = 20; // start assuming 20 threads is enough
ulong[] threadIds = null;
// We have no way of knowning how many threads the process has (and therefore how big our buffer should be)
// so while the return value of the function is the same as our buffer size (meaning it completely filled
// our buffer), double our buffer size and try again. This ensures that we don't miss any threads
do
{
threadIds = new ulong[size];
fixed (ulong* pBuffer = threadIds)
{
result = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, pBuffer, Marshal.SizeOf<ulong>() * threadIds.Length);
}
if (result <= 0)
{
throw new Win32Exception();
}
else
{
checked
{
size *= 2;
}
}
}
while (result == Marshal.SizeOf<ulong>() * threadIds.Length);
Debug.Assert((result % Marshal.SizeOf<ulong>()) == 0);
// Loop over each thread and get the thread info
int count = (int)(result / Marshal.SizeOf<ulong>());
List<KeyValuePair<ulong, proc_threadinfo?>> threads = new List<KeyValuePair<ulong, proc_threadinfo?>>(count);
for (int i = 0; i < count; i++)
{
threads.Add(new KeyValuePair<ulong, proc_threadinfo?>(threadIds[i], GetThreadInfoById(pid, threadIds[i])));
}
return threads;
}
/// <summary>
/// Retrieves the number of open file descriptors for the specified pid
/// </summary>
/// <returns>Returns an array of open File Descriptors for this process</returns>
/// <remarks>
/// This function doesn't use the helper since it seems to allow passing NULL
/// values in to the buffer and length parameters to get back an estimation
/// of how much data we will need to allocate; the other flavors don't seem
/// to support doing that.
/// </remarks>
internal static unsafe int GetFileDescriptorCountForPid(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException("pid");
}
// Query for an estimation about the size of the buffer we will need. This seems
// to add some padding from the real number, so we don't need to do that
int result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, (proc_fdinfo*)null, 0);
if (result <= 0)
{
throw new Win32Exception();
}
proc_fdinfo[] fds;
int size = (int)(result / Marshal.SizeOf<proc_fdinfo>());
// Just in case the app opened a ton of handles between when we asked and now,
// make sure we retry if our buffer is filled
do
{
fds = new proc_fdinfo[size];
fixed (proc_fdinfo* pFds = fds)
{
result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, pFds, Marshal.SizeOf<proc_fdinfo>() * fds.Length);
}
if (result <= 0)
{
throw new Win32Exception();
}
else
{
checked
{
size *= 2;
}
}
}
while (result == (fds.Length * Marshal.SizeOf<proc_fdinfo>()));
Debug.Assert((result % Marshal.SizeOf<proc_fdinfo>()) == 0);
return (int)(result / Marshal.SizeOf<proc_fdinfo>());
}
/// <summary>
/// Gets the full path to the executable file identified by the specified PID
/// </summary>
/// <param name="pid">The PID of the running process</param>
/// <param name="buffer">A pointer to an allocated block of memory that will be filled with the process path</param>
/// <param name="bufferSize">The size of the buffer, should be PROC_PIDPATHINFO_MAXSIZE</param>
/// <returns>Returns the length of the path returned on success</returns>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pidpath(
int pid,
byte* buffer,
uint bufferSize);
/// <summary>
/// Gets the full path to the executable file identified by the specified PID
/// </summary>
/// <param name="pid">The PID of the running process</param>
/// <returns>Returns the full path to the process executable</returns>
internal static unsafe string proc_pidpath(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException("pid", SR.NegativePidNotSupported);
}
// The path is a fixed buffer size, so use that and trim it after
int result = 0;
byte* pBuffer = stackalloc byte[PROC_PIDPATHINFO_MAXSIZE];
result = proc_pidpath(pid, pBuffer, (uint)(PROC_PIDPATHINFO_MAXSIZE * Marshal.SizeOf<byte>()));
if (result <= 0)
{
throw new Win32Exception();
}
// OS X uses UTF-8. The conversion may not strip off all trailing \0s so remove them here
return System.Text.Encoding.UTF8.GetString(pBuffer, result);
}
/// <summary>
/// Gets the rusage information for the process identified by the PID
/// </summary>
/// <param name="pid">The process to retrieve the rusage for</param>
/// <param name="flavor">Should be RUSAGE_SELF to specify getting the info for the specified process</param>
/// <param name="rusage_info_t">A buffer to be filled with rusage_info data</param>
/// <returns>Returns 0 on success; on fail, -1 and errno is set with the error code</returns>
/// <remarks>
/// We need to use IntPtr here for the buffer since the function signature uses
/// void* and not a strong type even though it returns a rusage_info struct
/// </remarks>
[DllImport(Interop.Libraries.libproc, SetLastError = true)]
private static unsafe extern int proc_pid_rusage(
int pid,
int flavor,
rusage_info_v3* rusage_info_t);
/// <summary>
/// Gets the rusage information for the process identified by the PID
/// </summary>
/// <param name="pid">The process to retrieve the rusage for</param>
/// <returns>On success, returns a struct containing info about the process; on
/// failure or when the caller doesn't have permissions to the process, throws a Win32Exception
/// </returns>
internal static unsafe rusage_info_v3 proc_pid_rusage(int pid)
{
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException("pid", SR.NegativePidNotSupported);
}
rusage_info_v3 info = new rusage_info_v3();
// Get the PIDs rusage info
int result = proc_pid_rusage(pid, RUSAGE_SELF, &info);
if (result <= 0)
{
throw new Win32Exception(SR.RUsageFailure);
}
Debug.Assert(result == Marshal.SizeOf<rusage_info_v3>());
return info;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.NativeCrypto;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using FILETIME = Internal.Cryptography.Pal.Native.FILETIME;
using System.Security.Cryptography;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
public static ICertificatePal FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, "handle");
SafeCertContextHandle safeCertContextHandle = Interop.crypt32.CertDuplicateCertificateContext(handle);
if (safeCertContextHandle.IsInvalid)
throw new CryptographicException(ErrorCode.HRESULT_INVALID_HANDLE);
CRYPTOAPI_BLOB dataBlob;
int cbData = 0;
bool deleteKeyContainer = Interop.crypt32.CertGetCertificateContextProperty(safeCertContextHandle, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, out dataBlob, ref cbData);
return new CertificatePal(safeCertContextHandle, deleteKeyContainer);
}
public IntPtr Handle
{
get { return _certContext.DangerousGetHandle(); }
}
public String Issuer
{
get
{
return GetIssuerOrSubject(issuer: true);
}
}
public String Subject
{
get
{
return GetIssuerOrSubject(issuer: false);
}
}
public byte[] Thumbprint
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, null, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
byte[] thumbprint = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
return thumbprint;
}
}
public String KeyAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
String keyAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
GC.KeepAlive(this);
return keyAlgorithm;
}
}
}
public byte[] KeyAlgorithmParameters
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
String keyAlgorithmOid = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
int algId;
if (keyAlgorithmOid == Oids.RsaRsa)
algId = AlgId.CALG_RSA_KEYX; // Fast-path for the most common case.
else
algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, keyAlgorithmOid, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
unsafe
{
byte* NULL_ASN_TAG = (byte*)0x5;
byte[] keyAlgorithmParameters;
if (algId == AlgId.CALG_DSS_SIGN
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.cbData == 0
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.pbData == NULL_ASN_TAG)
{
//
// DSS certificates may not have the DSS parameters in the certificate. In this case, we try to build
// the certificate chain and propagate the parameters down from the certificate chain.
//
keyAlgorithmParameters = PropagateKeyAlgorithmParametersFromChain();
}
else
{
keyAlgorithmParameters = pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.ToByteArray();
}
GC.KeepAlive(this);
return keyAlgorithmParameters;
}
}
}
}
private byte[] PropagateKeyAlgorithmParametersFromChain()
{
unsafe
{
SafeX509ChainHandle certChainContext = null;
try
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
{
CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
}
byte[] keyAlgorithmParameters = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
return keyAlgorithmParameters;
}
finally
{
if (certChainContext != null)
certChainContext.Dispose();
}
}
}
public byte[] PublicKeyValue
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] publicKey = pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.ToByteArray();
GC.KeepAlive(this);
return publicKey;
}
}
}
public byte[] SerialNumber
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] serialNumber = pCertContext->pCertInfo->SerialNumber.ToByteArray();
GC.KeepAlive(this);
return serialNumber;
}
}
}
public String SignatureAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
String signatureAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SignatureAlgorithm.pszObjId);
GC.KeepAlive(this);
return signatureAlgorithm;
}
}
}
public DateTime NotAfter
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notAfter = pCertContext->pCertInfo->NotAfter.ToDateTime();
GC.KeepAlive(this);
return notAfter;
}
}
}
public DateTime NotBefore
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notBefore = pCertContext->pCertInfo->NotBefore.ToDateTime();
GC.KeepAlive(this);
return notBefore;
}
}
}
public byte[] RawData
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int count = pCertContext->cbCertEncoded;
byte[] rawData = new byte[count];
Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), rawData, 0, count);
GC.KeepAlive(this);
return rawData;
}
}
}
public int Version
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int version = pCertContext->pCertInfo->dwVersion + 1;
GC.KeepAlive(this);
return version;
}
}
}
public bool Archived
{
get
{
int uninteresting = 0;
bool archivePropertyExists = Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, null, ref uninteresting);
return archivePropertyExists;
}
set
{
unsafe
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(0, (byte*)null);
CRYPTOAPI_BLOB* pValue = value ? &blob : (CRYPTOAPI_BLOB*)null;
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, CertSetPropertyFlags.None, pValue))
throw new CryptographicException(Marshal.GetLastWin32Error());
return;
}
}
}
public String FriendlyName
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, null, ref cbData))
return String.Empty;
StringBuilder sb = new StringBuilder((cbData + 1) / 2);
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, sb, ref cbData))
return String.Empty;
return sb.ToString();
}
set
{
String friendlyName = (value == null) ? String.Empty : value;
unsafe
{
IntPtr pFriendlyName = Marshal.StringToHGlobalUni(friendlyName);
try
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(checked(2 * (friendlyName.Length + 1)), (byte*)pFriendlyName);
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, CertSetPropertyFlags.None, &blob))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
finally
{
Marshal.FreeHGlobal(pFriendlyName);
}
}
return;
}
}
public X500DistinguishedName SubjectName
{
get
{
unsafe
{
byte[] encodedSubjectName = _certContext.CertContext->pCertInfo->Subject.ToByteArray();
X500DistinguishedName subjectName = new X500DistinguishedName(encodedSubjectName);
GC.KeepAlive(this);
return subjectName;
}
}
}
public X500DistinguishedName IssuerName
{
get
{
unsafe
{
byte[] encodedIssuerName = _certContext.CertContext->pCertInfo->Issuer.ToByteArray();
X500DistinguishedName issuerName = new X500DistinguishedName(encodedIssuerName);
GC.KeepAlive(this);
return issuerName;
}
}
}
public IEnumerable<X509Extension> Extensions
{
get
{
unsafe
{
CERT_INFO* pCertInfo = _certContext.CertContext->pCertInfo;
int numExtensions = pCertInfo->cExtension;
X509Extension[] extensions = new X509Extension[numExtensions];
for (int i = 0; i < numExtensions; i++)
{
CERT_EXTENSION* pCertExtension = pCertInfo->rgExtension + i;
String oidValue = Marshal.PtrToStringAnsi(pCertExtension->pszObjId);
Oid oid = new Oid(oidValue);
bool critical = pCertExtension->fCritical != 0;
byte[] rawData = pCertExtension->Value.ToByteArray();
extensions[i] = new X509Extension(oid, rawData, critical);
}
GC.KeepAlive(this);
return extensions;
}
}
}
public String GetNameInfo(X509NameType nameType, bool forIssuer)
{
CertNameType certNameType = MapNameType(nameType);
CertNameFlags certNameFlags = forIssuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStrTypeAndFlags strType = CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, null, 0);
if (cchCount == 0)
throw new CryptographicException(Marshal.GetLastWin32Error());
StringBuilder sb = new StringBuilder(cchCount);
if (Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, sb, cchCount) == 0)
throw new CryptographicException(Marshal.GetLastWin32Error());
return sb.ToString();
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
CspKeyContainerInfo cspKeyContainerInfo = null;
try
{
if (HasPrivateKey)
{
CspParameters parameters = GetPrivateKey();
cspKeyContainerInfo = new CspKeyContainerInfo(parameters);
}
}
// We could not access the key container. Just return.
catch (CryptographicException) { }
if (cspKeyContainerInfo == null)
return;
sb.Append(Environment.NewLine + Environment.NewLine + "[Private Key]");
sb.Append(Environment.NewLine + " Key Store: ");
sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User");
sb.Append(Environment.NewLine + " Provider Name: ");
sb.Append(cspKeyContainerInfo.ProviderName);
sb.Append(Environment.NewLine + " Provider type: ");
sb.Append(cspKeyContainerInfo.ProviderType);
sb.Append(Environment.NewLine + " Key Spec: ");
sb.Append(cspKeyContainerInfo.KeyNumber);
sb.Append(Environment.NewLine + " Key Container Name: ");
sb.Append(cspKeyContainerInfo.KeyContainerName);
try
{
String uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName;
sb.Append(Environment.NewLine + " Unique Key Container Name: ");
sb.Append(uniqueKeyContainer);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
bool b = false;
try
{
b = cspKeyContainerInfo.HardwareDevice;
sb.Append(Environment.NewLine + " Hardware Device: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Removable;
sb.Append(Environment.NewLine + " Removable: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Protected;
sb.Append(Environment.NewLine + " Protected: ");
sb.Append(b);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
}
public void Dispose()
{
SafeCertContextHandle certContext = _certContext;
_certContext = null;
if (certContext != null && !certContext.IsInvalid)
{
certContext.Dispose();
}
return;
}
internal SafeCertContextHandle CertContext
{
get
{
SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(_certContext.DangerousGetHandle());
GC.KeepAlive(_certContext);
return certContext;
}
}
private static CertNameType MapNameType(X509NameType nameType)
{
switch (nameType)
{
case X509NameType.SimpleName:
return CertNameType.CERT_NAME_SIMPLE_DISPLAY_TYPE;
case X509NameType.EmailName:
return CertNameType.CERT_NAME_EMAIL_TYPE;
case X509NameType.UpnName:
return CertNameType.CERT_NAME_UPN_TYPE;
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
return CertNameType.CERT_NAME_DNS_TYPE;
case X509NameType.UrlName:
return CertNameType.CERT_NAME_URL_TYPE;
default:
throw new ArgumentException(SR.Argument_InvalidNameType);
}
}
private String GetIssuerOrSubject(bool issuer)
{
CertNameFlags flags = issuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStringType stringType = CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, null, 0);
if (cchCount == 0)
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
StringBuilder sb = new StringBuilder(cchCount);
cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, sb, cchCount);
if (cchCount == 0)
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
return sb.ToString();
}
private CertificatePal(SafeCertContextHandle certContext, bool deleteKeyContainer)
{
if (deleteKeyContainer)
{
// We need to delete any associated key container upon disposition. Thus, replace the safehandle we got with a safehandle whose
// Release() method performs the key container deletion.
SafeCertContextHandle oldCertContext = certContext;
certContext = Interop.crypt32.CertDuplicateCertificateContextWithKeyContainerDeletion(oldCertContext.DangerousGetHandle());
GC.KeepAlive(oldCertContext);
}
_certContext = certContext;
return;
}
private SafeCertContextHandle _certContext;
}
}
| |
// <copyright file="SelectElement.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Support.UI
{
/// <summary>
/// Provides a convenience method for manipulating selections of options in an HTML select element.
/// </summary>
public class SelectElement : IWrapsElement
{
private readonly IWebElement element;
/// <summary>
/// Initializes a new instance of the <see cref="SelectElement"/> class.
/// </summary>
/// <param name="element">The element to be wrapped</param>
/// <exception cref="ArgumentNullException">Thrown when the <see cref="IWebElement"/> object is <see langword="null"/></exception>
/// <exception cref="UnexpectedTagNameException">Thrown when the element wrapped is not a <select> element.</exception>
public SelectElement(IWebElement element)
{
if (element == null)
{
throw new ArgumentNullException("element", "element cannot be null");
}
if (string.IsNullOrEmpty(element.TagName) || string.Compare(element.TagName, "select", StringComparison.OrdinalIgnoreCase) != 0)
{
throw new UnexpectedTagNameException("select", element.TagName);
}
this.element = element;
// let check if it's a multiple
string attribute = element.GetAttribute("multiple");
this.IsMultiple = attribute != null && attribute.ToLowerInvariant() != "false";
}
/// <summary>
/// Gets the <see cref="IWebElement"/> wrapped by this object.
/// </summary>
public IWebElement WrappedElement
{
get { return this.element; }
}
/// <summary>
/// Gets a value indicating whether the parent element supports multiple selections.
/// </summary>
public bool IsMultiple { get; private set; }
/// <summary>
/// Gets the list of options for the select element.
/// </summary>
public IList<IWebElement> Options
{
get
{
return this.element.FindElements(By.TagName("option"));
}
}
/// <summary>
/// Gets the selected item within the select element.
/// </summary>
/// <remarks>If more than one item is selected this will return the first item.</remarks>
/// <exception cref="NoSuchElementException">Thrown if no option is selected.</exception>
public IWebElement SelectedOption
{
get
{
foreach (IWebElement option in this.Options)
{
if (option.Selected)
{
return option;
}
}
throw new NoSuchElementException("No option is selected");
}
}
/// <summary>
/// Gets all of the selected options within the select element.
/// </summary>
public IList<IWebElement> AllSelectedOptions
{
get
{
List<IWebElement> returnValue = new List<IWebElement>();
foreach (IWebElement option in this.Options)
{
if (option.Selected)
{
returnValue.Add(option);
}
}
return returnValue;
}
}
/// <summary>
/// Select all options by the text displayed.
/// </summary>
/// <param name="text">The text of the option to be selected. If an exact match is not found,
/// this method will perform a substring match.</param>
/// <remarks>When given "Bar" this method would select an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
/// <exception cref="NoSuchElementException">Thrown if there is no element with the given text present.</exception>
public void SelectByText(string text)
{
if (text == null)
{
throw new ArgumentNullException("text", "text must not be null");
}
// try to find the option via XPATH ...
IList<IWebElement> options = this.element.FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"));
bool matched = false;
foreach (IWebElement option in options)
{
SetSelected(option, true);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
if (options.Count == 0 && text.Contains(" "))
{
string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
IList<IWebElement> candidates;
if (string.IsNullOrEmpty(substringWithoutSpace))
{
// hmm, text is either empty or contains only spaces - get all options ...
candidates = this.element.FindElements(By.TagName("option"));
}
else
{
// get candidates via XPATH ...
candidates = this.element.FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"));
}
foreach (IWebElement option in candidates)
{
if (text == option.Text)
{
SetSelected(option, true);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
}
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate element with text: " + text);
}
}
/// <summary>
/// Select an option by the value.
/// </summary>
/// <param name="value">The value of the option to be selected.</param>
/// <remarks>When given "foo" this method will select an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
/// <exception cref="NoSuchElementException">Thrown when no element with the specified value is found.</exception>
public void SelectByValue(string value)
{
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.Append(EscapeQuotes(value));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
bool matched = false;
foreach (IWebElement option in options)
{
SetSelected(option, true);
if (!this.IsMultiple)
{
return;
}
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with value: " + value);
}
}
/// <summary>
/// Select the option by the index, as determined by the "index" attribute of the element.
/// </summary>
/// <param name="index">The value of the index attribute of the option to be selected.</param>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified index attribute.</exception>
public void SelectByIndex(int index)
{
string match = index.ToString(CultureInfo.InvariantCulture);
foreach (IWebElement option in this.Options)
{
if (option.GetAttribute("index") == match)
{
SetSelected(option, true);
return;
}
}
throw new NoSuchElementException("Cannot locate option with index: " + index);
}
/// <summary>
/// Clear all selected entries. This is only valid when the SELECT supports multiple selections.
/// </summary>
/// <exception cref="WebDriverException">Thrown when attempting to deselect all options from a SELECT
/// that does not support multiple selections.</exception>
public void DeselectAll()
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect all options if multi-select is supported");
}
foreach (IWebElement option in this.Options)
{
SetSelected(option, false);
}
}
/// <summary>
/// Deselect the option by the text displayed.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when attempting to deselect option from a SELECT
/// that does not support multiple selections.</exception>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified test attribute.</exception>
/// <param name="text">The text of the option to be deselected.</param>
/// <remarks>When given "Bar" this method would deselect an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
public void DeselectByText(string text)
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
bool matched = false;
StringBuilder builder = new StringBuilder(".//option[normalize-space(.) = ");
builder.Append(EscapeQuotes(text));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
foreach (IWebElement option in options)
{
SetSelected(option, false);
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with text: " + text);
}
}
/// <summary>
/// Deselect the option having value matching the specified text.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when attempting to deselect option from a SELECT
/// that does not support multiple selections.</exception>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified value attribute.</exception>
/// <param name="value">The value of the option to deselect.</param>
/// <remarks>When given "foo" this method will deselect an option like:
/// <para>
/// <option value="foo">Bar</option>
/// </para>
/// </remarks>
public void DeselectByValue(string value)
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
bool matched = false;
StringBuilder builder = new StringBuilder(".//option[@value = ");
builder.Append(EscapeQuotes(value));
builder.Append("]");
IList<IWebElement> options = this.element.FindElements(By.XPath(builder.ToString()));
foreach (IWebElement option in options)
{
SetSelected(option, false);
matched = true;
}
if (!matched)
{
throw new NoSuchElementException("Cannot locate option with value: " + value);
}
}
/// <summary>
/// Deselect the option by the index, as determined by the "index" attribute of the element.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when attempting to deselect option from a SELECT
/// that does not support multiple selections.</exception>
/// <exception cref="NoSuchElementException">Thrown when no element exists with the specified index attribute.</exception>
/// <param name="index">The value of the index attribute of the option to deselect.</param>
public void DeselectByIndex(int index)
{
if (!this.IsMultiple)
{
throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
string match = index.ToString(CultureInfo.InvariantCulture);
foreach (IWebElement option in this.Options)
{
if (match == option.GetAttribute("index"))
{
SetSelected(option, false);
return;
}
}
throw new NoSuchElementException("Cannot locate option with index: " + index);
}
private static string EscapeQuotes(string toEscape)
{
// Convert strings with both quotes and ticks into: foo'"bar -> concat("foo'", '"', "bar")
if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1 && toEscape.IndexOf("'", StringComparison.OrdinalIgnoreCase) > -1)
{
bool quoteIsLast = false;
if (toEscape.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase) == toEscape.Length - 1)
{
quoteIsLast = true;
}
List<string> substrings = new List<string>(toEscape.Split('\"'));
if (quoteIsLast && string.IsNullOrEmpty(substrings[substrings.Count - 1]))
{
// If the last character is a quote ('"'), we end up with an empty entry
// at the end of the list, which is unnecessary. We don't want to split
// ignoring *all* empty entries, since that might mask legitimate empty
// strings. Instead, just remove the empty ending entry.
substrings.RemoveAt(substrings.Count - 1);
}
StringBuilder quoted = new StringBuilder("concat(");
for (int i = 0; i < substrings.Count; i++)
{
quoted.Append("\"").Append(substrings[i]).Append("\"");
if (i == substrings.Count - 1)
{
if (quoteIsLast)
{
quoted.Append(", '\"')");
}
else
{
quoted.Append(")");
}
}
else
{
quoted.Append(", '\"', ");
}
}
return quoted.ToString();
}
// Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1)
{
return string.Format(CultureInfo.InvariantCulture, "'{0}'", toEscape);
}
// Otherwise return the quoted string
return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", toEscape);
}
private static string GetLongestSubstringWithoutSpace(string s)
{
string result = string.Empty;
string[] substrings = s.Split(' ');
foreach (string substring in substrings)
{
if (substring.Length > result.Length)
{
result = substring;
}
}
return result;
}
private static void SetSelected(IWebElement option, bool select)
{
bool isSelected = option.Selected;
if ((!isSelected && select) || (isSelected && !select))
{
option.Click();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.SqlUtils;
namespace Orleans.Providers.SqlServer
{
/// <summary>
/// Plugin for publishing silos and client statistics to a SQL database.
/// </summary>
public class SqlStatisticsPublisher: IConfigurableStatisticsPublisher, IConfigurableSiloMetricsDataPublisher, IConfigurableClientMetricsDataPublisher, IProvider
{
private string deploymentId;
private IPAddress clientAddress;
private SiloAddress siloAddress;
private IPEndPoint gateway;
private string clientId;
private string siloName;
private string hostName;
private bool isSilo;
private long generation;
private RelationalOrleansQueries orleansQueries;
private Logger logger;
private IGrainReferenceConverter grainReferenceConverter;
/// <summary>
/// Name of the provider
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Initializes publisher
/// </summary>
/// <param name="name">Provider name</param>
/// <param name="providerRuntime">Provider runtime API</param>
/// <param name="config">Provider configuration</param>
/// <returns></returns>
public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
Name = name;
logger = providerRuntime.GetLogger("SqlStatisticsPublisher");
this.grainReferenceConverter = providerRuntime.ServiceProvider.GetRequiredService<IGrainReferenceConverter>();
string adoInvariant = AdoNetInvariants.InvariantNameSqlServer;
if (config.Properties.ContainsKey("AdoInvariant"))
adoInvariant = config.Properties["AdoInvariant"];
orleansQueries = await RelationalOrleansQueries.CreateInstance(adoInvariant, config.Properties["ConnectionString"], this.grainReferenceConverter);
}
/// <summary>
/// Closes provider
/// </summary>
/// <returns>Resolved task</returns>
public Task Close()
{
return Task.CompletedTask;
}
/// <summary>
/// Adds configuration parameters
/// </summary>
/// <param name="deployment">Deployment ID</param>
/// <param name="hostName">Host name</param>
/// <param name="client">Client ID</param>
/// <param name="address">IP address</param>
public void AddConfiguration(string deployment, string hostName, string client, IPAddress address)
{
deploymentId = deployment;
isSilo = false;
this.hostName = hostName;
clientId = client;
clientAddress = address;
generation = SiloAddress.AllocateNewGeneration();
}
/// <summary>
/// Adds configuration parameters
/// </summary>
/// <param name="deployment">Deployment ID</param>
/// <param name="silo">Silo name</param>
/// <param name="siloId">Silo ID</param>
/// <param name="address">Silo address</param>
/// <param name="gatewayAddress">Client gateway address</param>
/// <param name="hostName">Host name</param>
public void AddConfiguration(string deployment, bool silo, string siloId, SiloAddress address, IPEndPoint gatewayAddress, string hostName)
{
deploymentId = deployment;
isSilo = silo;
siloName = siloId;
siloAddress = address;
gateway = gatewayAddress;
this.hostName = hostName;
if(!isSilo)
{
generation = SiloAddress.AllocateNewGeneration();
}
}
async Task IClientMetricsDataPublisher.Init(ClientConfiguration config, IPAddress address, string clientId)
{
orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString, this.grainReferenceConverter);
}
/// <summary>
/// Writes metrics to the database
/// </summary>
/// <param name="metricsData">Metrics data</param>
/// <returns>Task for database operation</returns>
public async Task ReportMetrics(IClientPerformanceMetrics metricsData)
{
if(logger != null && logger.IsVerbose3) logger.Verbose3("SqlStatisticsPublisher.ReportMetrics (client) called with data: {0}.", metricsData);
try
{
await orleansQueries.UpsertReportClientMetricsAsync(deploymentId, clientId, clientAddress, hostName, metricsData);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("SqlStatisticsPublisher.ReportMetrics (client) failed: {0}", ex);
throw;
}
}
Task ISiloMetricsDataPublisher.Init(string deploymentId, string storageConnectionString, SiloAddress siloAddress, string siloName, IPEndPoint gateway, string hostName)
{
return Task.CompletedTask;
}
/// <summary>
/// Writes silo performance metrics to the database
/// </summary>
/// <param name="metricsData">Metrics data</param>
/// <returns>Task for database operation</returns>
public async Task ReportMetrics(ISiloPerformanceMetrics metricsData)
{
if (logger != null && logger.IsVerbose3) logger.Verbose3("SqlStatisticsPublisher.ReportMetrics (silo) called with data: {0}.", metricsData);
try
{
await orleansQueries.UpsertSiloMetricsAsync(deploymentId, siloName, gateway, siloAddress, hostName, metricsData);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("SqlStatisticsPublisher.ReportMetrics (silo) failed: {0}", ex);
throw;
}
}
Task IStatisticsPublisher.Init(bool isSilo, string storageConnectionString, string deploymentId, string address, string siloName, string hostName)
{
return Task.CompletedTask;
}
/// <summary>
/// Writes statistics to the database
/// </summary>
/// <param name="statsCounters">Statistics counters to write</param>
/// <returns>Task for database opearation</returns>
public async Task ReportStats(List<ICounter> statsCounters)
{
var siloOrClientName = (isSilo) ? siloName : clientId;
var id = (isSilo) ? siloAddress.ToLongString() : string.Format("{0}:{1}", siloOrClientName, generation);
if (logger != null && logger.IsVerbose3) logger.Verbose3("ReportStats called with {0} counters, name: {1}, id: {2}", statsCounters.Count, siloOrClientName, id);
var insertTasks = new List<Task>();
try
{
//This batching is done for two reasons:
//1) For not to introduce a query large enough to be rejected.
//2) Performance, though using a fixed constants likely will not give the optimal performance in every situation.
const int maxBatchSizeInclusive = 200;
var counterBatches = BatchCounters(statsCounters, maxBatchSizeInclusive);
foreach(var counterBatch in counterBatches)
{
//The query template from which to retrieve the set of columns that are being inserted.
insertTasks.Add(orleansQueries.InsertStatisticsCountersAsync(deploymentId, hostName, siloOrClientName, id, counterBatch));
}
await Task.WhenAll(insertTasks);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("ReportStats faulted: {0}", ex.ToString());
foreach(var faultedTask in insertTasks.Where(t => t.IsFaulted))
{
if (logger != null && logger.IsVerbose) logger.Verbose("Faulted task exception: {0}", faultedTask.ToString());
}
throw;
}
if (logger != null && logger.IsVerbose) logger.Verbose("ReportStats SUCCESS");
}
/// <summary>
/// Batches the counters list to batches of given maximum size.
/// </summary>
/// <param name="counters">The counters to batch.</param>
/// <param name="maxBatchSizeInclusive">The maximum size of one batch.</param>
/// <returns>The counters batched.</returns>
private static List<List<ICounter>> BatchCounters(List<ICounter> counters, int maxBatchSizeInclusive)
{
var batches = new List<List<ICounter>>();
for(int i = 0; i < counters.Count; i += maxBatchSizeInclusive)
{
batches.Add(counters.GetRange(i, Math.Min(maxBatchSizeInclusive, counters.Count - i)));
}
return batches;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using Tekla.Structures;
using Tekla.Structures.Catalogs;
using Tekla.Structures.Dialog;
using Tekla.Structures.Dialog.UIControls;
using Tekla.Structures.Model;
using Tekla.Structures.Geometry3d;
using TSD = Tekla.Structures.Datatype;
namespace Exercise
{
public partial class Form1 : ApplicationFormBase
{
public Form1()
{
InitializeComponent();
base.InitializeForm();
FootingSize.Text = "1500";
MyModel = new Model();
}
private readonly Model MyModel;
/// <summary>
/// Callback function to create objects on corrent places.
/// Two loops are used to go through all positions.
/// </summary>
private void CreatePadFootings(object sender, EventArgs e)
{
// Always remember to check that you really have working connection
if (MyModel.GetConnectionStatus())
{
// Loop through X-axis (these loops should be changed to match current grid)
for (double PositionX = 0.0; PositionX <= 12000.0; PositionX += 3000.0)
{
// In first and in last line
if (PositionX.Equals(0.0) || PositionX.Equals(12000.0))
{
// Loop through Y-axis to get pad footings on the longer sides of the grid
for (double PositionY = 0.0; PositionY <= 30000.0; PositionY += 6000.0)
{
CreateFootingAndColumn(PositionX, PositionY);
}
}
else
{
CreateFootingAndColumn(PositionX, 0.0);
CreateFootingAndColumn(PositionX, 30000.0);
}
}
// Always remember to commit changes to Tekla Structures, otherwise some things might be left in uncertain state
MyModel.CommitChanges();
}
}
/// <summary>
/// Loop through all footings (Name == "FOOTING") and create rebar on those.
/// </summary>
private void CreateRebars()
{
if (MyModel.GetConnectionStatus())
{
ModelObjectEnumerator ObjectsInModel = MyModel.GetModelObjectSelector().GetAllObjects();
while (ObjectsInModel.MoveNext())
{
Beam MyBeam = ObjectsInModel.Current as Beam;
if (MyBeam != null && MyBeam.Name == "FOOTING") //use same name as given in exercise 1
{
//Here is included also method for checking if pad footing already has rebar
//This still adds the new rebar to it, but could also skip the creation of new rebar
ModelObjectEnumerator BeamChildren = MyBeam.GetChildren();
bool HasRebars = false;
while (BeamChildren.MoveNext())
{
if (BeamChildren.Current is Reinforcement)
{
HasRebars = true;
}
}
if (HasRebars)
{
CreateRebar(MyBeam, MyBeam.StartPoint.X, MyBeam.StartPoint.Y);
}
else
{
CreateRebar(MyBeam, MyBeam.StartPoint.X, MyBeam.StartPoint.Y);
}
}
}
MyModel.CommitChanges();
}
}
/// <summary>
/// Create rebar on the given object to given position using FootingSize from dialog.
/// Polygon for the rebar is calculated from position and FootingSize from dialog, Polygon could also
/// be calculated using PadFooting's extrema.
/// </summary>
/// <param name="PadFooting">Father of the rebar</param>
/// <param name="PositionX">X-coordination</param>
/// <param name="PositionY"></param>
/// <returns></returns>
private void CreateRebar(ModelObject PadFooting, double PositionX, double PositionY)
{
RebarGroup Rebar = new RebarGroup();
Polygon RebarPolygon1 = new Polygon();
double MyFootingSize = double.Parse(FootingSize.Text);
//use given position and footing size
RebarPolygon1.Points.Add(new Point(PositionX - MyFootingSize / 2.0, PositionY - MyFootingSize / 2.0, 0));
RebarPolygon1.Points.Add(new Point(PositionX + MyFootingSize / 2.0, PositionY - MyFootingSize / 2.0, 0));
RebarPolygon1.Points.Add(new Point(PositionX + MyFootingSize / 2.0, PositionY + MyFootingSize / 2.0, 0));
RebarPolygon1.Points.Add(new Point(PositionX - MyFootingSize / 2.0, PositionY + MyFootingSize / 2.0, 0));
RebarPolygon1.Points.Add(new Point(PositionX - MyFootingSize / 2.0, PositionY - MyFootingSize / 2.0, 0));
Rebar.Polygons.Add(RebarPolygon1);
//or calculate by rebar's solid's Axis Aligned Bounding Box
//Rebar.Polygons.Add(GetPolygonBySolidsAABB(PadFooting as Beam));
Rebar.StartPoint.X = PositionX;
Rebar.StartPoint.Y = PositionY;
Rebar.StartPoint.Z = 0.0;
Rebar.EndPoint.X = PositionX;
Rebar.EndPoint.Y = PositionY;
Rebar.EndPoint.Z = -500.0;
Rebar.Father = PadFooting;
Rebar.EndPointOffsetType = Reinforcement.RebarOffsetTypeEnum.OFFSET_TYPE_COVER_THICKNESS;
Rebar.EndPointOffsetValue = 20.0;
Rebar.StartPointOffsetType = Reinforcement.RebarOffsetTypeEnum.OFFSET_TYPE_COVER_THICKNESS;
Rebar.StartPointOffsetValue = 20.0;
Rebar.Class = 3;
Rebar.Name = "FootingRebar";
Rebar.Grade = GradeTextBox.Text;
Rebar.Size = SizeTextBox.Text;
char[] Separator = { ' ' };
string[] Radiuses = BendingRadiusTextBox.Text.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
foreach (string Item in Radiuses)
Rebar.RadiusValues.Add(Convert.ToDouble(Item));
Rebar.SpacingType = BaseRebarGroup.RebarGroupSpacingTypeEnum.SPACING_TYPE_TARGET_SPACE;
Rebar.Spacings.Add(100.0);
Rebar.ExcludeType = BaseRebarGroup.ExcludeTypeEnum.EXCLUDE_TYPE_BOTH;
Rebar.NumberingSeries.StartNumber = 0;
Rebar.NumberingSeries.Prefix = "Group";
Rebar.OnPlaneOffsets.Add(25.0);
Rebar.FromPlaneOffset = 40;
//Adding hooks to make rebar stronger
Rebar.StartHook.Shape = RebarHookData.RebarHookShapeEnum.HOOK_90_DEGREES;
Rebar.EndHook.Shape = RebarHookData.RebarHookShapeEnum.HOOK_90_DEGREES;
Rebar.OnPlaneOffsets.Add(10.0);
Rebar.OnPlaneOffsets.Add(25.0);
if (!Rebar.Insert())
{
Console.WriteLine("Inserting rebar failed.");
}
}
/// <summary>
/// Calculate polygon for rebar group by solid of InputObject.
/// Object's Axis Aligned Bounding Box (AABB) is used for calculation.
/// </summary>
/// <param name="InputObject"></param>
/// <returns></returns>
private Polygon GetPolygonBySolidsAABB(Part InputObject)
{
Polygon Result = new Polygon();
Solid BeamSolid = InputObject.GetSolid();
Result.Points.Add(new Point(BeamSolid.MaximumPoint.X, BeamSolid.MaximumPoint.Y, 0));
Result.Points.Add(new Point(BeamSolid.MinimumPoint.X, BeamSolid.MaximumPoint.Y, 0));
Result.Points.Add(new Point(BeamSolid.MinimumPoint.X, BeamSolid.MinimumPoint.Y, 0));
Result.Points.Add(new Point(BeamSolid.MaximumPoint.X, BeamSolid.MinimumPoint.Y, 0));
Result.Points.Add(new Point(BeamSolid.MaximumPoint.X, BeamSolid.MaximumPoint.Y, 0));
return Result;
}
private void FootingSize_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
CreateRebars();
}
/// <summary>
/// Create pad footing, column on a given position and create base plate connection between those
/// </summary>
/// <param name="PositionX">X-coordination of the position</param>
/// <param name="PositionY">Y-coordination of the position</param>
private void CreateFootingAndColumn(double PositionX, double PositionY)
{
ModelObject PadFooting = CreatePadFooting(PositionX, PositionY, double.Parse(FootingSize.Text));
ModelObject Column = CreateColumn(PositionX, PositionY);
CreateBasePlate(Column, PadFooting);
}
/// <summary>
/// Method that creates a pad footing on given position and returns the created pad footing.
/// The created pad footing is recognized as beam in Tekla Structures.
/// </summary>
/// <param name="PositionX">X-coordination of the position</param>
/// <param name="PositionY">Y-coordination of the position</param>
/// <param name="FootingSize">Size of the footing: FootingSize*FootingSize for profile</param>
/// <returns></returns>
private static ModelObject CreatePadFooting(double PositionX, double PositionY, double FootingSize)
{
Beam PadFooting = new Beam();
PadFooting.Name = "FOOTING";
PadFooting.Profile.ProfileString = FootingSize + "*" + FootingSize; //"1500*1500";
PadFooting.Material.MaterialString = "K30-2";
PadFooting.Class = "8";
PadFooting.StartPoint.X = PositionX;
PadFooting.StartPoint.Y = PositionY;
PadFooting.EndPoint.X = PositionX;
PadFooting.EndPoint.Y = PositionY;
PadFooting.EndPoint.Z = -500.0;
PadFooting.Position.Rotation = Position.RotationEnum.FRONT;
PadFooting.Position.Plane = Position.PlaneEnum.MIDDLE;
PadFooting.Position.Depth = Position.DepthEnum.MIDDLE;
if (!PadFooting.Insert())
{
Console.WriteLine("Insertion of pad footing failed.");
}
return PadFooting;
}
/// <summary>
/// Method that creates a column to given position and returns the created column.
/// The created pad footing is recognized as beam in Tekla Structures.
/// </summary>
/// <param name="PositionX">X-coordination of the position</param>
/// <param name="PositionY">Y-coordination of the position</param>
/// <returns></returns>
private ModelObject CreateColumn(double PositionX, double PositionY)
{
Beam Column = new Beam();
Column.Name = "COLUMN";
Column.Profile.ProfileString = ColumnsProfileTextBox.Text;
Column.Material.MaterialString = "S235JR";
Column.Class = "2";
Column.StartPoint.X = PositionX;
Column.StartPoint.Y = PositionY;
Column.EndPoint.X = PositionX;
Column.EndPoint.Y = PositionY;
Column.EndPoint.Z = 5000.0;
Column.Position.Rotation = Position.RotationEnum.FRONT;
Column.Position.Plane = Position.PlaneEnum.MIDDLE;
Column.Position.Depth = Position.DepthEnum.MIDDLE;
if (!Column.Insert())
{
Console.WriteLine("Insertion of column failed.");
}
return Column;
}
/// <summary>
/// Method that creates connection (1004) between two given objects.
/// </summary>
/// <param name="PrimaryObject"></param>
/// <param name="SecondaryObject"></param>
private static void CreateBasePlate(ModelObject PrimaryObject, ModelObject SecondaryObject)
{
Connection BasePlate = new Connection();
BasePlate.Name = "Stiffened Base Plate";
BasePlate.Number = 1014;
BasePlate.LoadAttributesFromFile("standard");
BasePlate.UpVector = new Vector(0, 0, 1000);
BasePlate.PositionType = PositionTypeEnum.COLLISION_PLANE;
BasePlate.SetPrimaryObject(PrimaryObject);
BasePlate.SetSecondaryObject(SecondaryObject);
BasePlate.SetAttribute("cut", 1); //Enable anchor rods
if (!BasePlate.Insert())
{
Console.WriteLine("Insertion of stiffened base plate failed.");
}
}
/*-----------------------------------------*
* Exercise 5-6 under this *
* ----------------------------------------*/
/// <summary>
/// Callback function to show the profile selection dialog. The value set in
/// ColumnsProfileTextBox is set as SelectedProfile to be selected in the
/// dialog (if it exists).
/// </summary>
private void profileCatalog1_SelectClicked(object sender, EventArgs e)
{
profileCatalog1.SelectedProfile = ColumnsProfileTextBox.Text;
}
/// <summary>
/// Callback function to show the value selected in the profile selection form.
/// </summary>
private void profileCatalog1_SelectionDone(object sender, EventArgs e)
{
SetAttributeValue(ColumnsProfileTextBox, profileCatalog1.SelectedProfile);
}
/// <summary>
/// Callback function to show the reinforcement selection dialog. The value set in
/// text box will be selected in the dialog (if it exists).
/// </summary>
private void reinforcementCatalog1_SelectClicked(object sender, EventArgs e)
{
reinforcementCatalog1.SelectedRebarSize = SizeTextBox.Text;
reinforcementCatalog1.SelectedRebarGrade = GradeTextBox.Text;
reinforcementCatalog1.SelectedRebarBendingRadius = TSD.Distance.Parse(BendingRadiusTextBox.Text, CultureInfo.InvariantCulture).Millimeters;
}
/// <summary>
/// Callback function to show the values selected in the reinforcement
/// selection form.
/// </summary>
private void reinforcementCatalog1_SelectionDone(object sender, EventArgs e)
{
SetAttributeValue(SizeTextBox, reinforcementCatalog1.SelectedRebarSize);
SetAttributeValue(GradeTextBox, reinforcementCatalog1.SelectedRebarGrade);
SetAttributeValue(BendingRadiusTextBox, new TSD.Distance(reinforcementCatalog1.SelectedRebarBendingRadius));
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.Core.Contents.Controllers;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Notify;
using M33.SystemEditor.ViewModels;
using System.Collections.Generic;
using Orchard.Themes.Services;
using Orchard;
/*
* Author Rickard Magnusson, M33 2011
*/
namespace M33.SystemEditor.Controllers {
[ValidateInput(false)]
public class AdminController : Controller, IUpdateModel {
private readonly ISiteThemeService _siteThemeService;
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
private string Current = string.Empty;
private FileType TypeOfFile;
public AdminController(IOrchardServices services, ISiteThemeService siteThemeService) {
Services = services;
_siteThemeService = siteThemeService;
T = NullLocalizer.Instance;
}
public ActionResult Index()
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage files")))
return new HttpUnauthorizedResult();
TypeOfFile = FileType.CSS;
try
{
var files = EnumerateFiles("");
var filename = files.First();
var file = new StreamReader(filename.Path);
var data = file.ReadToEnd();
file.Close();
var viewModel = new FileViewModel { Content = data, FileName = filename.Name, Files = files};
return View(viewModel);
}
catch
{
return View();
}
}
public ActionResult ViewEditor()
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage css")))
return new HttpUnauthorizedResult();
TypeOfFile = FileType.RAZOR;
try
{
var files = EnumerateFiles("");
var filename = files.First();
var file = new StreamReader(filename.Path);
var data = file.ReadToEnd();
file.Close();
var viewModel = new FileViewModel { Content = data, FileName = filename.Name, Files = files };
return View(viewModel);
}
catch
{
return View();
}
}
public ActionResult JsEditor()
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage css")))
return new HttpUnauthorizedResult();
TypeOfFile = FileType.JS;
try
{
var files = EnumerateFiles("");
var filename = files.First();
var file = new StreamReader(filename.Path);
var data = file.ReadToEnd();
file.Close();
var viewModel = new FileViewModel { Content = data, FileName = filename.Name, Files = files };
return View(viewModel);
}
catch
{
var f = new FileViewModel { FileType = ViewModels.FileType.JS, Content = string.Empty, FileName = string.Empty, Files = new List<FileModel> { new FileModel { Current = false, Name = "No js", Path = string.Empty } } };
return View(f);
}
}
public JsonResult Load(string fileName)
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage files")))
return null;
var toload = new StreamReader(fileName);
var data = toload.ReadToEnd();
toload.Close();
FileViewModel viewModel = new FileViewModel { Content = data, FileName = new FileInfo(fileName).Name, Files = EnumerateFiles(fileName) };
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
public JsonResult Save(string fileName, string content)
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage files")))
return null;
using (var f = new System.IO.StreamWriter(fileName))
f.Write(content);
return Load(fileName);
}
public ActionResult Add()
{
var viewModel = new AddFile { FileName = string.Empty, TypeOfFile = "" };
return View(viewModel);
}
public ActionResult Settings()
{
var viewModel = new Settings { Description=string.Empty, Placement=string.Empty };
string path = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/Themes/{0}/", _siteThemeService.GetCurrentThemeName()));
var theme = System.IO.File.OpenText(Path.Combine(path, "Theme.txt"));
viewModel.Description = theme.ReadToEnd();
theme.Close();
var place = System.IO.File.OpenText(Path.Combine(path, "Placement.info"));
viewModel.Placement = place.ReadToEnd();
place.Close();
return View(viewModel);
}
[HttpPost, ActionName("Settings")]
public ActionResult SettingsPOST()
{
var viewModel = new Settings { Description = string.Empty, Placement = string.Empty };
string path = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/Themes/{0}/", _siteThemeService.GetCurrentThemeName()));
UpdateModel(viewModel);
using (var f = new System.IO.StreamWriter(Path.Combine(path, "Theme.txt"))){
f.Write(viewModel.Description);
Services.Notifier.Information(T("Updated Theme.txt successfully."));
}
using (var f = new System.IO.StreamWriter(Path.Combine(path, "Placement.info"))){
f.Write(viewModel.Placement);
Services.Notifier.Information(T("Updated Placement.info successfully."));
}
try
{
if (!String.IsNullOrWhiteSpace(Request.Files[0].FileName)){
Request.Files["ThemeImage"].SaveAs(Path.Combine(path, "Theme.png"));
Services.Notifier.Information(T("Updated/added Theme.png successfully."));
}
if (!String.IsNullOrWhiteSpace(Request.Files[1].FileName)){
Request.Files["ThemeZoneImage"].SaveAs(Path.Combine(path, "ThemeZonePreview.png"));
Services.Notifier.Information(T("Updated/added ThemeZonePreview.png successfully."));
}
if (!String.IsNullOrWhiteSpace(Request.Files[2].FileName))
{
Request.Files["ThemeExtended"].SaveAs(Path.Combine(path, Request.Files["ThemeExtended"].FileName));
Services.Notifier.Information(T("Added image successfully."));
}
}catch (Exception exception){
this.AddModelError("Upload failed", T("Uploading media file failed:" + exception.ToString()));
return View(viewModel);
}
return Settings();
}
[FormValueRequired("submit")]
[HttpPost, ActionName("Add")]
public ActionResult AddPost()
{
var viewModel = new AddFile{ FileName=string.Empty, TypeOfFile = "" };
string folder = string.Empty;
string extension = string.Empty;
string view = string.Empty;
if (TryUpdateModel(viewModel))
{
switch (viewModel.TypeOfFile)
{
case "css":
extension = ".css";
folder = "Styles";
view = "Index";
break;
case "js":
extension = ".js";
folder = "Scripts";
view = "JsEditor";
break;
case "razor":
extension = ".cshtml";
folder = "Views";
view = "ViewEditor";
break;
}
var filename = string.Format("{0}{1}", viewModel.FileName, extension);
string path = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/Themes/{0}/{1}/{2}", _siteThemeService.GetCurrentThemeName(), folder, filename));
if (System.IO.File.Exists(path))
AddModelError("Filename error", T("This file already exist.Choose another filename!", viewModel.FileName));
using (var f = System.IO.File.CreateText(path)) { }
}
return RedirectToAction(view);
}
private IEnumerable<FileModel> EnumerateFiles(string filepath)
{
string extension = "*.css";
string folder = "Styles";
switch (TypeOfFile)
{
case FileType.CSS:
extension = "*.css";
folder = "Styles";
break;
case FileType.JS:
extension = "*.js";
folder = "Scripts";
break;
case FileType.RAZOR:
extension = "*.cshtml";
folder = "Views";
break;
}
string path = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/Themes/{0}/{1}/", _siteThemeService.GetCurrentThemeName(),folder));
var files = Directory.EnumerateFiles(path, extension);
var docs = new List<FileModel>();
foreach (string f in files)
docs.Add(new FileModel { Name = new FileInfo(f).Name, Path = f, Current = (f == filepath) });
if (string.IsNullOrEmpty(filepath))
docs.First().Current = true;
return docs;
}
private FileType GetFileType(string path)
{
if (path.EndsWith(".css"))
return FileType.CSS;
else
return FileType.RAZOR;
}
bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
}
void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
public void AddModelError(string key, LocalizedString errorMessage) {
ModelState.AddModelError(key, errorMessage.ToString());
}
}
}
| |
//
// 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;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery
{
/// <summary>
/// Definition of recoveryplan operations for the Site Recovery extension.
/// </summary>
public partial interface IRecoveryPlanOperations
{
/// <summary>
/// Commit the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginCommitAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Create the recovery plan.
/// </summary>
/// <param name='input'>
/// Create recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginCreateRecoveryPlanAsync(RecoveryPlanXmlData input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Remove a Recovery Plan from the current Azure Site Recovery Vault.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginDeleteAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// PlannedFailover for the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='input'>
/// Input to do planned failover of a recovery plan.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginRecoveryPlanPlannedFailoverAsync(string name, RpPlannedFailoverRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// TestFailover for the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='input'>
/// Input to do test failover of a recovery plan.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginRecoveryPlanTestFailoverAsync(string name, RpTestFailoverRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// UnplannedFailover for the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan ID.
/// </param>
/// <param name='input'>
/// Input to do unplanned failover of a recovery plan.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginRecoveryPlanUnplannedFailoverAsync(string name, RpUnplannedFailoverRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Reprotect the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginReprotectAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Update the recovery plan.
/// </summary>
/// <param name='input'>
/// Update recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> BeginUpdateRecoveryPlanAsync(RecoveryPlanXmlData input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Commit the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> CommitAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Create the recovery plan.
/// </summary>
/// <param name='input'>
/// Create recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> CreateRecoveryPlanAsync(RecoveryPlanXmlData input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Remove a Recovery Plan from the current Azure Site Recovery Vault.
/// </summary>
/// <param name='name'>
/// RecoveryPlan name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> DeleteAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Get the recovery plan by the ID.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Recovery Plan object.
/// </returns>
Task<RecoveryPlanResponse> GetAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanCommitStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanCreateStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanDeleteStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanPlannedFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanReprotectStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanTestFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetRecoveryPlanUnplannedFailoverStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Get the recovery plan xml by the ID.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The xml output for the recoveryplan object.
/// </returns>
Task<RecoveryPlanXmlOuput> GetRecoveryPlanXmlAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<RecoveryPlanOperationResponse> GetUpdateRecoveryPlanUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken);
/// <summary>
/// Get the list of all recoveryplans under the resource.
/// </summary>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list recoveryplans operation.
/// </returns>
Task<RecoveryPlanListResponse> ListAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// PlannedFailover for the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='input'>
/// Input to do planned failover of a recovery plan.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> RecoveryPlanPlannedFailoverAsync(string name, RpPlannedFailoverRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// TestFailover for the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='input'>
/// Input to do test failover of a recovery plan.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> RecoveryPlanTestFailoverAsync(string name, RpTestFailoverRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// UnplannedFailover for the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='input'>
/// Input to do unplanned failover of a recovery plan.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> RecoveryPlanUnplannedFailoverAsync(string name, RpUnplannedFailoverRequest input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Reprotect the recovery plan.
/// </summary>
/// <param name='name'>
/// RecoveryPlan Name.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> ReprotectAsync(string name, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
/// <summary>
/// Update the recovery plan.
/// </summary>
/// <param name='input'>
/// Update recovery plan input parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
Task<LongRunningOperationResponse> UpdateRecoveryPlanAsync(RecoveryPlanXmlData input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Util;
using System.Collections.Generic;
using System.Reflection;
namespace Lucene.Net.Index
{
//using AlreadySetException = Lucene.Net.Util.SetOnce.AlreadySetException;
using NUnit.Framework;
using Codec = Lucene.Net.Codecs.Codec;
using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using IndexingChain = Lucene.Net.Index.DocumentsWriterPerThread.IndexingChain;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using InfoStream = Lucene.Net.Util.InfoStream;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
using Store = Field.Store;
[TestFixture]
public class TestIndexWriterConfig : LuceneTestCase
{
private sealed class MySimilarity : DefaultSimilarity
{
// Does not implement anything - used only for type checking on IndexWriterConfig.
}
public class MyIndexingChain : IndexingChain
{
// Does not implement anything - used only for type checking on IndexWriterConfig.
public override DocConsumer GetChain(DocumentsWriterPerThread documentsWriter)
{
return null;
}
}
[Test]
public virtual void TestDefaults()
{
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
Assert.AreEqual(typeof(MockAnalyzer), conf.Analyzer.GetType());
Assert.IsNull(conf.IndexCommit);
Assert.AreEqual(typeof(KeepOnlyLastCommitDeletionPolicy), conf.DelPolicy.GetType());
Assert.AreEqual(typeof(ConcurrentMergeScheduler), conf.MergeScheduler.GetType());
Assert.AreEqual(OpenMode_e.CREATE_OR_APPEND, conf.OpenMode);
// we don't need to assert this, it should be unspecified
Assert.IsTrue(IndexSearcher.DefaultSimilarity == conf.Similarity);
Assert.AreEqual(IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL, conf.TermIndexInterval);
Assert.AreEqual(IndexWriterConfig.DefaultWriteLockTimeout, conf.WriteLockTimeout);
Assert.AreEqual(IndexWriterConfig.WRITE_LOCK_TIMEOUT, IndexWriterConfig.DefaultWriteLockTimeout);
Assert.AreEqual(IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS, conf.MaxBufferedDeleteTerms);
Assert.AreEqual(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB, conf.RAMBufferSizeMB, 0.0);
Assert.AreEqual(IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS, conf.MaxBufferedDocs);
Assert.AreEqual(IndexWriterConfig.DEFAULT_READER_POOLING, conf.ReaderPooling);
Assert.IsTrue(DocumentsWriterPerThread.DefaultIndexingChain == conf.IndexingChain);
Assert.IsNull(conf.MergedSegmentWarmer);
Assert.AreEqual(IndexWriterConfig.DEFAULT_READER_TERMS_INDEX_DIVISOR, conf.ReaderTermsIndexDivisor);
Assert.AreEqual(typeof(TieredMergePolicy), conf.MergePolicy.GetType());
Assert.AreEqual(typeof(ThreadAffinityDocumentsWriterThreadPool), conf.IndexerThreadPool.GetType());
Assert.AreEqual(typeof(FlushByRamOrCountsPolicy), conf.FlushPolicy.GetType());
Assert.AreEqual(IndexWriterConfig.DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB, conf.RAMPerThreadHardLimitMB);
Assert.AreEqual(Codec.Default, conf.Codec);
Assert.AreEqual(InfoStream.Default, conf.InfoStream);
Assert.AreEqual(IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM, conf.UseCompoundFile);
// Sanity check - validate that all getters are covered.
HashSet<string> getters = new HashSet<string>();
getters.Add("getAnalyzer");
getters.Add("getIndexCommit");
getters.Add("getIndexDeletionPolicy");
getters.Add("getMaxFieldLength");
getters.Add("getMergeScheduler");
getters.Add("getOpenMode");
getters.Add("getSimilarity");
getters.Add("getTermIndexInterval");
getters.Add("getWriteLockTimeout");
getters.Add("getDefaultWriteLockTimeout");
getters.Add("getMaxBufferedDeleteTerms");
getters.Add("getRAMBufferSizeMB");
getters.Add("getMaxBufferedDocs");
getters.Add("getIndexingChain");
getters.Add("getMergedSegmentWarmer");
getters.Add("getMergePolicy");
getters.Add("getMaxThreadStates");
getters.Add("getReaderPooling");
getters.Add("getIndexerThreadPool");
getters.Add("getReaderTermsIndexDivisor");
getters.Add("getFlushPolicy");
getters.Add("getRAMPerThreadHardLimitMB");
getters.Add("getCodec");
getters.Add("getInfoStream");
getters.Add("getUseCompoundFile");
foreach (MethodInfo m in typeof(IndexWriterConfig).GetMethods())
{
if (m.DeclaringType == typeof(IndexWriterConfig) && m.Name.StartsWith("get") && !m.Name.StartsWith("get_"))
{
Assert.IsTrue(getters.Contains(m.Name), "method " + m.Name + " is not tested for defaults");
}
}
}
[Test]
public virtual void TestSettersChaining()
{
// Ensures that every setter returns IndexWriterConfig to allow chaining.
HashSet<string> liveSetters = new HashSet<string>();
HashSet<string> allSetters = new HashSet<string>();
foreach (MethodInfo m in typeof(IndexWriterConfig).GetMethods())
{
if (m.Name.StartsWith("Set") && !m.IsStatic)
{
allSetters.Add(m.Name);
// setters overridden from LiveIndexWriterConfig are returned twice, once with
// IndexWriterConfig return type and second with LiveIndexWriterConfig. The ones
// from LiveIndexWriterConfig are marked 'synthetic', so just collect them and
// assert in the end that we also received them from IWC.
// In C# we do not have them marked synthetic so we look at the declaring type instead.
if (m.DeclaringType.Name == "LiveIndexWriterConfig")
{
liveSetters.Add(m.Name);
}
else
{
Assert.AreEqual(typeof(IndexWriterConfig), m.ReturnType, "method " + m.Name + " does not return IndexWriterConfig");
}
}
}
foreach (string setter in liveSetters)
{
Assert.IsTrue(allSetters.Contains(setter), "setter method not overridden by IndexWriterConfig: " + setter);
}
}
[Test]
public virtual void TestReuse()
{
Directory dir = NewDirectory();
// test that IWC cannot be reused across two IWs
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, null);
(new RandomIndexWriter(Random(), dir, conf)).Dispose();
// this should fail
try
{
Assert.IsNotNull(new RandomIndexWriter(Random(), dir, conf));
Assert.Fail("should have hit AlreadySetException");
}
catch (SetOnce<IndexWriter>.AlreadySetException e)
{
// expected
}
// also cloning it won't help, after it has been used already
try
{
Assert.IsNotNull(new RandomIndexWriter(Random(), dir, (IndexWriterConfig)conf.Clone()));
Assert.Fail("should have hit AlreadySetException");
}
catch (SetOnce<IndexWriter>.AlreadySetException e)
{
// expected
}
// if it's cloned in advance, it should be ok
conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, null);
(new RandomIndexWriter(Random(), dir, (IndexWriterConfig)conf.Clone())).Dispose();
(new RandomIndexWriter(Random(), dir, (IndexWriterConfig)conf.Clone())).Dispose();
dir.Dispose();
}
[Test]
public virtual void TestOverrideGetters()
{
// Test that IndexWriterConfig overrides all getters, so that javadocs
// contain all methods for the users. Also, ensures that IndexWriterConfig
// doesn't declare getters that are not declared on LiveIWC.
HashSet<string> liveGetters = new HashSet<string>();
foreach (MethodInfo m in typeof(LiveIndexWriterConfig).GetMethods())
{
if (m.Name.StartsWith("get") && !m.IsStatic)
{
liveGetters.Add(m.Name);
}
}
foreach (MethodInfo m in typeof(IndexWriterConfig).GetMethods())
{
if (m.Name.StartsWith("get") && !m.Name.StartsWith("get_") && !m.IsStatic)
{
Assert.AreEqual(typeof(IndexWriterConfig), m.DeclaringType, "method " + m.Name + " not overrided by IndexWriterConfig");
Assert.IsTrue(liveGetters.Contains(m.Name), "method " + m.Name + " not declared on LiveIndexWriterConfig");
}
}
}
[Test]
public virtual void TestConstants()
{
// Tests that the values of the constants does not change
Assert.AreEqual(1000, IndexWriterConfig.WRITE_LOCK_TIMEOUT);
Assert.AreEqual(32, IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL);
Assert.AreEqual(-1, IndexWriterConfig.DISABLE_AUTO_FLUSH);
Assert.AreEqual(IndexWriterConfig.DISABLE_AUTO_FLUSH, IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS);
Assert.AreEqual(IndexWriterConfig.DISABLE_AUTO_FLUSH, IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS);
Assert.AreEqual(16.0, IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB, 0.0);
Assert.AreEqual(false, IndexWriterConfig.DEFAULT_READER_POOLING);
Assert.AreEqual(true, IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM);
Assert.AreEqual(DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, IndexWriterConfig.DEFAULT_READER_TERMS_INDEX_DIVISOR);
}
//LUCENE TODO: Compilation problems
/*[Test]
public virtual void TestToString()
{
string str = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).ToString();
foreach (Field f in typeof(IndexWriterConfig).DeclaredFields)
{
int modifiers = f.Modifiers;
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers))
{
// Skip static final fields, they are only constants
continue;
}
else if ("indexingChain".Equals(f.Name))
{
// indexingChain is a package-private setting and thus is not output by
// toString.
continue;
}
if (f.Name.Equals("inUseByIndexWriter"))
{
continue;
}
Assert.IsTrue(str.IndexOf(f.Name) != -1, f.Name + " not found in toString");
}
}*/
[Test]
public virtual void TestClone()
{
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
IndexWriterConfig clone = (IndexWriterConfig)conf.Clone();
// Make sure parameters that can't be reused are cloned
IndexDeletionPolicy delPolicy = conf.DelPolicy;
IndexDeletionPolicy delPolicyClone = clone.DelPolicy;
Assert.IsTrue(delPolicy.GetType() == delPolicyClone.GetType() && (delPolicy != delPolicyClone || delPolicy.Clone() == delPolicyClone.Clone()));
FlushPolicy flushPolicy = conf.FlushPolicy;
FlushPolicy flushPolicyClone = clone.FlushPolicy;
Assert.IsTrue(flushPolicy.GetType() == flushPolicyClone.GetType() && (flushPolicy != flushPolicyClone || flushPolicy.Clone() == flushPolicyClone.Clone()));
DocumentsWriterPerThreadPool pool = conf.IndexerThreadPool;
DocumentsWriterPerThreadPool poolClone = clone.IndexerThreadPool;
Assert.IsTrue(pool.GetType() == poolClone.GetType() && (pool != poolClone || pool.Clone() == poolClone.Clone()));
MergePolicy mergePolicy = conf.MergePolicy;
MergePolicy mergePolicyClone = clone.MergePolicy;
Assert.IsTrue(mergePolicy.GetType() == mergePolicyClone.GetType() && (mergePolicy != mergePolicyClone || mergePolicy.Clone() == mergePolicyClone.Clone()));
MergeScheduler mergeSched = conf.MergeScheduler;
MergeScheduler mergeSchedClone = clone.MergeScheduler;
Assert.IsTrue(mergeSched.GetType() == mergeSchedClone.GetType() && (mergeSched != mergeSchedClone || mergeSched.Clone() == mergeSchedClone.Clone()));
conf.SetMergeScheduler(new SerialMergeScheduler());
Assert.AreEqual(typeof(ConcurrentMergeScheduler), clone.MergeScheduler.GetType());
}
[Test]
public virtual void TestInvalidValues()
{
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
// Test IndexDeletionPolicy
Assert.AreEqual(typeof(KeepOnlyLastCommitDeletionPolicy), conf.DelPolicy.GetType());
conf.SetIndexDeletionPolicy(new SnapshotDeletionPolicy(null));
Assert.AreEqual(typeof(SnapshotDeletionPolicy), conf.DelPolicy.GetType());
try
{
conf.SetIndexDeletionPolicy(null);
Assert.Fail();
}
catch (System.ArgumentException e)
{
// ok
}
// Test MergeScheduler
Assert.AreEqual(typeof(ConcurrentMergeScheduler), conf.MergeScheduler.GetType());
conf.SetMergeScheduler(new SerialMergeScheduler());
Assert.AreEqual(typeof(SerialMergeScheduler), conf.MergeScheduler.GetType());
try
{
conf.SetMergeScheduler(null);
Assert.Fail();
}
catch (System.ArgumentException e)
{
// ok
}
// Test Similarity:
// we shouldnt assert what the default is, just that its not null.
Assert.IsTrue(IndexSearcher.DefaultSimilarity == conf.Similarity);
conf.SetSimilarity(new MySimilarity());
Assert.AreEqual(typeof(MySimilarity), conf.Similarity.GetType());
try
{
conf.SetSimilarity(null);
Assert.Fail();
}
catch (System.ArgumentException e)
{
// ok
}
// Test IndexingChain
Assert.IsTrue(DocumentsWriterPerThread.DefaultIndexingChain == conf.IndexingChain);
conf.SetIndexingChain(new MyIndexingChain());
Assert.AreEqual(typeof(MyIndexingChain), conf.IndexingChain.GetType());
try
{
conf.SetIndexingChain(null);
Assert.Fail();
}
catch (System.ArgumentException e)
{
// ok
}
try
{
conf.SetMaxBufferedDeleteTerms(0);
Assert.Fail("should not have succeeded to set maxBufferedDeleteTerms to 0");
}
catch (System.ArgumentException e)
{
// this is expected
}
try
{
conf.SetMaxBufferedDocs(1);
Assert.Fail("should not have succeeded to set maxBufferedDocs to 1");
}
catch (System.ArgumentException e)
{
// this is expected
}
try
{
// Disable both MAX_BUF_DOCS and RAM_SIZE_MB
conf.SetMaxBufferedDocs(4);
conf.SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
conf.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
Assert.Fail("should not have succeeded to disable maxBufferedDocs when ramBufferSizeMB is disabled as well");
}
catch (System.ArgumentException e)
{
// this is expected
}
conf.SetRAMBufferSizeMB(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB);
conf.SetMaxBufferedDocs(IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS);
try
{
conf.SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);
Assert.Fail("should not have succeeded to disable ramBufferSizeMB when maxBufferedDocs is disabled as well");
}
catch (System.ArgumentException e)
{
// this is expected
}
// Test setReaderTermsIndexDivisor
try
{
conf.SetReaderTermsIndexDivisor(0);
Assert.Fail("should not have succeeded to set termsIndexDivisor to 0");
}
catch (System.ArgumentException e)
{
// this is expected
}
// Setting to -1 is ok
conf.SetReaderTermsIndexDivisor(-1);
try
{
conf.SetReaderTermsIndexDivisor(-2);
Assert.Fail("should not have succeeded to set termsIndexDivisor to < -1");
}
catch (System.ArgumentException e)
{
// this is expected
}
try
{
conf.SetRAMPerThreadHardLimitMB(2048);
Assert.Fail("should not have succeeded to set RAMPerThreadHardLimitMB to >= 2048");
}
catch (System.ArgumentException e)
{
// this is expected
}
try
{
conf.SetRAMPerThreadHardLimitMB(0);
Assert.Fail("should not have succeeded to set RAMPerThreadHardLimitMB to 0");
}
catch (System.ArgumentException e)
{
// this is expected
}
// Test MergePolicy
Assert.AreEqual(typeof(TieredMergePolicy), conf.MergePolicy.GetType());
conf.SetMergePolicy(new LogDocMergePolicy());
Assert.AreEqual(typeof(LogDocMergePolicy), conf.MergePolicy.GetType());
try
{
conf.SetMergePolicy(null);
Assert.Fail();
}
catch (System.ArgumentException e)
{
// ok
}
}
[Test]
public virtual void TestLiveChangeToCFS()
{
Directory dir = NewDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
iwc.SetMergePolicy(NewLogMergePolicy(true));
// Start false:
iwc.SetUseCompoundFile(false);
iwc.MergePolicy.NoCFSRatio = 0.0d;
IndexWriter w = new IndexWriter(dir, iwc);
// Change to true:
w.Config.SetUseCompoundFile(true);
Document doc = new Document();
doc.Add(NewStringField("field", "foo", Store.NO));
w.AddDocument(doc);
w.Commit();
Assert.IsTrue(w.NewestSegment().Info.UseCompoundFile, "Expected CFS after commit");
doc.Add(NewStringField("field", "foo", Store.NO));
w.AddDocument(doc);
w.Commit();
w.ForceMerge(1);
w.Commit();
// no compound files after merge
Assert.IsFalse(w.NewestSegment().Info.UseCompoundFile, "Expected Non-CFS after merge");
MergePolicy lmp = w.Config.MergePolicy;
lmp.NoCFSRatio = 1.0;
lmp.MaxCFSSegmentSizeMB = double.PositiveInfinity;
w.AddDocument(doc);
w.ForceMerge(1);
w.Commit();
Assert.IsTrue(w.NewestSegment().Info.UseCompoundFile, "Expected CFS after merge");
w.Dispose();
dir.Dispose();
}
}
}
| |
// <copyright file="Settings.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BeanIO.Config;
using BeanIO.Config.SchemeHandlers;
using NodaTime;
namespace BeanIO.Internal.Util
{
/// <summary>
/// <see cref="Settings"/> is used to load and store BeanIO configuration settings.
/// </summary>
internal class Settings
{
/// <summary>
/// This property is set to the fully qualified class name of the default stream factory implementation
/// </summary>
public static readonly string STREAM_FACTORY_CLASS = "org.beanio.streamFactory";
/// <summary>
/// The default locale used by type handlers
/// </summary>
public static readonly string DEFAULT_LOCALE = "org.beanio.defaultTypeHandlerLocale";
/// <summary>
/// The default date format pattern for fields assigned type alias <see cref="DateTime"/>
/// </summary>
public static readonly string DEFAULT_DATE_FORMAT = "org.beanio.defaultDateFormat";
/// <summary>
/// The default date format pattern for fields assigned type alias <see cref="DateTime"/> or of type <see cref="LocalDate"/>
/// </summary>
public static readonly string DEFAULT_DATETIME_FORMAT = "org.beanio.defaultDateTimeFormat";
/// <summary>
/// The default date format pattern for fields assigned type alias <see cref="LocalTime"/>
/// </summary>
public static readonly string DEFAULT_TIME_FORMAT = "org.beanio.defaultTimeFormat";
/// <summary>
/// Whether property values support the following escape sequences
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><code>\\</code> - Backslash</item>
/// <item><code>\n</code> - Line Feed</item>
/// <item><code>\r</code> - Carriage Return</item>
/// <item><code>\t</code> - Tab</item>
/// <item><code>\f</code> - Form Feed</item>
/// <item><code>\0</code> - Null</item>
/// </list>
/// <para>A backslash preceding any other character is ignored.</para>
/// <para>Set to <code>false</code> to disable.</para>
/// </remarks>
public static readonly string PROPERTY_ESCAPING_ENABLED = "org.beanio.propertyEscapingEnabled";
/// <summary>
/// Whether the null character can be escaped using <code>\0</code> when property escaping is enabled.
/// </summary>
public static readonly string NULL_ESCAPING_ENABLED = "org.beanio.propertyEscapingEnabled";
/// <summary>
/// Whether property substitution is enabled for mapping files
/// </summary>
public static readonly string PROPERTY_SUBSTITUTION_ENABLED = "org.beanio.propertySubstitutionEnabled";
/// <summary>
/// The default XML type for a field definition, set to <code>element</code> or <code>attribute</code>.
/// </summary>
public static readonly string DEFAULT_XML_TYPE = "org.beanio.xml.defaultXmlType";
/// <summary>
/// The default namespace prefix for 'http://www.w3.org/2001/XMLSchema-instance'
/// </summary>
public static readonly string DEFAULT_XSI_NAMESPACE_PREFIX = "org.beanio.xml.xsiNamespacePrefix";
/// <summary>
/// Used for Spring Batch integration. Set to 'true' to have the XmlWriter only update the execution context (state)
/// with changes since the last update. At the time of writing, it's not known whether Spring Batch will create a new
/// ExecutionContext every time state is updated, or if the current context is used. Disabled by default until proven
/// the optimization will not impact state updates.
/// </summary>
public static readonly string XML_WRITER_UPDATE_STATE_USING_DELTA = "org.beanio.stream.xml.XmlWriter.deltaEnabled";
/// <summary>
/// Whether a configured field default is marshalled for null property values. The default configuration
/// sets this property to <code>true</code>.
/// </summary>
public static readonly string DEFAULT_MARSHALLING_ENABLED = "org.beanio.marshalDefaultEnabled";
/// <summary>
/// Whether a configured field default is unmarshalled on initialization. The default configuration
/// sets this property to <code>true</code>.
/// </summary>
/// <remarks>
/// This is useful when the default value cannot be represented using the underlying type.
/// </remarks>
public static readonly string DEFAULT_PARSING_ENABLED = "org.beanio.parseDefaultEnabled";
/// <summary>
/// The default minOccurs setting for a group.
/// </summary>
public static readonly string DEFAULT_GROUP_MIN_OCCURS = "org.beanio.group.minOccurs";
/// <summary>
/// The default minOccurs setting for a record.
/// </summary>
public static readonly string DEFAULT_RECORD_MIN_OCCURS = "org.beanio.record.minOccurs";
/// <summary>
/// The default minOccurs setting for a field (after appending the stream format)
/// </summary>
public static readonly string DEFAULT_FIELD_MIN_OCCURS = "org.beanio.field.minOccurs";
/// <summary>
/// The method of property access to use, <code>reflection</code> (default) or <code>asm</code> is supported
/// </summary>
public static readonly string PROPERTY_ACCESSOR_METHOD = "org.beanio.propertyAccessorFactory";
/// <summary>
/// Whether version 2.0.0 style unmarshalling should be supported which instantiates bean objects
/// for missing fields and records during unmarshalling. This behavior is not recommended.
/// </summary>
public static readonly string CREATE_MISSING_BEANS = "org.beanio.createMissingBeans";
/// <summary>
/// Whether objects are lazily instantiated if Strings are empty, rather than just null.
/// </summary>
public static readonly string LAZY_IF_EMPTY = "org.beanio.lazyIfEmpty";
/// <summary>
/// Whether null field values should throw an exception if bound to a primitive
/// </summary>
public static readonly string ERROR_IF_NULL_PRIMITIVE = "org.beanio.errorIfNullPrimitive";
/// <summary>
/// Whether default field values apply to missing fields
/// </summary>
public static readonly string USE_DEFAULT_IF_MISSING = "org.beanio.useDefaultIfMissing";
/// <summary>
/// Whether to validate marshalled fields
/// </summary>
public static readonly string VALIDATE_ON_MARSHAL = "org.beanio.validateOnMarshal";
/// <summary>
/// Whether XML components should be sorted by position. Helpful for use with annotations
/// where fields and methods may not be ordered by their position in the stream.
/// </summary>
public static readonly string SORT_XML_COMPONENTS_BY_POSITION = "org.beanio.xml.sorted";
/// <summary>
/// Whether non-public fields and methods may be made accessible.
/// </summary>
public static readonly string ALLOW_PROTECTED_PROPERTY_ACCESS = "org.beanio.allowProtectedAccess";
private const string DEFAULT_CONFIGURATION_PATH = "BeanIO.Internal.Config.beanio.properties";
private static readonly object _syncRoot = new object();
private static Settings _instance;
private readonly Properties _properties;
private readonly Dictionary<string, ISchemeHandler> _schemeHandlers = new Dictionary<string, ISchemeHandler>();
/// <summary>
/// Initializes a new instance of the <see cref="Settings"/> class.
/// </summary>
/// <param name="properties">The properties to use for this settings object.</param>
public Settings(Properties properties)
{
_properties = properties;
Add(new ResourceSchemeHandler());
}
/// <summary>
/// Gets or sets the global <see cref="Settings"/> instance.
/// </summary>
public static Settings Instance
{
get
{
lock (_syncRoot)
return _instance ?? (_instance = new Settings(CreateDefaultProvider().Read()));
}
set
{
lock (_syncRoot)
_instance = value;
}
}
/// <summary>
/// Gets all registered scheme handlers
/// </summary>
public IReadOnlyDictionary<string, ISchemeHandler> SchemeHandlers => _schemeHandlers;
/// <summary>
/// Returns a BeanIO configuration setting
/// </summary>
/// <param name="key">the name of the setting</param>
/// <returns>the value of the setting, or null if the name is invalid</returns>
public string this[string key]
{
get
{
string result;
if (_properties.TryGetValue(key, out result))
return result;
return null;
}
}
/// <summary>
/// Returns a BeanIO configuration setting
/// </summary>
/// <param name="key">the name of the setting</param>
/// <returns>the value of the setting, or null if the name is invalid</returns>
public string GetProperty(string key)
{
return this[key];
}
/// <summary>
/// Returns the boolean value of a BeanIO configuration setting
/// </summary>
/// <param name="key">the property key</param>
/// <returns>true if the property value is "1" or "true" (case insensitive),
/// or false if the property is any other value</returns>
public bool GetBoolean(string key)
{
var temp = this[key];
if (string.IsNullOrEmpty(temp))
return false;
temp = temp.Trim();
if (string.Equals("true", temp, StringComparison.OrdinalIgnoreCase))
return true;
return temp == "1";
}
/// <summary>
/// Returns a BeanIO configuration setting as an integer
/// </summary>
/// <param name="key">the property key</param>
/// <param name="defaultValue">the default value if the setting wasn't configured or invalid</param>
/// <returns>the <code>int</code> property value or <paramref name="defaultValue"/></returns>
public int GetInt(string key, int defaultValue)
{
var temp = this[key];
if (string.IsNullOrWhiteSpace(temp))
return defaultValue;
int result;
if (int.TryParse(temp, out result))
return result;
return defaultValue;
}
/// <summary>
/// Adds a new <see cref="ISchemeHandler"/>
/// </summary>
/// <param name="handler">the handler to add</param>
public void Add(ISchemeHandler handler)
{
_schemeHandlers[handler.Scheme] = handler;
}
public ISchemeHandler GetSchemeHandler(Uri url, bool throwIfMissing)
{
return GetSchemeHandler(url.Scheme, throwIfMissing);
}
public ISchemeHandler GetSchemeHandler(string scheme, bool throwIfMissing)
{
ISchemeHandler handler;
if (!SchemeHandlers.TryGetValue(scheme, out handler))
{
if (!throwIfMissing)
return null;
throw new BeanIOConfigurationException(
$"Scheme '{scheme}' must one of: {string.Join(", ", SchemeHandlers.Keys.Select(x => $"'{x}'"))}");
}
return handler;
}
private static IPropertiesProvider CreateDefaultProvider()
{
var defaultProvider = new PropertiesStreamProvider(typeof(Settings).GetTypeInfo().Assembly.GetManifestResourceStream(DEFAULT_CONFIGURATION_PATH));
return defaultProvider;
}
}
}
| |
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 BreadTalk.WebAPI.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;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.