context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Lucene.Net.Util;
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Index
{
/*
* 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 Bits = Lucene.Net.Util.Bits;
//using FilterIterator = Lucene.Net.Util.FilterIterator;
/// <summary>
/// A <seealso cref="FilterAtomicReader"/> that exposes only a subset
/// of fields from the underlying wrapped reader.
/// </summary>
public sealed class FieldFilterAtomicReader : FilterAtomicReader
{
private readonly ISet<string> Fields_Renamed;
private readonly bool Negate;
private readonly FieldInfos FieldInfos_Renamed;
public FieldFilterAtomicReader(AtomicReader @in, ISet<string> fields, bool negate)
: base(@in)
{
this.Fields_Renamed = fields;
this.Negate = negate;
List<FieldInfo> filteredInfos = new List<FieldInfo>();
foreach (FieldInfo fi in @in.FieldInfos)
{
if (HasField(fi.Name))
{
filteredInfos.Add(fi);
}
}
FieldInfos_Renamed = new FieldInfos(filteredInfos.ToArray());
}
internal bool HasField(string field)
{
return Negate ^ Fields_Renamed.Contains(field);
}
public override FieldInfos FieldInfos
{
get
{
return FieldInfos_Renamed;
}
}
public override Fields GetTermVectors(int docID)
{
Fields f = base.GetTermVectors(docID);
if (f == null)
{
return null;
}
f = new FieldFilterFields(this, f);
// we need to check for emptyness, so we can return
// null:
return f.GetEnumerator().MoveNext() ? f : null;
}
public override void Document(int docID, StoredFieldVisitor visitor)
{
base.Document(docID, new StoredFieldVisitorAnonymousInnerClassHelper(this, visitor));
}
private class StoredFieldVisitorAnonymousInnerClassHelper : StoredFieldVisitor
{
private readonly FieldFilterAtomicReader OuterInstance;
private readonly StoredFieldVisitor Visitor;
public StoredFieldVisitorAnonymousInnerClassHelper(FieldFilterAtomicReader outerInstance, StoredFieldVisitor visitor)
{
this.OuterInstance = outerInstance;
this.Visitor = visitor;
}
public override void BinaryField(FieldInfo fieldInfo, byte[] value)
{
Visitor.BinaryField(fieldInfo, value);
}
public override void StringField(FieldInfo fieldInfo, string value)
{
Visitor.StringField(fieldInfo, value);
}
public override void IntField(FieldInfo fieldInfo, int value)
{
Visitor.IntField(fieldInfo, value);
}
public override void LongField(FieldInfo fieldInfo, long value)
{
Visitor.LongField(fieldInfo, value);
}
public override void FloatField(FieldInfo fieldInfo, float value)
{
Visitor.FloatField(fieldInfo, value);
}
public override void DoubleField(FieldInfo fieldInfo, double value)
{
Visitor.DoubleField(fieldInfo, value);
}
public override Status NeedsField(FieldInfo fieldInfo)
{
return OuterInstance.HasField(fieldInfo.Name) ? Visitor.NeedsField(fieldInfo) : Status.NO;
}
}
public override Fields Fields
{
get
{
Fields f = base.Fields;
return (f == null) ? null : new FieldFilterFields(this, f);
}
}
public override NumericDocValues GetNumericDocValues(string field)
{
return HasField(field) ? base.GetNumericDocValues(field) : null;
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
return HasField(field) ? base.GetBinaryDocValues(field) : null;
}
public override SortedDocValues GetSortedDocValues(string field)
{
return HasField(field) ? base.GetSortedDocValues(field) : null;
}
public override NumericDocValues GetNormValues(string field)
{
return HasField(field) ? base.GetNormValues(field) : null;
}
public override Bits GetDocsWithField(string field)
{
return HasField(field) ? base.GetDocsWithField(field) : null;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("FieldFilterAtomicReader(reader=");
sb.Append(@in).Append(", fields=");
if (Negate)
{
sb.Append('!');
}
return sb.Append(Fields_Renamed).Append(')').ToString();
}
private class FieldFilterFields : FilterFields
{
private readonly FieldFilterAtomicReader OuterInstance;
public FieldFilterFields(FieldFilterAtomicReader outerInstance, Fields @in)
: base(@in)
{
this.OuterInstance = outerInstance;
}
public override int Size
{
get
{
// this information is not cheap, return -1 like MultiFields does:
return -1;
}
}
public override IEnumerator<string> GetEnumerator()
{
return new FilterIteratorAnonymousInnerClassHelper(this, base.GetEnumerator());
}
private class FilterIteratorAnonymousInnerClassHelper : FilterIterator<string>
{
private readonly FieldFilterFields OuterInstance;
public FilterIteratorAnonymousInnerClassHelper(FieldFilterFields outerInstance, IEnumerator<string> iterator)
: base(iterator)
{
this.OuterInstance = outerInstance;
}
protected override bool PredicateFunction(string field)
{
return OuterInstance.OuterInstance.HasField(field);
}
}
public override Terms Terms(string field)
{
return OuterInstance.HasField(field) ? base.Terms(field) : null;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System.Collections.Generic;
using NPOI.Util;
using NPOI.HWPF.Model.IO;
using System;
namespace NPOI.HWPF.Model
{
/**
* @author Ryan Ackley
*/
public class SectionTable
{
private static int SED_SIZE = 12;
protected List<SEPX> _sections = new List<SEPX>();
protected List<TextPiece> _text;
/** So we can know if things are unicode or not */
private TextPieceTable tpt;
public SectionTable()
{
}
public SectionTable(byte[] documentStream, byte[] tableStream, int OffSet,
int size, int fcMin,
TextPieceTable tpt, int mainLength)
{
PlexOfCps sedPlex = new PlexOfCps(tableStream, OffSet, size, SED_SIZE);
this.tpt = tpt;
this._text = tpt.TextPieces;
int length = sedPlex.Length;
for (int x = 0; x < length; x++)
{
GenericPropertyNode node = sedPlex.GetProperty(x);
SectionDescriptor sed = new SectionDescriptor(node.Bytes, 0);
int fileOffset = sed.GetFc();
//int startAt = CPtoFC(node.Start);
//int endAt = CPtoFC(node.End);
int startAt = node.Start;
int endAt = node.End;
// check for the optimization
if (fileOffset == unchecked((int)0xffffffff))
{
_sections.Add(new SEPX(sed, startAt, endAt, new byte[0]));
}
else
{
// The first short at the offset is the size of the grpprl.
int sepxSize = LittleEndian.GetShort(documentStream, fileOffset);
byte[] buf = new byte[sepxSize];
fileOffset += LittleEndianConsts.SHORT_SIZE;
Array.Copy(documentStream, fileOffset, buf, 0, buf.Length);
_sections.Add(new SEPX(sed, startAt, endAt, buf));
}
}
// Some files seem to lie about their unicode status, which
// is very very pesky. Try to work around these, but this
// is Getting on for black magic...
int mainEndsAt = mainLength;
bool matchAt = false;
bool matchHalf = false;
for (int i = 0; i < _sections.Count; i++)
{
SEPX s = _sections[i];
if (s.End == mainEndsAt)
{
matchAt = true;
}
else if (s.End == mainEndsAt || s.End == mainEndsAt - 1)
{
matchHalf = true;
}
}
if (!matchAt && matchHalf)
{
//System.err.println("Your document seemed to be mostly unicode, but the section defInition was in bytes! Trying anyway, but things may well go wrong!");
for (int i = 0; i < _sections.Count; i++)
{
SEPX s = _sections[i];
GenericPropertyNode node = sedPlex.GetProperty(i);
int startAt = node.Start;
int endAt = node.End;
s.Start = (startAt);
s.End = (endAt);
}
}
}
public void AdjustForInsert(int listIndex, int Length)
{
int size = _sections.Count;
SEPX sepx = _sections[listIndex];
sepx.End = (sepx.End + Length);
for (int x = listIndex + 1; x < size; x++)
{
sepx = _sections[x];
sepx.Start = (sepx.Start + Length);
sepx.End = (sepx.End + Length);
}
}
// goss version of CPtoFC - this takes into account non-contiguous textpieces
// that we have come across in real world documents. Tests against the example
// code in HWPFDocument show no variation to Ryan's version of the code in
// normal use, but this version works with our non-contiguous test case.
// So far unable to get this test case to be written out as well due to
// other issues. - piers
private int CPtoFC(int CP)
{
TextPiece TP = null;
for (int i = _text.Count - 1; i > -1; i--)
{
TP = _text[i];
if (CP >= TP.GetCP()) break;
}
int FC = TP.PieceDescriptor.FilePosition;
int offset = CP - TP.GetCP();
if (TP.IsUnicode)
{
offset = offset * 2;
}
FC = FC + offset;
return FC;
}
public List<SEPX> GetSections()
{
return _sections;
}
public void WriteTo(HWPFFileSystem sys, int fcMin)
{
HWPFStream docStream = sys.GetStream("WordDocument");
HWPFStream tableStream = sys.GetStream("1Table");
int offset = docStream.Offset;
int len = _sections.Count;
PlexOfCps plex = new PlexOfCps(SED_SIZE);
for (int x = 0; x < len; x++)
{
SEPX sepx = _sections[x];
byte[] grpprl = sepx.GetGrpprl();
// write the sepx to the document stream. starts with a 2 byte size
// followed by the grpprl
byte[] shortBuf = new byte[2];
LittleEndian.PutShort(shortBuf, (short)grpprl.Length);
docStream.Write(shortBuf);
docStream.Write(grpprl);
// set the fc in the section descriptor
SectionDescriptor sed = sepx.GetSectionDescriptor();
sed.SetFc(offset);
// add the section descriptor bytes to the PlexOfCps.
// original line -
//GenericPropertyNode property = new GenericPropertyNode(sepx.Start, sepx.End, sed.ToArray());
// Line using Ryan's FCtoCP() conversion method -
// unable to observe any effect on our testcases when using this code - piers
GenericPropertyNode property = new GenericPropertyNode(tpt.GetCharIndex(sepx.StartBytes), tpt.GetCharIndex(sepx.EndBytes), sed.ToArray());
plex.AddProperty(property);
offset = docStream.Offset;
}
tableStream.Write(plex.ToByteArray());
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Parallel;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
[ParallelFixture]
public class InKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAtRoot_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalStatement_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalVariableDeclaration_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterFrom()
{
VerifyAbsence(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFromIdentifier()
{
VerifyKeyword(AddInsideMethod(
@"var q = from x $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFromAndTypeAndIdentifier()
{
VerifyKeyword(AddInsideMethod(
@"var q = from int x $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterJoin()
{
VerifyAbsence(AddInsideMethod(
@"var q = from x in y
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterJoinIdentifier()
{
VerifyKeyword(AddInsideMethod(
@"var q = from x in y
join z $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterJoinAndTypeAndIdentifier()
{
VerifyKeyword(AddInsideMethod(
@"var q = from x in y
join int z $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterJoinNotAfterIn()
{
VerifyAbsence(AddInsideMethod(
@"var q = from x in y
join z in $$"));
}
[WorkItem(544158)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterJoinPredefinedType()
{
VerifyAbsence(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from x in y
join int $$");
}
[WorkItem(544158)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterJoinType()
{
VerifyAbsence(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from x in y
join Int32 $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForEach()
{
VerifyKeyword(AddInsideMethod(
@"foreach (var v $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForEach1()
{
VerifyKeyword(AddInsideMethod(
@"foreach (var v $$ c"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForEach2()
{
VerifyKeyword(AddInsideMethod(
@"foreach (var v $$ c"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInForEach()
{
VerifyAbsence(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInForEach1()
{
VerifyAbsence(AddInsideMethod(
@"foreach (var $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInForEach2()
{
VerifyAbsence(AddInsideMethod(
@"foreach (var v in $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInForEach3()
{
VerifyAbsence(AddInsideMethod(
@"foreach (var v in c $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InterfaceTypeVarianceAfterAngle()
{
VerifyKeyword(
@"interface IFoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InterfaceTypeVarianceNotAfterIn()
{
VerifyAbsence(
@"interface IFoo<in $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InterfaceTypeVarianceAfterComma()
{
VerifyKeyword(
@"interface IFoo<Foo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InterfaceTypeVarianceAfterAttribute()
{
VerifyKeyword(
@"interface IFoo<[Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void DelegateTypeVarianceAfterAngle()
{
VerifyKeyword(
@"delegate void D<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void DelegateTypeVarianceAfterComma()
{
VerifyKeyword(
@"delegate void D<Foo, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void DelegateTypeVarianceAfterAttribute()
{
VerifyKeyword(
@"delegate void D<[Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInClassTypeVarianceAfterAngle()
{
VerifyAbsence(
@"class IFoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInStructTypeVarianceAfterAngle()
{
VerifyAbsence(
@"struct IFoo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInBaseListAfterAngle()
{
VerifyAbsence(
@"interface IFoo : Bar<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInGenericMethod()
{
VerifyAbsence(
@"interface IFoo {
void Foo<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void From2()
{
VerifyKeyword(AddInsideMethod(
@"var q2 = from int x $$ ((IEnumerable)src))"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void From3()
{
VerifyKeyword(AddInsideMethod(
@"var q2 = from x $$ ((IEnumerable)src))"));
}
[WorkItem(544158)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterFromPredefinedType()
{
VerifyAbsence(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from int $$");
}
[WorkItem(544158)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterFromType()
{
VerifyAbsence(
@"using System;
using System.Linq;
class C {
void M()
{
var q = from Int32 $$");
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using Cassandra.Data.Linq;
using Cassandra.IntegrationTests.Linq.Structures;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using Cassandra.Mapping;
using Cassandra.Mapping.Statements;
namespace Cassandra.IntegrationTests.Core
{
[Category("long")]
public class ConsistencyTests : TestGlobals
{
private ISession _session;
private string _ksName;
private Table<ManyDataTypesEntity> _table;
private string _defaultSelectStatement = "SELECT * FROM \"" + typeof(ManyDataTypesEntity).Name + "\"";
private string _preparedInsertStatementAsString =
"INSERT INTO \"" + typeof(ManyDataTypesEntity).Name + "\" (\"StringType\", \"GuidType\", \"DateTimeType\", \"DateTimeOffsetType\", \"BooleanType\", " +
"\"DecimalType\", \"DoubleType\", \"FloatType\", \"NullableIntType\", \"IntType\", \"Int64Type\", " +
"\"DictionaryStringLongType\", \"DictionaryStringStringType\", \"ListOfGuidsType\", \"ListOfStringsType\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private string _simpleStatementInsertFormat =
"INSERT INTO \"" + typeof(ManyDataTypesEntity).Name + "\" (\"StringType\", \"GuidType\", \"BooleanType\", " +
"\"DecimalType\", \"DoubleType\", \"FloatType\", \"IntType\", \"Int64Type\") VALUES ('{0}', {1}, {2}, {3}, {4}, {5}, {6}, {7})";
private List<ManyDataTypesEntity> _defaultPocoList;
private int _defaultNodeCountOne = 1;
private PreparedStatement _preparedStatement;
[TearDown]
public void TeardownTest()
{
TestUtils.TryToDeleteKeyspace(_session, _ksName);
}
private ITestCluster SetupSessionAndCluster(int nodes, Dictionary<string, string> replication = null)
{
ITestCluster testCluster = TestClusterManager.GetTestCluster(nodes);
_session = testCluster.Session;
_ksName = TestUtils.GetUniqueKeyspaceName();
_session.CreateKeyspace(_ksName, replication);
TestUtils.WaitForSchemaAgreement(_session.Cluster);
_session.ChangeKeyspace(_ksName);
_table = new Table<ManyDataTypesEntity>(_session, new MappingConfiguration());
_table.Create();
_defaultPocoList = ManyDataTypesEntity.GetDefaultAllDataTypesList();
_preparedStatement = _session.Prepare(_preparedInsertStatementAsString);
foreach (var manyDataTypesEntity in _defaultPocoList)
_session.Execute(GetBoundInsertStatementBasedOnEntity(manyDataTypesEntity));
return testCluster;
}
private BoundStatement GetBoundInsertStatementBasedOnEntity(ManyDataTypesEntity entity)
{
BoundStatement boundStatement = _preparedStatement.Bind(ConvertEntityToObjectArray(entity));
return boundStatement;
}
private string GetSimpleStatementInsertString(ManyDataTypesEntity entity)
{
string strForSimpleStatement = string.Format(_simpleStatementInsertFormat,
new object[] {
entity.StringType, entity.GuidType, entity.BooleanType, entity.DecimalType,
entity.DoubleType, entity.FloatType, entity.IntType, entity.Int64Type
});
return strForSimpleStatement;
}
//////////////////////////////////////////////////
/// Begin SimpleStatement Tests
//////////////////////////////////////////////////
[Test]
public void Consistency_SimpleStatement_LocalSerial_Insert_Success()
{
SetupSessionAndCluster(_defaultNodeCountOne);
string simpleStatementStr = GetSimpleStatementInsertString(ManyDataTypesEntity.GetRandomInstance());
SimpleStatement simpleStatement = new SimpleStatement(simpleStatementStr);
simpleStatement = (SimpleStatement)simpleStatement.SetConsistencyLevel(ConsistencyLevel.Quorum).SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
var result = _session.Execute(simpleStatement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
var selectResult = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(_defaultPocoList.Count + 1, selectResult.GetRows().ToList().Count);
}
[Test]
public void Consistency_SimpleStatement_LocalSerial_Insert_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoSimpleStatementInsertTest(ConsistencyLevel.LocalSerial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_LocalSerial_Select_Success()
{
SetupSessionAndCluster(_defaultNodeCountOne);
// Read consistency specified and write consistency specified
SimpleStatement statement = (SimpleStatement)new SimpleStatement(_defaultSelectStatement).SetConsistencyLevel(ConsistencyLevel.Quorum).SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
var result = _session.Execute(statement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
Assert.AreEqual(_defaultPocoList.Count, result.GetRows().ToList().Count);
}
[Test]
public void Consistency_SimpleStatement_LocalSerial_Select_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoSimpleStatementSelectTest(ConsistencyLevel.LocalSerial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_Serial_Insert_Success()
{
SetupSessionAndCluster(_defaultNodeCountOne);
string simpleStatementStr = GetSimpleStatementInsertString(ManyDataTypesEntity.GetRandomInstance());
SimpleStatement simpleStatement = new SimpleStatement(simpleStatementStr);
simpleStatement = (SimpleStatement)simpleStatement.SetConsistencyLevel(ConsistencyLevel.Quorum).SetSerialConsistencyLevel(ConsistencyLevel.Serial);
var result = _session.Execute(simpleStatement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
var selectResult = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(_defaultPocoList.Count + 1, selectResult.GetRows().ToList().Count);
}
[Test]
public void Consistency_SimpleStatement_Serial_Insert_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoSimpleStatementInsertTest(ConsistencyLevel.Serial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_Serial_Select_Success()
{
SetupSessionAndCluster(_defaultNodeCountOne);
SetupSessionAndCluster(_defaultNodeCountOne);
// Read consistency specified and write consistency specified
SimpleStatement statement = (SimpleStatement)new SimpleStatement(_defaultSelectStatement).SetConsistencyLevel(ConsistencyLevel.Quorum).SetSerialConsistencyLevel(ConsistencyLevel.Serial);
var result = _session.Execute(statement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
Assert.AreEqual(_defaultPocoList.Count, result.GetRows().ToList().Count);
}
[Test]
public void Consistency_SimpleStatement_Serial_Select_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoSimpleStatementSelectTest(ConsistencyLevel.Serial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_LocalOne_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementSelectTest(ConsistencyLevel.LocalOne);
}
[Test]
public void Consistency_SimpleStatement_LocalOne_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.LocalOne);
}
[Test]
public void Consistency_SimpleStatement_Quorum_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementSelectTest(ConsistencyLevel.Quorum);
}
[Test]
public void Consistency_SimpleStatement_Quorum_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.Quorum);
}
[Test]
public void Consistency_SimpleStatement_All_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementSelectTest(ConsistencyLevel.All);
}
[Test]
public void Consistency_SimpleStatement_All_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.All);
}
[Test]
public void Consistency_SimpleStatement_Any_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<InvalidQueryException>(() => DoSimpleStatementSelectTest(ConsistencyLevel.Any));
Assert.AreEqual("ANY ConsistencyLevel is only supported for writes", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_Any_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.Any);
}
[Test]
public void Consistency_SimpleStatement_EachQuorum_SelectFails()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<InvalidQueryException>(() => DoSimpleStatementSelectTest(ConsistencyLevel.EachQuorum));
Assert.AreEqual("EACH_QUORUM ConsistencyLevel is only supported for writes", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_LocalQuorum_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementSelectTest(ConsistencyLevel.LocalQuorum);
}
[Test]
public void Consistency_SimpleStatement_EachQuorum_InsertSucceeds()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.EachQuorum);
}
[Test]
public void Consistency_SimpleStatement_LocalQuorum_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.LocalQuorum);
}
[Test]
public void Consistency_SimpleStatement_One_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementSelectTest(ConsistencyLevel.One);
}
[Test]
public void Consistency_SimpleStatement_One_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoSimpleStatementInsertTest(ConsistencyLevel.One);
}
[Test]
public void Consistency_SimpleStatement_Three_Select_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoSimpleStatementInsertTest(ConsistencyLevel.Three));
Assert.AreEqual("Not enough replicas available for query at consistency Three (3 required but only 1 alive)", ex.Message);
}
[Test, Category("long")]
public void Consistency_SimpleStatement_Three_SelectAndInsert()
{
int copies = 3;
Dictionary<string, string> replication = new Dictionary<string, string> { { "class", ReplicationStrategies.SimpleStrategy }, { "replication_factor", copies.ToString() } };
var testCluster = SetupSessionAndCluster(copies, replication);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30);
DoSimpleStatementSelectTest(ConsistencyLevel.Three);
DoSimpleStatementInsertTest(ConsistencyLevel.Three);
}
[Test]
public void Consistency_SimpleStatement_Three_Insert_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoSimpleStatementInsertTest(ConsistencyLevel.Three));
Assert.AreEqual("Not enough replicas available for query at consistency Three (3 required but only 1 alive)", ex.Message);
}
[Test]
public void Consistency_SimpleStatement_Two_Select_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoSimpleStatementInsertTest(ConsistencyLevel.Two));
Assert.AreEqual("Not enough replicas available for query at consistency Two (2 required but only 1 alive)", ex.Message);
}
[Test, Category("long")]
public void Consistency_SimpleStatement_Two_SelectAndInsert()
{
int copies = 2;
Dictionary<string, string> replication = new Dictionary<string, string> { { "class", ReplicationStrategies.SimpleStrategy }, { "replication_factor", copies.ToString() } };
var testCluster = SetupSessionAndCluster(copies, replication);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
DoSimpleStatementSelectTest(ConsistencyLevel.Two);
DoSimpleStatementInsertTest(ConsistencyLevel.Two);
}
[Test]
public void Consistency_SimpleStatement_Two_Insert_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoSimpleStatementInsertTest(ConsistencyLevel.Two));
Assert.AreEqual("Not enough replicas available for query at consistency Two (2 required but only 1 alive)", ex.Message);
}
//////////////////////////////////////////////////
/// Begin PreparedStatement Tests
//////////////////////////////////////////////////
[Test]
public void Consistency_PreparedStatement_LocalSerial_Insert_Success()
{
ManyDataTypesEntity mdtp = ManyDataTypesEntity.GetRandomInstance();
object[] vals = ConvertEntityToObjectArray(mdtp);
SetupSessionAndCluster(_defaultNodeCountOne);
PreparedStatement preparedInsertStatement = _session.Prepare(_preparedInsertStatementAsString);
BoundStatement boundStatement = preparedInsertStatement.SetConsistencyLevel(ConsistencyLevel.Quorum).Bind(vals);
boundStatement.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
var result = _session.Execute(boundStatement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
var selectResult = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(_defaultPocoList.Count + 1, selectResult.GetRows().ToList().Count);
}
[Test]
public void Consistency_PreparedStatement_LocalSerial_Insert_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoPreparedInsertTest(ConsistencyLevel.LocalSerial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
/// <summary>
/// Read and write consistency must be specified separately
/// </summary>
[Test]
public void Consistency_PreparedStatement_LocalSerial_Select_Success()
{
SetupSessionAndCluster(_defaultNodeCountOne);
PreparedStatement preparedSelectStatement = _session.Prepare(_defaultSelectStatement);
BoundStatement statement = preparedSelectStatement.SetConsistencyLevel(ConsistencyLevel.Quorum).Bind();
statement.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial);
var result = _session.Execute(statement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
Assert.AreEqual(_defaultPocoList.Count, result.GetRows().ToList().Count);
}
[Test]
public void Consistency_PreparedStatement_LocalSerial_Select_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoPreparedSelectTest(ConsistencyLevel.LocalSerial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
[Test]
public void Consistency_PreparedStatement_Serial_Insert_Success()
{
ManyDataTypesEntity mdtp = ManyDataTypesEntity.GetRandomInstance();
object[] vals = ConvertEntityToObjectArray(mdtp);
SetupSessionAndCluster(_defaultNodeCountOne);
PreparedStatement preparedInsertStatement = _session.Prepare(_preparedInsertStatementAsString);
BoundStatement boundStatement = preparedInsertStatement.SetConsistencyLevel(ConsistencyLevel.Quorum).Bind(vals);
boundStatement.SetSerialConsistencyLevel(ConsistencyLevel.Serial);
var result = _session.Execute(boundStatement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
var selectResult = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(_defaultPocoList.Count + 1, selectResult.GetRows().ToList().Count);
}
[Test]
public void Consistency_PreparedStatement_Serial_Insert_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoPreparedInsertTest(ConsistencyLevel.Serial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
/// <summary>
/// Read and write consistency must be specified separately
/// </summary>
[Test]
public void Consistency_PreparedStatement_Serial_Select_Success()
{
SetupSessionAndCluster(_defaultNodeCountOne);
PreparedStatement preparedSelectStatement = _session.Prepare(_defaultSelectStatement);
BoundStatement statement = preparedSelectStatement.SetConsistencyLevel(ConsistencyLevel.Quorum).Bind();
statement.SetSerialConsistencyLevel(ConsistencyLevel.Serial);
var result = _session.Execute(statement);
Assert.AreEqual(ConsistencyLevel.Quorum, result.Info.AchievedConsistency);
Assert.AreEqual(_defaultPocoList.Count, result.GetRows().ToList().Count);
}
[Test]
public void Consistency_PreparedStatement_Serial_Select_Fail()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<RequestInvalidException>(() => DoPreparedSelectTest(ConsistencyLevel.Serial));
Assert.AreEqual("Serial consistency specified as a non-serial one.", ex.Message);
}
[Test]
public void Consistency_PreparedStatement_LocalOne_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedSelectTest(ConsistencyLevel.One);
}
[Test]
public void Consistency_PreparedStatement_LocalOne_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.One);
}
[Test]
public void Consistency_PreparedStatement_Quorum_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedSelectTest(ConsistencyLevel.Quorum);
}
[Test]
public void Consistency_PreparedStatement_Quorum_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.Quorum);
}
[Test]
public void Consistency_PreparedStatement_All_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedSelectTest(ConsistencyLevel.All);
}
[Test]
public void Consistency_PreparedStatement_All_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.All);
}
[Test]
public void Consistency_PreparedStatement_Any_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<InvalidQueryException>(() => DoPreparedSelectTest(ConsistencyLevel.Any));
Assert.AreEqual("ANY ConsistencyLevel is only supported for writes", ex.Message);
}
[Test]
public void Consistency_PreparedStatement_Any_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.Any);
}
[Test]
public void Consistency_PreparedStatement_EachQuorum_SelectFails()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<InvalidQueryException>(() => DoPreparedSelectTest(ConsistencyLevel.EachQuorum));
Assert.AreEqual("EACH_QUORUM ConsistencyLevel is only supported for writes", ex.Message);
}
[Test]
public void Consistency_PreparedStatement_LocalQuorum_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedSelectTest(ConsistencyLevel.LocalQuorum);
}
[Test]
public void Consistency_PreparedStatement_EachQuorum_InsertSucceeds()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.EachQuorum);
}
[Test]
public void Consistency_PreparedStatement_LocalQuorum_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.LocalQuorum);
}
[Test]
public void Consistency_PreparedStatement_One_Select()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedSelectTest(ConsistencyLevel.One);
}
[Test]
public void Consistency_PreparedStatement_One_Insert()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoPreparedInsertTest(ConsistencyLevel.One);
}
[Test]
public void Consistency_PreparedStatement_Three_Select_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoPreparedInsertTest(ConsistencyLevel.Three));
Assert.AreEqual("Not enough replicas available for query at consistency Three (3 required but only 1 alive)", ex.Message);
}
[Test, Category("long")]
public void Consistency_PreparedStatement_Three_SelectAndInsert()
{
int copies = 3;
Dictionary<string, string> replication = new Dictionary<string, string> { { "class", ReplicationStrategies.SimpleStrategy }, { "replication_factor", copies.ToString() } };
var testCluster = SetupSessionAndCluster(copies, replication);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30);
DoPreparedSelectTest(ConsistencyLevel.Three);
DoPreparedInsertTest(ConsistencyLevel.Three);
}
[Test]
public void Consistency_PreparedStatement_Three_Insert_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoPreparedInsertTest(ConsistencyLevel.Three));
Assert.AreEqual("Not enough replicas available for query at consistency Three (3 required but only 1 alive)", ex.Message);
}
[Test]
public void Consistency_PreparedStatement_Two_Select_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoPreparedInsertTest(ConsistencyLevel.Two));
Assert.AreEqual("Not enough replicas available for query at consistency Two (2 required but only 1 alive)", ex.Message);
}
[Test, Category("long")]
public void Consistency_PreparedStatement_Two_SelectAndInsert()
{
int copies = 2;
Dictionary<string, string> replication = new Dictionary<string, string> { { "class", ReplicationStrategies.SimpleStrategy }, { "replication_factor", copies.ToString() } };
var testCluster = SetupSessionAndCluster(copies, replication);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
DoPreparedSelectTest(ConsistencyLevel.Two);
DoPreparedInsertTest(ConsistencyLevel.Two);
}
[Test]
public void Consistency_PreparedStatement_Two_Insert_NotEnoughReplicas()
{
SetupSessionAndCluster(_defaultNodeCountOne);
var ex = Assert.Throws<UnavailableException>(() => DoPreparedInsertTest(ConsistencyLevel.Two));
Assert.AreEqual("Not enough replicas available for query at consistency Two (2 required but only 1 alive)", ex.Message);
}
//////////////////////////////////////////////////
/// Begin Batch Tests
//////////////////////////////////////////////////
[Test, TestCassandraVersion(2,0)]
public void Consistency_Batch_All()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.All);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_Any()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.Any);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_EachQuorum()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.EachQuorum);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_LocalOne()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.LocalOne);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_LocalQuorum()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.LocalQuorum);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_LocalSerial()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.LocalSerial);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_One()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.One);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_Quorum()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.Quorum);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_Serial()
{
SetupSessionAndCluster(_defaultNodeCountOne);
DoBatchInsertTest(ConsistencyLevel.Serial);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_Two()
{
int copies = 2;
Dictionary<string, string> replication = new Dictionary<string, string> { { "class", ReplicationStrategies.SimpleStrategy }, { "replication_factor", copies.ToString() } };
var testCluster = SetupSessionAndCluster(copies, replication);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
DoBatchInsertTest(ConsistencyLevel.Two);
}
[Test, TestCassandraVersion(2, 0)]
public void Consistency_Batch_Three()
{
int copies = 3;
Dictionary<string, string> replication = new Dictionary<string, string> { { "class", ReplicationStrategies.SimpleStrategy }, { "replication_factor", copies.ToString() } };
var testCluster = SetupSessionAndCluster(copies, replication);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30);
DoBatchInsertTest(ConsistencyLevel.Three);
}
///////////////////////////////////////
/// Test Helper Methods
///////////////////////////////////////
private void DoBatchInsertTest(ConsistencyLevel expectedConsistencyLevel)
{
// Add a few more records via batch statement
BatchStatement batch = new BatchStatement();
batch.SetConsistencyLevel(expectedConsistencyLevel);
var addlPocoList = ManyDataTypesEntity.GetDefaultAllDataTypesList();
foreach (var manyDataTypesPoco in addlPocoList)
{
string simpleStatementStr = GetSimpleStatementInsertString(manyDataTypesPoco);
SimpleStatement simpleStatement = new SimpleStatement(simpleStatementStr);
batch.Add(simpleStatement);
}
// Validate Results
var result = _session.Execute(batch);
Assert.AreEqual(expectedConsistencyLevel, result.Info.AchievedConsistency);
int totalExpectedRecords = _defaultPocoList.Count + addlPocoList.Count;
result = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(totalExpectedRecords, result.GetRows().ToList().Count);
}
private void DoSimpleStatementSelectTest(ConsistencyLevel expectedConsistencyLevel)
{
SimpleStatement simpleStatement = (SimpleStatement)new SimpleStatement(_defaultSelectStatement).SetConsistencyLevel(expectedConsistencyLevel);
var result = _session.Execute(simpleStatement);
Assert.AreEqual(expectedConsistencyLevel, result.Info.AchievedConsistency);
Assert.AreEqual(_defaultPocoList.Count, result.GetRows().ToList().Count);
}
private void DoSimpleStatementInsertTest(ConsistencyLevel expectedConsistencyLevel)
{
string simpleStatementStr = GetSimpleStatementInsertString(ManyDataTypesEntity.GetRandomInstance());
SimpleStatement simpleStatement = new SimpleStatement(simpleStatementStr);
simpleStatement = (SimpleStatement)simpleStatement.SetConsistencyLevel(expectedConsistencyLevel);
var result = _session.Execute(simpleStatement);
Assert.AreEqual(expectedConsistencyLevel, result.Info.AchievedConsistency);
var selectResult = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(_defaultPocoList.Count + 1, selectResult.GetRows().ToList().Count);
}
private void DoPreparedSelectTest(ConsistencyLevel expectedConsistencyLevel)
{
// NOTE: We have to re-prepare every time since there is a unique Keyspace used for every test
PreparedStatement preparedSelectStatement = _session.Prepare(_defaultSelectStatement);
var result = _session.Execute(preparedSelectStatement.SetConsistencyLevel(expectedConsistencyLevel).Bind());
Assert.AreEqual(expectedConsistencyLevel, result.Info.AchievedConsistency);
Assert.AreEqual(_defaultPocoList.Count, result.GetRows().ToList().Count);
}
private void DoPreparedInsertTest(ConsistencyLevel expectedConsistencyLevel)
{
ManyDataTypesEntity mdtp = ManyDataTypesEntity.GetRandomInstance();
object[] vals = ConvertEntityToObjectArray(mdtp);
// NOTE: We have to re-prepare every time since there is a unique Keyspace used for every test
PreparedStatement preparedInsertStatement = _session.Prepare(_preparedInsertStatementAsString).SetConsistencyLevel(expectedConsistencyLevel);
BoundStatement boundStatement = preparedInsertStatement.Bind(vals);
var result = _session.Execute(boundStatement);
Assert.AreEqual(expectedConsistencyLevel, result.Info.AchievedConsistency);
var selectResult = _session.Execute(_defaultSelectStatement);
Assert.AreEqual(_defaultPocoList.Count + 1, selectResult.GetRows().ToList().Count);
}
private static object[] ConvertEntityToObjectArray(ManyDataTypesEntity mdtp)
{
// ToString() Example output:
// INSERT INTO "ManyDataTypesPoco" ("StringType", "GuidType", "DateTimeType", "DateTimeOffsetType", "BooleanType",
// "DecimalType", "DoubleType", "FloatType", "NullableIntType", "IntType", "Int64Type",
// "TimeUuidType", "NullableTimeUuidType", "DictionaryStringLongType", "DictionaryStringStringType", "ListOfGuidsType", "ListOfStringsType") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
object[] vals =
{
mdtp.StringType, mdtp.GuidType, mdtp.DateTimeType, mdtp.DateTimeOffsetType, mdtp.BooleanType,
mdtp.DecimalType, mdtp.DoubleType, mdtp.FloatType, mdtp.NullableIntType, mdtp.IntType, mdtp.Int64Type,
// mdtp.TimeUuidType,
// mdtp.NullableTimeUuidType,
mdtp.DictionaryStringLongType, mdtp.DictionaryStringStringType, mdtp.ListOfGuidsType, mdtp.ListOfStringsType,
};
return vals;
}
}
}
| |
// http://paulmoore.mit-license.org
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace SimpleAI.Framework
{
/// <summary>
/// The main search class.
/// </summary>
/// <remarks>
/// This class implements a minimax search with alpha-beta pruning.
/// </remarks>
public sealed class Search <S, A, V, F, P> : IComparer<A> where S : State<A>, MutableClone<S>
{
private readonly A[] actions;
private readonly List<ManualResetEvent> resets;
private readonly CloneCache<S> stateCache;
private readonly CloneCache<EvaluationFunction<S, A, V, P>> evalCache;
private P maxPlayer, minPlayer;
private S state;
private uint cutoffDepth, maxDepth;
private bool isCutoff;
/// <summary>
/// Gets or sets the initial depth.
/// The depth will automatically increase with each subsequent call to search.
/// </summary>
/// <value>
/// The initial depth the search begins at.
/// </value>
public uint InitialDepth
{
get; set;
}
/// <summary>
/// Gets or sets the max explorations.
/// If the successor function produces more actions than this value, they are sorted and truncated to this value.
/// </summary>
/// <value>
/// The maximum amount of child actions to expand.
/// </value>
public uint MaxExplorations
{
get; set;
}
/// <summary>
/// Gets or sets the evaluation function.
/// This object will be cloned during the search.
/// </summary>
/// <value>
/// The evaluation function.
/// </value>
public EvaluationFunction<S, A, V, P> EvalFunc
{
get; set;
}
/// <summary>
/// Gets or sets the successor function.
/// </summary>
/// <value>
/// The successor function.
/// </value>
public SuccessorFunction<S, A, F, P> SuccessorFunc
{
get; set;
}
/// <summary>
/// Gets or sets the cutoff test.
/// </summary>
/// <value>
/// The cutoff test.
/// </value>
public CutoffTest<S, A> Cutoff
{
get; set;
}
/// <summary>
/// Gets or sets the action builder.
/// </summary>
/// <value>
/// The action builder.
/// </value>
public ActionBuilder<A, V> Builder
{
get; set;
}
/// <summary>
/// Initializes a new instance of the <see cref="SimpleAI.Framework.Search`5"/> class.
/// </summary>
/// <param name='maxActions'>
/// The maximum amount of actions to have generated at once.
/// This space will be stored up front and cannot be changed.
/// </param>
public Search (int maxActions)
{
int workers, ports;
ThreadPool.GetAvailableThreads(out workers, out ports);
resets = new List<ManualResetEvent>(workers);
stateCache = new CloneCache<S>();
evalCache = new CloneCache<EvaluationFunction<S, A, V, P>>();
actions = new A[maxActions];
InitialDepth = 1;
MaxExplorations = uint.MaxValue;
}
/// <summary>
/// Performs a search on the game tree for the best move.
/// </summary>
/// <returns>
/// The best move the search could come up with.
/// </returns>
/// <param name='state'>
/// The initial state to perform the search on.
/// </param>
/// <param name='maxPlayer'>
/// The max player (the player making the move).
/// </param>
/// <param name='minPlayer'>
/// The min player (the current player's opponent).
/// </param>
public A MinimaxDecision (S state, P maxPlayer, P minPlayer)
{
this.maxPlayer = maxPlayer;
this.minPlayer = minPlayer;
this.state = state;
stateCache.Parent = state;
evalCache.Parent = EvalFunc;
cutoffDepth = InitialDepth;
isCutoff = false;
uint bestDepth = 0;
A best = default(A);
Cutoff.Begin();
do {
maxDepth = 0;
A decision = MaxValue(default(A), Builder.NegInf, Builder.PosInf, 1, 0);
// record new bests only if the search was not cutoff
// this is to prevent false positives if the search was cutoff at a lower depth
if (maxDepth > bestDepth && !isCutoff) {
bestDepth = maxDepth;
best = decision;
}
cutoffDepth++;
} while (!isCutoff);
Cutoff.End();
// update the initial depth if we have reached a new fully explored depth
InitialDepth = Math.Max(bestDepth - 1, InitialDepth);
// reset all values so this search can be ran again
Parallel.For(0, actions.Length, i => {
actions[i] = default(A);
});
this.maxPlayer = default(P);
this.minPlayer = default(P);
this.state = default(S);
stateCache.Clear();
stateCache.Parent = null;
evalCache.Clear();
evalCache.Parent = null;
return best;
}
private A MaxValue (A parent, V alpha, V beta, uint depth, int startIndex)
{
maxDepth = Math.Max(maxDepth, depth);
if (Cutoff.Test(state)) {
// search was cutoff, start ending the search
isCutoff = true;
return EndEarly(parent);
}
if (depth >= cutoffDepth) {
// IDS cutoff
return EndEarly(parent);
}
int endIndex = GenerateActions(maxPlayer, startIndex);
if (endIndex < 0) {
// out of memory
isCutoff = true;
return EndEarly(parent);
}
int i = startIndex;
V v = Builder.NegInf;
A best = default(A);
while (i <= endIndex && !isCutoff) {
A action = actions[i];
// all cached states need to be updated with the current action
UpdateAllStates(action);
A minAction = MinValue(action, alpha, beta, depth + 1, endIndex + 1);
V minValue = Builder.ExtractValue(minAction);
// important to undo this action so a new one may be applied next iteration
UndoAllStates(action);
// pruning step
if (Builder.Compare(v, minValue) < 0) {
v = minValue;
best = action;
}
if (Builder.Compare(v, beta) >= 0) {
break;
}
if (Builder.Compare(v, alpha) > 0) {
alpha = v;
}
i++;
}
return Builder.InsertValue(best, v);
}
private A MinValue (A parent, V alpha, V beta, uint depth, int startIndex)
{
maxDepth = Math.Max(maxDepth, depth);
if (Cutoff.Test(state)) {
// search was cutoff, start ending the search
isCutoff = true;
return EndEarly(parent);
}
if (depth >= cutoffDepth) {
// IDS cutoff
return EndEarly(parent);
}
int endIndex = GenerateActions(minPlayer, startIndex);
if (endIndex < 0) {
// out of memory
isCutoff = true;
return EndEarly(parent);
}
int i = startIndex;
V v = Builder.PosInf;
A best = default(A);
while (i <= endIndex && !isCutoff) {
A action = actions[i];
// all cached states need to be updated with the current action
UpdateAllStates(action);
A maxAction = MaxValue(action, alpha, beta, depth + 1, endIndex + 1);
V maxValue = Builder.ExtractValue(maxAction);
// important to undo this action so a new one may be applied next iteration
UndoAllStates(action);
// pruning step
if (Builder.Compare(v, maxValue) > 0) {
v = maxValue;
best = action;
}
if (Builder.Compare(v, alpha) <= 0) {
break;
}
if (Builder.Compare(v, beta) < 0) {
beta = v;
}
i++;
}
return Builder.InsertValue(best, v);
}
private int GenerateActions (P player, int startIndex)
{
if (startIndex >= actions.Length) {
// out of memory
return -1;
}
int endIndex = startIndex - 1;
// expand the state into partitions
SuccessorFunc.Partition(state, player, partition => {
// each partition gets a thread local state and eval function
var localState = stateCache.Get();
var localEvalFunc = evalCache.Get();
ManualResetEvent reset = new ManualResetEvent(false);
resets.Add(reset);
// queue each partition to be computed in parallel
ThreadPool.QueueUserWorkItem(info => {
// expand this partition into individual successor actions
SuccessorFunc.Expand(localState, player, partition, action => {
int i = Interlocked.Increment(ref endIndex);
if (i < actions.Length) {
// apply, evaluate, and store the successor action
localState.ApplyAction(action);
V eval = localEvalFunc.Evaluate(localState, player);
Builder.InsertValue(action, eval);
localState.UndoAction(action);
actions[i] = action;
return true;
}
// out of memory
return false;
});
stateCache.Put(localState);
evalCache.Put(localEvalFunc);
reset.Set();
});
});
// wait for all partitions to complete
WaitHandle.WaitAll(resets.ToArray());
resets.Clear();
endIndex = Math.Min(actions.Length - 1, endIndex);
int count = endIndex - startIndex + 1;
if (count > 0) {
Array.Sort(actions, startIndex, count, this);
if (count > MaxExplorations) {
// trim the lowest ranking actions if we expanded too many
endIndex = startIndex + (int)MaxExplorations - 1;
}
return endIndex;
}
return -1;
}
public int Compare (A a0, A a1)
{
V v0 = Builder.ExtractValue(a0);
V v1 = Builder.ExtractValue(a1);
return Builder.Compare(v0, v1);
}
private void UpdateAllStates (A action)
{
state.ApplyAction(action);
foreach (var cached in stateCache.BackingStore) {
cached.ApplyAction(action);
}
}
private void UndoAllStates (A action)
{
state.UndoAction(action);
foreach (var cached in stateCache.BackingStore) {
cached.UndoAction(action);
}
}
private A EndEarly (A action)
{
action = Builder.Clone(action);
action = Builder.InsertValue(action, EvalFunc.Evaluate(state, maxPlayer));
return action;
}
}
}
| |
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 NinjaCamp.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Diagnostics.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Diagnostics\Get-WinEvent command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class GetWinEvent : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public GetWinEvent()
{
this.DisplayName = "Get-WinEvent";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Diagnostics\\Get-WinEvent"; } }
// Arguments
/// <summary>
/// Provides access to the ListLog parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ListLog { get; set; }
/// <summary>
/// Provides access to the LogName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> LogName { get; set; }
/// <summary>
/// Provides access to the ListProvider parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ListProvider { get; set; }
/// <summary>
/// Provides access to the ProviderName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> ProviderName { get; set; }
/// <summary>
/// Provides access to the Path parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Path { get; set; }
/// <summary>
/// Provides access to the MaxEvents parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int64> MaxEvents { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the FilterXPath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> FilterXPath { get; set; }
/// <summary>
/// Provides access to the FilterXml parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Xml.XmlDocument> FilterXml { get; set; }
/// <summary>
/// Provides access to the FilterHashtable parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable[]> FilterHashtable { get; set; }
/// <summary>
/// Provides access to the Force parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Force { get; set; }
/// <summary>
/// Provides access to the Oldest parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Oldest { get; set; }
/// <summary>
/// Declares that this activity supports its own remoting.
/// </summary>
protected override bool SupportsCustomRemoting { get { return true; } }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(ListLog.Expression != null)
{
targetCommand.AddParameter("ListLog", ListLog.Get(context));
}
if(LogName.Expression != null)
{
targetCommand.AddParameter("LogName", LogName.Get(context));
}
if(ListProvider.Expression != null)
{
targetCommand.AddParameter("ListProvider", ListProvider.Get(context));
}
if(ProviderName.Expression != null)
{
targetCommand.AddParameter("ProviderName", ProviderName.Get(context));
}
if(Path.Expression != null)
{
targetCommand.AddParameter("Path", Path.Get(context));
}
if(MaxEvents.Expression != null)
{
targetCommand.AddParameter("MaxEvents", MaxEvents.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(FilterXPath.Expression != null)
{
targetCommand.AddParameter("FilterXPath", FilterXPath.Get(context));
}
if(FilterXml.Expression != null)
{
targetCommand.AddParameter("FilterXml", FilterXml.Get(context));
}
if(FilterHashtable.Expression != null)
{
targetCommand.AddParameter("FilterHashtable", FilterHashtable.Get(context));
}
if(Force.Expression != null)
{
targetCommand.AddParameter("Force", Force.Get(context));
}
if(Oldest.Expression != null)
{
targetCommand.AddParameter("Oldest", Oldest.Get(context));
}
if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>AdParameter</c> resource.</summary>
public sealed partial class AdParameterName : gax::IResourceName, sys::IEquatable<AdParameterName>
{
/// <summary>The possible contents of <see cref="AdParameterName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>.
/// </summary>
CustomerAdGroupCriterionParameterIndex = 1,
}
private static gax::PathTemplate s_customerAdGroupCriterionParameterIndex = new gax::PathTemplate("customers/{customer_id}/adParameters/{ad_group_id_criterion_id_parameter_index}");
/// <summary>Creates a <see cref="AdParameterName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdParameterName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdParameterName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdParameterName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdParameterName"/> with the pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="parameterIndexId">The <c>ParameterIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdParameterName"/> constructed from the provided ids.</returns>
public static AdParameterName FromCustomerAdGroupCriterionParameterIndex(string customerId, string adGroupId, string criterionId, string parameterIndexId) =>
new AdParameterName(ResourceNameType.CustomerAdGroupCriterionParameterIndex, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)), parameterIndexId: gax::GaxPreconditions.CheckNotNullOrEmpty(parameterIndexId, nameof(parameterIndexId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdParameterName"/> with pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="parameterIndexId">The <c>ParameterIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdParameterName"/> with pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string criterionId, string parameterIndexId) =>
FormatCustomerAdGroupCriterionParameterIndex(customerId, adGroupId, criterionId, parameterIndexId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdParameterName"/> with pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="parameterIndexId">The <c>ParameterIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdParameterName"/> with pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>.
/// </returns>
public static string FormatCustomerAdGroupCriterionParameterIndex(string customerId, string adGroupId, string criterionId, string parameterIndexId) =>
s_customerAdGroupCriterionParameterIndex.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(parameterIndexId, nameof(parameterIndexId)))}");
/// <summary>Parses the given resource name string into a new <see cref="AdParameterName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adParameterName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdParameterName"/> if successful.</returns>
public static AdParameterName Parse(string adParameterName) => Parse(adParameterName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdParameterName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adParameterName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdParameterName"/> if successful.</returns>
public static AdParameterName Parse(string adParameterName, bool allowUnparsed) =>
TryParse(adParameterName, allowUnparsed, out AdParameterName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdParameterName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adParameterName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdParameterName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adParameterName, out AdParameterName result) =>
TryParse(adParameterName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdParameterName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adParameterName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdParameterName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adParameterName, bool allowUnparsed, out AdParameterName result)
{
gax::GaxPreconditions.CheckNotNull(adParameterName, nameof(adParameterName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupCriterionParameterIndex.TryParseName(adParameterName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupCriterionParameterIndex(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adParameterName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdParameterName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null, string parameterIndexId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CriterionId = criterionId;
CustomerId = customerId;
ParameterIndexId = parameterIndexId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdParameterName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adParameters/{ad_group_id}~{criterion_id}~{parameter_index}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="parameterIndexId">The <c>ParameterIndex</c> ID. Must not be <c>null</c> or empty.</param>
public AdParameterName(string customerId, string adGroupId, string criterionId, string parameterIndexId) : this(ResourceNameType.CustomerAdGroupCriterionParameterIndex, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)), parameterIndexId: gax::GaxPreconditions.CheckNotNullOrEmpty(parameterIndexId, nameof(parameterIndexId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>ParameterIndex</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string ParameterIndexId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupCriterionParameterIndex: return s_customerAdGroupCriterionParameterIndex.Expand(CustomerId, $"{AdGroupId}~{CriterionId}~{ParameterIndexId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdParameterName);
/// <inheritdoc/>
public bool Equals(AdParameterName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdParameterName a, AdParameterName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdParameterName a, AdParameterName b) => !(a == b);
}
public partial class AdParameter
{
/// <summary>
/// <see cref="AdParameterName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdParameterName ResourceNameAsAdParameterName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdParameterName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupCriterionName"/>-typed view over the <see cref="AdGroupCriterion"/> resource name
/// property.
/// </summary>
internal AdGroupCriterionName AdGroupCriterionAsAdGroupCriterionName
{
get => string.IsNullOrEmpty(AdGroupCriterion) ? null : AdGroupCriterionName.Parse(AdGroupCriterion, allowUnparsed: true);
set => AdGroupCriterion = value?.ToString() ?? "";
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SimpleDataPortal.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Implements the server-side DataPortal as discussed</summary>
//-----------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Csla.Properties;
using Csla.Reflection;
namespace Csla.Server
{
/// <summary>
/// Implements the server-side DataPortal as discussed
/// in Chapter 4.
/// </summary>
public class SimpleDataPortal : IDataPortalServer
{
/// <summary>
/// Create a new business object.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public async Task<DataPortalResult> Create(
Type objectType, object criteria, DataPortalContext context, bool isSync)
{
LateBoundObject obj = null;
IDataPortalTarget target = null;
var eventArgs = new DataPortalEventArgs(context, objectType, criteria, DataPortalOperations.Create);
try
{
// create an instance of the business object.
obj = new LateBoundObject(ApplicationContext.DataPortalActivator.CreateInstance(objectType));
ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance);
target = obj.Instance as IDataPortalTarget;
if (target != null)
{
target.DataPortal_OnDataPortalInvoke(eventArgs);
target.MarkNew();
}
else
{
obj.CallMethodIfImplemented("DataPortal_OnDataPortalInvoke", eventArgs);
obj.CallMethodIfImplemented("MarkNew");
}
// tell the business object to create its data
if (criteria is EmptyCriteria)
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Create");
await obj.CallMethodTryAsync("DataPortal_Create").ConfigureAwait(false);
}
else
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Create", criteria);
await obj.CallMethodTryAsync("DataPortal_Create", criteria).ConfigureAwait(false);
}
var busy = obj.Instance as Csla.Core.ITrackStatus;
if (busy != null && busy.IsBusy)
throw new InvalidOperationException(string.Format("{0}.IsBusy == true", objectType.Name));
if (target != null)
target.DataPortal_OnDataPortalInvokeComplete(eventArgs);
else
obj.CallMethodIfImplemented(
"DataPortal_OnDataPortalInvokeComplete", eventArgs);
// return the populated business object as a result
return new DataPortalResult(obj.Instance);
}
catch (Exception ex)
{
try
{
if (target != null)
target.DataPortal_OnDataPortalException(eventArgs, ex);
else if (obj != null)
obj.CallMethodIfImplemented("DataPortal_OnDataPortalException", eventArgs, ex);
}
catch
{
// ignore exceptions from the exception handler
}
object outval = null;
if (obj != null) outval = obj.Instance;
throw DataPortal.NewDataPortalException(
"DataPortal.Create " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, outval, criteria, "DataPortal.Create", ex),
outval);
}
finally
{
object reference = null;
if (obj != null)
reference = obj.Instance;
ApplicationContext.DataPortalActivator.FinalizeInstance(reference);
}
}
/// <summary>
/// Get an existing business object.
/// </summary>
/// <param name="objectType">Type of business object to retrieve.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public async Task<DataPortalResult> Fetch(Type objectType, object criteria, DataPortalContext context, bool isSync)
{
LateBoundObject obj = null;
IDataPortalTarget target = null;
var eventArgs = new DataPortalEventArgs(context, objectType, criteria, DataPortalOperations.Fetch);
try
{
// create an instance of the business object.
obj = new LateBoundObject(ApplicationContext.DataPortalActivator.CreateInstance(objectType));
ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance);
target = obj.Instance as IDataPortalTarget;
if (target != null)
{
target.DataPortal_OnDataPortalInvoke(eventArgs);
target.MarkOld();
}
else
{
obj.CallMethodIfImplemented("DataPortal_OnDataPortalInvoke", eventArgs);
obj.CallMethodIfImplemented("MarkOld");
}
// tell the business object to fetch its data
if (criteria is EmptyCriteria)
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Fetch");
await obj.CallMethodTryAsync("DataPortal_Fetch").ConfigureAwait(false);
}
else
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Fetch", criteria);
await obj.CallMethodTryAsync("DataPortal_Fetch", criteria).ConfigureAwait(false);
}
var busy = obj.Instance as Csla.Core.ITrackStatus;
if (busy != null && busy.IsBusy)
throw new InvalidOperationException(string.Format("{0}.IsBusy == true", objectType.Name));
if (target != null)
target.DataPortal_OnDataPortalInvokeComplete(eventArgs);
else
obj.CallMethodIfImplemented(
"DataPortal_OnDataPortalInvokeComplete",
eventArgs);
// return the populated business object as a result
return new DataPortalResult(obj.Instance);
}
catch (Exception ex)
{
try
{
if (target != null)
target.DataPortal_OnDataPortalException(eventArgs, ex);
else if (obj != null)
obj.CallMethodIfImplemented("DataPortal_OnDataPortalException", eventArgs, ex);
}
catch
{
// ignore exceptions from the exception handler
}
object outval = null;
if (obj != null) outval = obj.Instance;
throw DataPortal.NewDataPortalException(
"DataPortal.Fetch " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, outval, criteria, "DataPortal.Fetch", ex),
outval);
}
finally
{
object reference = null;
if (obj != null)
reference = obj.Instance;
ApplicationContext.DataPortalActivator.FinalizeInstance(reference);
}
}
/// <summary>
/// Update a business object.
/// </summary>
/// <param name="obj">Business object to update.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")]
public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
{
DataPortalOperations operation = DataPortalOperations.Update;
Type objectType = obj.GetType();
var target = obj as IDataPortalTarget;
LateBoundObject lb = new LateBoundObject(obj);
ApplicationContext.DataPortalActivator.InitializeInstance(lb.Instance);
try
{
if (target != null)
target.DataPortal_OnDataPortalInvoke(
new DataPortalEventArgs(context, objectType, obj, operation));
else
lb.CallMethodIfImplemented(
"DataPortal_OnDataPortalInvoke",
new DataPortalEventArgs(context, objectType, obj, operation));
// tell the business object to update itself
var busObj = obj as Core.BusinessBase;
if (busObj != null)
{
if (busObj.IsDeleted)
{
if (!busObj.IsNew)
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_DeleteSelf");
// tell the object to delete itself
await lb.CallMethodTryAsync("DataPortal_DeleteSelf").ConfigureAwait(false);
}
if (target != null)
target.MarkNew();
else
lb.CallMethodIfImplemented("MarkNew");
}
else
{
if (busObj.IsNew)
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Insert");
// tell the object to insert itself
await lb.CallMethodTryAsync("DataPortal_Insert").ConfigureAwait(false);
}
else
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Update");
// tell the object to update itself
await lb.CallMethodTryAsync("DataPortal_Update").ConfigureAwait(false);
}
if (target != null)
target.MarkOld();
else
lb.CallMethodIfImplemented("MarkOld");
}
}
else if (obj is Core.ICommandObject)
{
operation = DataPortalOperations.Execute;
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Execute");
// tell the object to update itself
await lb.CallMethodTryAsync("DataPortal_Execute").ConfigureAwait(false);
}
else
{
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Update");
// this is an updatable collection or some other
// non-BusinessBase type of object
// tell the object to update itself
await lb.CallMethodTryAsync("DataPortal_Update").ConfigureAwait(false);
if (target != null)
target.MarkOld();
else
lb.CallMethodIfImplemented("MarkOld");
}
var busy = busObj as Csla.Core.ITrackStatus;
if (busy != null && busy.IsBusy)
throw new InvalidOperationException(string.Format("{0}.IsBusy == true", objectType.Name));
if (target != null)
target.DataPortal_OnDataPortalInvokeComplete(
new DataPortalEventArgs(context, objectType, obj, operation));
else
lb.CallMethodIfImplemented("DataPortal_OnDataPortalInvokeComplete",
new DataPortalEventArgs(context, objectType, obj, operation));
return new DataPortalResult(obj);
}
catch (Exception ex)
{
try
{
if (target != null)
target.DataPortal_OnDataPortalException(
new DataPortalEventArgs(context, objectType, obj, operation), ex);
else
lb.CallMethodIfImplemented("DataPortal_OnDataPortalException", new DataPortalEventArgs(context, objectType, obj, operation), ex);
}
catch
{
// ignore exceptions from the exception handler
}
throw DataPortal.NewDataPortalException(
"DataPortal.Update " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(obj.GetType(), obj, null, "DataPortal.Update", ex),
obj);
}
finally
{
object reference = null;
if (lb != null)
reference = lb.Instance;
ApplicationContext.DataPortalActivator.FinalizeInstance(reference);
}
}
/// <summary>
/// Delete a business object.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")]
public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
{
LateBoundObject obj = null;
IDataPortalTarget target = null;
var eventArgs = new DataPortalEventArgs(context, objectType, criteria, DataPortalOperations.Delete);
try
{
// create an instance of the business objet
obj = new LateBoundObject(ApplicationContext.DataPortalActivator.CreateInstance(objectType));
ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance);
target = obj.Instance as IDataPortalTarget;
if (target != null)
target.DataPortal_OnDataPortalInvoke(eventArgs);
else
obj.CallMethodIfImplemented("DataPortal_OnDataPortalInvoke", eventArgs);
Utilities.ThrowIfAsyncMethodOnSyncClient(isSync, target, "DataPortal_Delete", criteria);
// tell the business object to delete itself
await obj.CallMethodTryAsync("DataPortal_Delete", criteria).ConfigureAwait(false);
var busy = obj.Instance as Csla.Core.ITrackStatus;
if (busy != null && busy.IsBusy)
throw new InvalidOperationException(string.Format("{0}.IsBusy == true", objectType.Name));
if (target != null)
target.DataPortal_OnDataPortalInvokeComplete(eventArgs);
else
obj.CallMethodIfImplemented("DataPortal_OnDataPortalInvokeComplete", eventArgs);
return new DataPortalResult();
}
catch (Exception ex)
{
try
{
if (target != null)
target.DataPortal_OnDataPortalException(eventArgs, ex);
else if (obj != null)
obj.CallMethodIfImplemented("DataPortal_OnDataPortalException", eventArgs, ex);
}
catch
{
// ignore exceptions from the exception handler
}
throw DataPortal.NewDataPortalException(
"DataPortal.Delete " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, obj, null, "DataPortal.Delete", ex),
null);
}
finally
{
object reference = null;
if (obj != null)
reference = obj.Instance;
ApplicationContext.DataPortalActivator.FinalizeInstance(reference);
}
}
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: api@oanda.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// InlineResponse20014
/// </summary>
[DataContract]
public partial class InlineResponse20014 : IEquatable<InlineResponse20014>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InlineResponse20014" /> class.
/// </summary>
/// <param name="LongOrderCreateTransaction">LongOrderCreateTransaction.</param>
/// <param name="LongOrderFillTransaction">LongOrderFillTransaction.</param>
/// <param name="LongOrderCancelTransaction">LongOrderCancelTransaction.</param>
/// <param name="ShortOrderCreateTransaction">ShortOrderCreateTransaction.</param>
/// <param name="ShortOrderFillTransaction">ShortOrderFillTransaction.</param>
/// <param name="ShortOrderCancelTransaction">ShortOrderCancelTransaction.</param>
/// <param name="RelatedTransactionIDs">The IDs of all Transactions that were created while satisfying the request..</param>
/// <param name="LastTransactionID">The ID of the most recent Transaction created for the Account.</param>
public InlineResponse20014(MarketOrderTransaction LongOrderCreateTransaction = default(MarketOrderTransaction), OrderFillTransaction LongOrderFillTransaction = default(OrderFillTransaction), OrderCancelTransaction LongOrderCancelTransaction = default(OrderCancelTransaction), MarketOrderTransaction ShortOrderCreateTransaction = default(MarketOrderTransaction), OrderFillTransaction ShortOrderFillTransaction = default(OrderFillTransaction), OrderCancelTransaction ShortOrderCancelTransaction = default(OrderCancelTransaction), List<string> RelatedTransactionIDs = default(List<string>), string LastTransactionID = default(string))
{
this.LongOrderCreateTransaction = LongOrderCreateTransaction;
this.LongOrderFillTransaction = LongOrderFillTransaction;
this.LongOrderCancelTransaction = LongOrderCancelTransaction;
this.ShortOrderCreateTransaction = ShortOrderCreateTransaction;
this.ShortOrderFillTransaction = ShortOrderFillTransaction;
this.ShortOrderCancelTransaction = ShortOrderCancelTransaction;
this.RelatedTransactionIDs = RelatedTransactionIDs;
this.LastTransactionID = LastTransactionID;
}
/// <summary>
/// Gets or Sets LongOrderCreateTransaction
/// </summary>
[DataMember(Name="longOrderCreateTransaction", EmitDefaultValue=false)]
public MarketOrderTransaction LongOrderCreateTransaction { get; set; }
/// <summary>
/// Gets or Sets LongOrderFillTransaction
/// </summary>
[DataMember(Name="longOrderFillTransaction", EmitDefaultValue=false)]
public OrderFillTransaction LongOrderFillTransaction { get; set; }
/// <summary>
/// Gets or Sets LongOrderCancelTransaction
/// </summary>
[DataMember(Name="longOrderCancelTransaction", EmitDefaultValue=false)]
public OrderCancelTransaction LongOrderCancelTransaction { get; set; }
/// <summary>
/// Gets or Sets ShortOrderCreateTransaction
/// </summary>
[DataMember(Name="shortOrderCreateTransaction", EmitDefaultValue=false)]
public MarketOrderTransaction ShortOrderCreateTransaction { get; set; }
/// <summary>
/// Gets or Sets ShortOrderFillTransaction
/// </summary>
[DataMember(Name="shortOrderFillTransaction", EmitDefaultValue=false)]
public OrderFillTransaction ShortOrderFillTransaction { get; set; }
/// <summary>
/// Gets or Sets ShortOrderCancelTransaction
/// </summary>
[DataMember(Name="shortOrderCancelTransaction", EmitDefaultValue=false)]
public OrderCancelTransaction ShortOrderCancelTransaction { get; set; }
/// <summary>
/// The IDs of all Transactions that were created while satisfying the request.
/// </summary>
/// <value>The IDs of all Transactions that were created while satisfying the request.</value>
[DataMember(Name="relatedTransactionIDs", EmitDefaultValue=false)]
public List<string> RelatedTransactionIDs { get; set; }
/// <summary>
/// The ID of the most recent Transaction created for the Account
/// </summary>
/// <value>The ID of the most recent Transaction created for the Account</value>
[DataMember(Name="lastTransactionID", EmitDefaultValue=false)]
public string LastTransactionID { 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 InlineResponse20014 {\n");
sb.Append(" LongOrderCreateTransaction: ").Append(LongOrderCreateTransaction).Append("\n");
sb.Append(" LongOrderFillTransaction: ").Append(LongOrderFillTransaction).Append("\n");
sb.Append(" LongOrderCancelTransaction: ").Append(LongOrderCancelTransaction).Append("\n");
sb.Append(" ShortOrderCreateTransaction: ").Append(ShortOrderCreateTransaction).Append("\n");
sb.Append(" ShortOrderFillTransaction: ").Append(ShortOrderFillTransaction).Append("\n");
sb.Append(" ShortOrderCancelTransaction: ").Append(ShortOrderCancelTransaction).Append("\n");
sb.Append(" RelatedTransactionIDs: ").Append(RelatedTransactionIDs).Append("\n");
sb.Append(" LastTransactionID: ").Append(LastTransactionID).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as InlineResponse20014);
}
/// <summary>
/// Returns true if InlineResponse20014 instances are equal
/// </summary>
/// <param name="other">Instance of InlineResponse20014 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InlineResponse20014 other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.LongOrderCreateTransaction == other.LongOrderCreateTransaction ||
this.LongOrderCreateTransaction != null &&
this.LongOrderCreateTransaction.Equals(other.LongOrderCreateTransaction)
) &&
(
this.LongOrderFillTransaction == other.LongOrderFillTransaction ||
this.LongOrderFillTransaction != null &&
this.LongOrderFillTransaction.Equals(other.LongOrderFillTransaction)
) &&
(
this.LongOrderCancelTransaction == other.LongOrderCancelTransaction ||
this.LongOrderCancelTransaction != null &&
this.LongOrderCancelTransaction.Equals(other.LongOrderCancelTransaction)
) &&
(
this.ShortOrderCreateTransaction == other.ShortOrderCreateTransaction ||
this.ShortOrderCreateTransaction != null &&
this.ShortOrderCreateTransaction.Equals(other.ShortOrderCreateTransaction)
) &&
(
this.ShortOrderFillTransaction == other.ShortOrderFillTransaction ||
this.ShortOrderFillTransaction != null &&
this.ShortOrderFillTransaction.Equals(other.ShortOrderFillTransaction)
) &&
(
this.ShortOrderCancelTransaction == other.ShortOrderCancelTransaction ||
this.ShortOrderCancelTransaction != null &&
this.ShortOrderCancelTransaction.Equals(other.ShortOrderCancelTransaction)
) &&
(
this.RelatedTransactionIDs == other.RelatedTransactionIDs ||
this.RelatedTransactionIDs != null &&
this.RelatedTransactionIDs.SequenceEqual(other.RelatedTransactionIDs)
) &&
(
this.LastTransactionID == other.LastTransactionID ||
this.LastTransactionID != null &&
this.LastTransactionID.Equals(other.LastTransactionID)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.LongOrderCreateTransaction != null)
hash = hash * 59 + this.LongOrderCreateTransaction.GetHashCode();
if (this.LongOrderFillTransaction != null)
hash = hash * 59 + this.LongOrderFillTransaction.GetHashCode();
if (this.LongOrderCancelTransaction != null)
hash = hash * 59 + this.LongOrderCancelTransaction.GetHashCode();
if (this.ShortOrderCreateTransaction != null)
hash = hash * 59 + this.ShortOrderCreateTransaction.GetHashCode();
if (this.ShortOrderFillTransaction != null)
hash = hash * 59 + this.ShortOrderFillTransaction.GetHashCode();
if (this.ShortOrderCancelTransaction != null)
hash = hash * 59 + this.ShortOrderCancelTransaction.GetHashCode();
if (this.RelatedTransactionIDs != null)
hash = hash * 59 + this.RelatedTransactionIDs.GetHashCode();
if (this.LastTransactionID != null)
hash = hash * 59 + this.LastTransactionID.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
public abstract class VCButtonBase : VCCollideableObject
{
public delegate void VCButtonDelegate(VCButtonBase button);
public string vcName;
protected static Dictionary<string, VCButtonBase> _instancesByVcName;
public bool touchMustBeginOnCollider = true;
public bool releaseOnMoveOut = true;
public bool anyTouchActivatesControl;
public bool skipCollisionDetection;
public bool debugKeyEnabled;
public KeyCode debugTouchKey = KeyCode.A;
public bool debugTouchKeyTogglesPress;
protected bool _visible;
protected bool _pressed;
protected bool _forcePressed;
protected bool _lastPressedState;
protected VCTouchWrapper _touch;
public VCButtonBase.VCButtonDelegate OnHold;
public VCButtonBase.VCButtonDelegate OnPress;
public VCButtonBase.VCButtonDelegate OnRelease;
public bool Pressed
{
get
{
return this._pressed;
}
private set
{
if (this._pressed == value)
{
return;
}
this._pressed = value;
if (this._pressed)
{
if (this.OnPress != null)
{
this.OnPress(this);
}
}
else
{
if (this.OnRelease != null)
{
this.OnRelease(this);
}
this.HoldTime = 0f;
this._touch = null;
}
}
}
public bool ForcePressed
{
get
{
return this._forcePressed;
}
set
{
this._forcePressed = value;
if (this._forcePressed)
{
this.Pressed = true;
}
else
{
this.Pressed = !this.PressEnded;
}
}
}
public float HoldTime
{
get;
private set;
}
protected bool PressEnded
{
get
{
return !this.ForcePressed && (this._touch == null || !this._touch.Active || (!this.anyTouchActivatesControl && this.releaseOnMoveOut && !this.Colliding(this._touch)));
}
}
protected void AddInstance()
{
if (string.IsNullOrEmpty(this.vcName))
{
return;
}
if (VCButtonBase._instancesByVcName == null)
{
VCButtonBase._instancesByVcName = new Dictionary<string, VCButtonBase>();
}
while (VCButtonBase._instancesByVcName.ContainsKey(this.vcName))
{
this.vcName += "_copy";
LogSystem.LogWarning(new object[]
{
"Attempting to add instance with duplicate VCName!\nVCNames must be unique -- renaming this instance to " + this.vcName
});
}
VCButtonBase._instancesByVcName.Add(this.vcName, this);
}
public static VCButtonBase GetInstance(string vcName)
{
if (VCButtonBase._instancesByVcName == null || !VCButtonBase._instancesByVcName.ContainsKey(vcName))
{
return null;
}
return VCButtonBase._instancesByVcName[vcName];
}
protected abstract void ShowPressedState(bool pressed);
protected abstract bool Colliding(VCTouchWrapper tw);
public void ForceRelease()
{
this.Pressed = false;
}
protected void Start()
{
this.Init();
}
protected virtual bool Init()
{
base.useGUILayout = false;
if (VCTouchController.Instance == null)
{
LogSystem.LogWarning(new object[]
{
"Cannot find VCTouchController!\nVirtualControls requires a gameObject which has VCTouchController component attached in scene. Adding one for you..."
});
base.gameObject.AddComponent<VCTouchController>();
}
this._lastPressedState = true;
this.Pressed = false;
this.HoldTime = 0f;
this.AddInstance();
return true;
}
protected void Update()
{
if (!this.skipCollisionDetection)
{
if (this.Pressed)
{
if (this.PressEnded)
{
this.Pressed = false;
}
else
{
this.HoldTime += Time.deltaTime;
if (this.OnHold != null)
{
this.OnHold(this);
}
}
}
else
{
for (int i = 0; i < VCTouchController.Instance.touches.Count; i++)
{
VCTouchWrapper vCTouchWrapper = VCTouchController.Instance.touches[i];
if (vCTouchWrapper.Active && (!this.touchMustBeginOnCollider || vCTouchWrapper.phase == TouchPhase.Began))
{
if (this.anyTouchActivatesControl || this.Colliding(vCTouchWrapper))
{
this._touch = vCTouchWrapper;
this.Pressed = true;
}
}
}
}
}
this.UpdateVisibility();
}
protected virtual void UpdateVisibility()
{
if (this.Pressed == this._lastPressedState)
{
return;
}
this._lastPressedState = this.Pressed;
if (this.Pressed)
{
this.ShowPressedState(true);
}
else
{
this.ShowPressedState(false);
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
************************************************************************************/
using UnityEngine;
using System.Collections; // required for Coroutines
/// <summary>
/// Fades the screen from black after a new scene is loaded. Fade can also be controlled mid-scene using SetUIFade and SetFadeLevel
/// </summary>
public class OVRScreenFade : MonoBehaviour
{
[Tooltip("Fade duration")]
public float fadeTime = 2.0f;
[Tooltip("Screen color at maximum fade")]
public Color fadeColor = new Color(0.01f, 0.01f, 0.01f, 1.0f);
public bool fadeOnStart = true;
/// <summary>
/// The render queue used by the fade mesh. Reduce this if you need to render on top of it.
/// </summary>
public int renderQueue = 5000;
private float uiFadeAlpha = 0;
private MeshRenderer fadeRenderer;
private MeshFilter fadeMesh;
private Material fadeMaterial = null;
private bool isFading = false;
public float currentAlpha { get; private set; }
/// <summary>
/// Automatically starts a fade in
/// </summary>
void Start()
{
if (gameObject.name.StartsWith("OculusMRC_"))
{
Destroy(this);
return;
}
// create the fade material
fadeMaterial = new Material(Shader.Find("Oculus/Unlit Transparent Color"));
fadeMesh = gameObject.AddComponent<MeshFilter>();
fadeRenderer = gameObject.AddComponent<MeshRenderer>();
var mesh = new Mesh();
fadeMesh.mesh = mesh;
Vector3[] vertices = new Vector3[4];
float width = 2f;
float height = 2f;
float depth = 1f;
vertices[0] = new Vector3(-width, -height, depth);
vertices[1] = new Vector3(width, -height, depth);
vertices[2] = new Vector3(-width, height, depth);
vertices[3] = new Vector3(width, height, depth);
mesh.vertices = vertices;
int[] tri = new int[6];
tri[0] = 0;
tri[1] = 2;
tri[2] = 1;
tri[3] = 2;
tri[4] = 3;
tri[5] = 1;
mesh.triangles = tri;
Vector3[] normals = new Vector3[4];
normals[0] = -Vector3.forward;
normals[1] = -Vector3.forward;
normals[2] = -Vector3.forward;
normals[3] = -Vector3.forward;
mesh.normals = normals;
Vector2[] uv = new Vector2[4];
uv[0] = new Vector2(0, 0);
uv[1] = new Vector2(1, 0);
uv[2] = new Vector2(0, 1);
uv[3] = new Vector2(1, 1);
mesh.uv = uv;
SetFadeLevel(0);
if (fadeOnStart)
{
StartCoroutine(Fade(1, 0));
}
}
/// <summary>
/// Start a fade out
/// </summary>
public void FadeOut()
{
StartCoroutine(Fade(0,1));
}
/// <summary>
/// Starts a fade in when a new level is loaded
/// </summary>
void OnLevelFinishedLoading(int level)
{
StartCoroutine(Fade(1,0));
}
void OnEnable()
{
if (!fadeOnStart)
{
SetFadeLevel(0);
}
}
/// <summary>
/// Cleans up the fade material
/// </summary>
void OnDestroy()
{
if (fadeRenderer != null)
Destroy(fadeRenderer);
if (fadeMaterial != null)
Destroy(fadeMaterial);
if (fadeMesh != null)
Destroy(fadeMesh);
}
/// <summary>
/// Set the UI fade level - fade due to UI in foreground
/// </summary>
public void SetUIFade(float level)
{
uiFadeAlpha = Mathf.Clamp01(level);
SetMaterialAlpha();
}
/// <summary>
/// Override current fade level
/// </summary>
/// <param name="level"></param>
public void SetFadeLevel(float level)
{
currentAlpha = level;
SetMaterialAlpha();
}
/// <summary>
/// Fades alpha from 1.0 to 0.0
/// </summary>
IEnumerator Fade(float startAlpha, float endAlpha)
{
float elapsedTime = 0.0f;
while (elapsedTime < fadeTime)
{
elapsedTime += Time.deltaTime;
currentAlpha = Mathf.Lerp(startAlpha, endAlpha, Mathf.Clamp01(elapsedTime / fadeTime));
SetMaterialAlpha();
yield return new WaitForEndOfFrame();
}
}
/// <summary>
/// Update material alpha. UI fade and the current fade due to fade in/out animations (or explicit control)
/// both affect the fade. (The max is taken)
/// </summary>
private void SetMaterialAlpha()
{
Color color = fadeColor;
color.a = Mathf.Max(currentAlpha, uiFadeAlpha);
isFading = color.a > 0;
if (fadeMaterial != null)
{
fadeMaterial.color = color;
fadeMaterial.renderQueue = renderQueue;
fadeRenderer.material = fadeMaterial;
fadeRenderer.enabled = isFading;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightArithmeticInt1616()
{
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightArithmeticInt1616
{
private struct TestStruct
{
public Vector256<Int16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightArithmeticInt1616 testClass)
{
var result = Avx2.ShiftRightArithmetic(_fld, 16);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector256<Int16> _clsVar;
private Vector256<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static ImmUnaryOpTest__ShiftRightArithmeticInt1616()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public ImmUnaryOpTest__ShiftRightArithmeticInt1616()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ShiftRightArithmetic(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ShiftRightArithmetic(
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ShiftRightArithmetic(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ShiftRightArithmetic(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightArithmetic(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightArithmeticInt1616();
var result = Avx2.ShiftRightArithmetic(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ShiftRightArithmetic(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ShiftRightArithmetic(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(firstOp[0] >> 15) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(firstOp[i] >> 15) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightArithmetic)}<Int16>(Vector256<Int16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Xsl;
using XmlCoreTest.Common;
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
//[TestCase(Name = "Xml 4th Errata tests for XslCompiledTransform", Params = new object[] { 300 })]
public class Errata4 : XsltApiTestCaseBase2
{
private ITestOutputHelper _output;
public Errata4(ITestOutputHelper output) : base(output)
{
_output = output;
}
private Random _rand = new Random(unchecked((int)DateTime.Now.Ticks));
#region private const string xmlDocTemplate = ...
private const string xmlDocTemplate =
@"<root>
<node>{0}</node>
<{0}>{0}</{0}>
<{0}:node xmlns:{0}=""ns1"" />
<node {0}=""attr"" />
<node {0}:a=""attr"" xmlns:{0}=""ns1""/>
</root>";
#endregion private const string xmlDocTemplate = ...
#region private const string xslStylesheetTemplate = ...
private const string xslStylesheetTemplate =
@"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:output indent=""no"" method=""text""/>
<xsl:template match=""/"">
<xsl:apply-templates select=""*/node()"" />
</xsl:template>
<!-- <node>{{0}}</node> -->
<xsl:template match=""node[text() = '{0}']"">
<xsl:value-of select=""../node[text() = '{0}']"" />
</xsl:template>
<!-- <{{0}}>{{0}}</{{0}}> -->
<xsl:template match=""{0}"">
<xsl:value-of select=""../{0}"" />
</xsl:template>
<!-- <{{0}}:node xmlns:{{0}}=""ns1"" /> -->
<xsl:template match=""{0}:node"" xmlns:{0}=""ns1"">
<xsl:value-of select=""substring-before(name(), ':')"" />
</xsl:template>
<!-- <node {0}=""attr"" /> -->
<xsl:template match=""node[@{0}]"">
<xsl:value-of select=""local-name(@{0})"" />
</xsl:template>
<!-- <node {{0}}:a=""attr"" xmlns:{{0}}=""ns1""/> -->
<xsl:template match=""node[@{0}:a]"" xmlns:{0}=""ns1"">
<xsl:value-of select=""substring-before(name(@{0}:a), ':')"" />
</xsl:template>
</xsl:stylesheet>";
#endregion private const string xslStylesheetTemplate = ...
#region private const string createElementsXsltAndXpath = ...
private const string createElementsXsltAndXpath = @" <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:output method=""xml"" indent=""yes""/>
<xsl:param name=""mode""/>
<xsl:param name=""char""/>
<xsl:template match=""/*"">
<xsl:if test=""$mode='middle'"">
<xsl:element name=""{concat('mid',$char,'dle')}"">
<xsl:attribute name=""{concat('mid',$char,'dle')}"">
<xsl:value-of select=""100""/>
</xsl:attribute>
</xsl:element>
</xsl:if>
<xsl:if test=""$mode='start'"">
<xsl:element name=""{concat($char,'start')}"">
<xsl:attribute name=""{concat($char,'start')}"">
<xsl:value-of select=""100""/>
</xsl:attribute>
</xsl:element>
</xsl:if>
</xsl:template>
</xsl:stylesheet>";
#endregion private const string createElementsXsltAndXpath = ...
#region private const string createElementsXsltInline = ...
private const string createElementsXsltInline = @" <xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" xmlns:a=""foo"">
<xsl:output method=""xml"" indent=""yes""/>
<xsl:template match=""/*"">
<xsl:element name=""{0}"">
<xsl:attribute name=""{0}"">
<xsl:value-of select=""100""/>
</xsl:attribute>
</xsl:element>
</xsl:template>
</xsl:stylesheet>";
#endregion private const string createElementsXsltInline = ...
//[Variation(Priority = 1, Desc = "Crate elment/attribute :: Invalid start name char", Params = new object[] { false, CharType.NCNameStartChar })]
[InlineData(false, CharType.NameStartChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute :: Invalid name char", Params = new object[] { false, CharType.NCNameChar })]
[InlineData(false, CharType.NameChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute :: Invalid name CharType.NameStartSurrogateHighChar", Params = new object[] { false, CharType.NameStartSurrogateHighChar })]
[InlineData(false, CharType.NameStartSurrogateHighChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute :: Invalid name CharType.NameStartSurrogateLowChar", Params = new object[] { false, CharType.NameStartSurrogateLowChar })]
[InlineData(false, CharType.NameStartSurrogateLowChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute :: Invalid name CharType.NameSurrogateHighChar", Params = new object[] { false, CharType.NameSurrogateHighChar })]
[InlineData(false, CharType.NameSurrogateHighChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute :: Invalid name CharType.NameSurrogateLowChar", Params = new object[] { false, CharType.NameSurrogateLowChar })]
[InlineData(false, CharType.NameSurrogateLowChar)]
// ---
//[Variation(Priority = 0, Desc = "Crate elment/attribute :: Valid start name char", Params = new object[] { true, CharType.NCNameStartChar })]
[InlineData(true, CharType.NameStartChar)]
//[Variation(Priority = 0, Desc = "Crate elment/attribute :: Valid name char", Params = new object[] { true, CharType.NCNameChar })]
[InlineData(true, CharType.NameChar)]
// Only Valid for Fifth Edition Xml
//[Variation(Priority = 0, Desc = "Crate elment/attribute :: Valid name CharType.NameStartSurrogateHighChar", Params = new object[] { true, CharType.NameStartSurrogateHighChar })]
//[Variation(Priority = 0, Desc = "Crate elment/attribute :: Valid name CharType.NameStartSurrogateLowChar", Params = new object[] { true, CharType.NameStartSurrogateLowChar })]
//[Variation(Priority = 0, Desc = "Crate elment/attribute :: Valid name CharType.NameSurrogateHighChar", Params = new object[] { true, CharType.NameSurrogateHighChar })]
//[Variation(Priority = 0, Desc = "Crate elment/attribute :: Valid name CharType.NameSurrogateLowChar", Params = new object[] { true, CharType.NameSurrogateLowChar })]
[OuterLoop]
[Theory]
public void CreateElementsAndAttributesUsingXsltAndXPath(object param0, object param1)
{
bool isValidChar = (bool)param0;
CharType charType = (CharType)param1;
var startChars = new CharType[] { CharType.NameStartChar, CharType.NameStartSurrogateHighChar, CharType.NameStartSurrogateLowChar };
string charsToChooseFrom = isValidChar ? UnicodeCharHelper.GetValidCharacters(charType) : UnicodeCharHelper.GetInvalidCharacters(charType);
Assert.True(charsToChooseFrom.Length > 0);
foreach (bool enableDebug in new bool[] { /*true,*/ false }) // XSLT debugging not supported in Core
{
XslCompiledTransform transf = new XslCompiledTransform(enableDebug);
using (XmlReader r = XmlReader.Create(new StringReader(createElementsXsltAndXpath))) transf.Load(r);
for (int i = 0; i < charsToChooseFrom.Length; i++)
{
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddParam("mode", "", Array.Exists(startChars, x => x == charType) ? "start" : "middle");
string strToInject = GenerateStringToInject(charsToChooseFrom, i, charType);
if (strToInject[0] == ':') continue;
arguments.AddParam("char", "", strToInject);
StringBuilder sb = new StringBuilder();
try
{
using (XmlReader r = XmlReader.Create(new StringReader("<root/>"))) transf.Transform(r, arguments, new StringWriter(sb));
Assert.True(isValidChar);
// TODO: verification for valid case
}
catch (Exception)
{
if (isValidChar) throw;
else continue; //exception expected -> continue
}
}
}
return;
}
//[Variation(Priority = 1, Desc = "Crate elment/attribute (Inline) :: Invalid start name char", Params = new object[] { false, CharType.NCNameStartChar })]
[InlineData(false, CharType.NCNameStartChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute (Inline) :: Invalid name char", Params = new object[] { false, CharType.NCNameChar })]
[InlineData(false, CharType.NCNameChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute (Inline) :: Invalid name CharType.NameStartSurrogateHighChar", Params = new object[] { false, CharType.NameStartSurrogateHighChar })]
[InlineData(false, CharType.NameStartSurrogateHighChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute (Inline) :: Invalid name CharType.NameStartSurrogateLowChar", Params = new object[] { false, CharType.NameStartSurrogateLowChar })]
[InlineData(false, CharType.NameStartSurrogateLowChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute (Inline) :: Invalid name CharType.NameSurrogateHighChar", Params = new object[] { false, CharType.NameSurrogateHighChar })]
[InlineData(false, CharType.NameSurrogateHighChar)]
//[Variation(Priority = 1, Desc = "Crate elment/attribute (Inline) :: Invalid name CharType.NameSurrogateLowChar", Params = new object[] { false, CharType.NameSurrogateLowChar })]
[InlineData(false, CharType.NameSurrogateLowChar)]
// ---
//[Variation(Priority = 0, Desc = "Crate elment/attribute (Inline) :: Valid start name char", Params = new object[] { true, CharType.NCNameStartChar })]
[InlineData(true, CharType.NCNameStartChar)]
//[Variation(Priority = 0, Desc = "Crate elment/attribute (Inline) :: Valid name char", Params = new object[] { true, CharType.NCNameChar })]
[InlineData(true, CharType.NCNameChar)]
// Only Valid for Fifth Edition Xml
//[Variation(Priority = 0, Desc = "Crate elment/attribute (Inline) :: Valid name CharType.NameStartSurrogateHighChar", Params = new object[] { true, CharType.NameStartSurrogateHighChar })]
//[Variation(Priority = 0, Desc = "Crate elment/attribute (Inline) :: Valid name CharType.NameStartSurrogateLowChar", Params = new object[] { true, CharType.NameStartSurrogateLowChar })]
//[Variation(Priority = 0, Desc = "Crate elment/attribute (Inline) :: Valid name CharType.NameSurrogateHighChar", Params = new object[] { true, CharType.NameSurrogateHighChar })]
//[Variation(Priority = 0, Desc = "Crate elment/attribute (Inline) :: Valid name CharType.NameSurrogateLowChar", Params = new object[] { true, CharType.NameSurrogateLowChar })]
[OuterLoop]
[Theory]
public void CreateElementsAndAttributesUsingXsltInline(object param0, object param1)
{
int numOfRepeat = 300; // from the test case
bool isValidChar = (bool)param0;
CharType charType = (CharType)param1;
var startChars = new CharType[] { CharType.NameStartChar, CharType.NameStartSurrogateHighChar, CharType.NameStartSurrogateLowChar };
string charsToChooseFrom = isValidChar ? UnicodeCharHelper.GetValidCharacters(charType) : UnicodeCharHelper.GetInvalidCharacters(charType);
Assert.True(charsToChooseFrom.Length > 0);
foreach (bool enableDebug in new bool[] { /*true,*/ false }) // XSLT debugging not supported in Core
{
foreach (string name in FuzzNames(!isValidChar, charType, numOfRepeat))
{
XslCompiledTransform transf = new XslCompiledTransform(enableDebug);
try
{
using (XmlReader r = XmlReader.Create(new StringReader(String.Format(createElementsXsltInline, name)))) transf.Load(r);
Assert.True(isValidChar);
}
catch (Exception)
{
if (isValidChar) throw;
else continue; //exception expected -> continue
}
// if loading of the stylesheet passed, then we should be able to provide
StringBuilder sb = new StringBuilder();
using (XmlReader r = XmlReader.Create(new StringReader("<root/>"))) transf.Transform(r, null, new StringWriter(sb));
// TODO: verification for valid case
}
}
return;
}
private string GenerateStringToInject(string charsToChooseFrom, int position, CharType charType)
{
char charToInject = charsToChooseFrom[position];
switch (charType)
{
case CharType.NameStartChar:
case CharType.NameChar:
return new string(charToInject, 1);
case CharType.NameStartSurrogateHighChar:
case CharType.NameSurrogateHighChar:
return new string(new char[] { charToInject, '\udc00' });
case CharType.NameStartSurrogateLowChar:
case CharType.NameSurrogateLowChar:
return new string(new char[] { '\udb7f', charToInject });
default:
throw new CTestFailedException("TEST_ISSUE:: CharType not recognized!");
}
}
//[Variation(Priority = 1, Desc = "Invalid start name char", Params = new object[] { false, CharType.NCNameStartChar })]
[InlineData(false, CharType.NCNameStartChar)]
//[Variation(Priority = 1, Desc = "Invalid name char", Params = new object[] { false, CharType.NCNameChar })]
[InlineData(false, CharType.NCNameChar)]
//[Variation(Priority = 1, Desc = "Invalid name CharType.NameStartSurrogateHighChar", Params = new object[] { false, CharType.NameStartSurrogateHighChar })]
[InlineData(false, CharType.NameStartSurrogateHighChar)]
//[Variation(Priority = 1, Desc = "Invalid name CharType.NameStartSurrogateLowChar", Params = new object[] { false, CharType.NameStartSurrogateLowChar })]
[InlineData(false, CharType.NameStartSurrogateLowChar)]
//[Variation(Priority = 1, Desc = "Invalid name CharType.NameSurrogateHighChar", Params = new object[] { false, CharType.NameSurrogateHighChar })]
[InlineData(false, CharType.NameSurrogateHighChar)]
//[Variation(Priority = 1, Desc = "Invalid name CharType.NameSurrogateLowChar", Params = new object[] { false, CharType.NameSurrogateLowChar })]
[InlineData(false, CharType.NameSurrogateLowChar)]
// ---
//[Variation(Priority = 0, Desc = "Valid start name char", Params = new object[] { true, CharType.NCNameStartChar })]
[InlineData(true, CharType.NCNameStartChar)]
//[Variation(Priority = 0, Desc = "Valid name char", Params = new object[] { true, CharType.NCNameChar })]
[InlineData(true, CharType.NCNameChar)]
// Only Valid for Fifth Edition Xml
//[Variation(Priority = 0, Desc = "Valid name CharType.NameStartSurrogateHighChar", Params = new object[] { true, CharType.NameStartSurrogateHighChar })]
//[Variation(Priority = 0, Desc = "Valid name CharType.NameStartSurrogateLowChar", Params = new object[] { true, CharType.NameStartSurrogateLowChar })]
//[Variation(Priority = 0, Desc = "Valid name CharType.NameSurrogateHighChar", Params = new object[] { true, CharType.NameSurrogateHighChar })]
//[Variation(Priority = 0, Desc = "Valid name CharType.NameSurrogateLowChar", Params = new object[] { true, CharType.NameSurrogateLowChar })]
[Theory]
public void TestXslTransform(object param0, object param1)
{
int numOfRepeat = 300; // from the test case
bool isValidChar = (bool)param0;
CharType charType = (CharType)param1;
foreach (string name in FuzzNames(!isValidChar, charType, numOfRepeat))
{
string xsltString = string.Format(xslStylesheetTemplate, name);
XslCompiledTransform xslt = new XslCompiledTransform();
try
{
using (XmlReader xr = XmlReader.Create(new StringReader(xsltString)))
{
xslt.Load(xr, null, new XmlUrlResolver());
}
Assert.True(isValidChar);
}
catch (XsltException)
{
if (isValidChar) throw;
else continue; //exception expected -> continue
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(string.Format(xmlDocTemplate, name));
StringBuilder actualResult = new StringBuilder();
using (XmlTextWriter xw = new XmlTextWriter(new StringWriter(actualResult)))
{
xslt.Transform(xmlDoc, xw);
}
StringBuilder expectedResult = new StringBuilder();
for (int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
{
expectedResult.Append(name);
}
Assert.True(expectedResult.ToString() == actualResult.ToString());
}
return;
}
private IEnumerable<string> FuzzNames(bool useInvalidCharacters, CharType charType, int namesCount)
{
string chars =
useInvalidCharacters ?
UnicodeCharHelper.GetInvalidCharacters(charType) :
UnicodeCharHelper.GetValidCharacters(charType);
for (int i = 0; i < namesCount; i++)
{
yield return GenerateString(chars[_rand.Next(chars.Length)], charType);
}
}
private string GenerateString(char c, CharType charType)
{
switch (charType)
{
case CharType.NCNameStartChar:
return new string(new char[] { c, 'a', 'b' });
case CharType.NCNameChar:
return new string(new char[] { 'a', c, 'b' });
case CharType.NameStartSurrogateHighChar:
return new string(new char[] { c, '\udc00', 'a', 'b' });
case CharType.NameStartSurrogateLowChar:
return new string(new char[] { '\udb7f', c, 'a', 'b' });
case CharType.NameSurrogateHighChar:
return new string(new char[] { 'a', 'b', c, '\udc00' });
case CharType.NameSurrogateLowChar:
return new string(new char[] { 'a', 'b', '\udb7f', c });
default:
throw new CTestFailedException("TEST ISSUE: CharType FAILURE!");
}
}
public new int Init(object objParam)
{
return 1;
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace MongoDB
{
/// <summary>
/// </summary>
[Serializable]
public sealed class MongoRegex : IEquatable<MongoRegex>, IXmlSerializable
{
/// <summary>
/// Initializes a new instance of the <see cref = "MongoRegex" /> class.
/// </summary>
public MongoRegex()
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "MongoRegex" /> class.
/// </summary>
/// <param name = "expression">The expression.</param>
public MongoRegex(string expression)
: this(expression, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "MongoRegex" /> class.
/// </summary>
/// <param name = "expression">The expression.</param>
/// <param name = "options">The options.</param>
public MongoRegex(string expression, MongoRegexOption options)
{
Expression = expression;
Options = options;
}
/// <summary>
/// Initializes a new instance of the <see cref="MongoRegex"/> class.
/// </summary>
/// <param name="expression">The Regex expression.</param>
/// <param name="options">The Regex options.</param>
public MongoRegex(string expression, RegexOptions options)
: this(new Regex(expression, options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "MongoRegex" /> class.
/// </summary>
/// <param name = "regex">The regex.</param>
public MongoRegex(Regex regex)
{
if(regex == null)
throw new ArgumentNullException("regex");
Expression = regex.ToString();
ToggleOption("i", (regex.Options & RegexOptions.IgnoreCase) != 0);
ToggleOption("m", (regex.Options & RegexOptions.Multiline) != 0);
ToggleOption("g", (regex.Options & RegexOptions.IgnorePatternWhitespace) != 0);
}
/// <summary>
/// Initializes a new instance of the <see cref = "MongoRegex" /> class.
/// </summary>
/// <param name = "expression">The expression.</param>
/// <param name = "options">The options.</param>
public MongoRegex(string expression, string options)
{
Expression = expression;
RawOptions = options;
}
/// <summary>
/// A valid regex string including the enclosing / characters.
/// </summary>
public string Expression { get; set; }
/// <summary>
/// Gets or sets the options.
/// </summary>
/// <value>The options.</value>
public MongoRegexOption Options
{
get
{
var options = MongoRegexOption.None;
if(RawOptions != null)
{
if(RawOptions.Contains("i"))
options = options | MongoRegexOption.IgnoreCase;
if(RawOptions.Contains("m"))
options = options | MongoRegexOption.Multiline;
if(RawOptions.Contains("g"))
options = options | MongoRegexOption.IgnorePatternWhitespace;
}
return options;
}
set
{
ToggleOption("i", (value & MongoRegexOption.IgnoreCase) != 0);
ToggleOption("m", (value & MongoRegexOption.Multiline) != 0);
ToggleOption("g", (value & MongoRegexOption.IgnorePatternWhitespace) != 0);
}
}
/// <summary>
/// A string that may contain only the characters 'g', 'i', and 'm'.
/// Because the JS and TenGen representations support a limited range of options,
/// any nonconforming options will be dropped when converting to this representation
/// </summary>
public string RawOptions { get; set; }
/// <summary>
/// Builds a .Net Regex.
/// </summary>
/// <returns></returns>
public Regex BuildRegex()
{
var options = RegexOptions.None;
if(RawOptions != null)
{
if(RawOptions.Contains("i"))
options = options | RegexOptions.IgnoreCase;
if(RawOptions.Contains("m"))
options = options | RegexOptions.Multiline;
if(RawOptions.Contains("g"))
options = options | RegexOptions.IgnorePatternWhitespace;
}
return new Regex(Expression,options);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name = "other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false.
/// </returns>
public bool Equals(MongoRegex other)
{
if(ReferenceEquals(null, other))
return false;
if(ReferenceEquals(this, other))
return true;
return Equals(other.Expression, Expression) && Equals(other.RawOptions, RawOptions);
}
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref = "T:System.Xml.Serialization.XmlSchemaProviderAttribute" /> to the class.
/// </summary>
/// <returns>
/// An <see cref = "T:System.Xml.Schema.XmlSchema" /> that describes the XML representation of the object that is produced by the <see cref = "M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)" /> method and consumed by the <see cref = "M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)" /> method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name = "reader">The <see cref = "T:System.Xml.XmlReader" /> stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
if(reader.MoveToAttribute("options"))
RawOptions = reader.Value;
if(reader.IsEmptyElement)
return;
Expression = reader.ReadString();
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name = "writer">The <see cref = "T:System.Xml.XmlWriter" /> stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if(RawOptions != null)
writer.WriteAttributeString("options", RawOptions);
if(Expression == null)
return;
writer.WriteString(Expression);
}
/// <summary>
/// Toggles the option.
/// </summary>
/// <param name = "option">The option.</param>
/// <param name = "enabled">if set to <c>true</c> [enabled].</param>
private void ToggleOption(string option, bool enabled)
{
if(RawOptions == null)
RawOptions = string.Empty;
if(enabled)
{
if(RawOptions.Contains(option))
return;
RawOptions += option;
}
else
{
if(!RawOptions.Contains(option))
return;
RawOptions = RawOptions.Replace(option, string.Empty);
}
}
/// <summary>
/// Determines whether the specified <see cref = "System.Object" /> is equal to this instance.
/// </summary>
/// <param name = "obj">The <see cref = "System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref = "System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
/// <exception cref = "T:System.NullReferenceException">
/// The <paramref name = "obj" /> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj))
return false;
if(ReferenceEquals(this, obj))
return true;
return obj.GetType() == typeof(MongoRegex) && Equals((MongoRegex)obj);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name = "left">The left.</param>
/// <param name = "right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(MongoRegex left, MongoRegex right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name = "left">The left.</param>
/// <param name = "right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(MongoRegex left, MongoRegex right)
{
return !Equals(left, right);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
unchecked
{
return ((Expression != null ? Expression.GetHashCode() : 0)*397) ^ (RawOptions != null ? RawOptions.GetHashCode() : 0);
}
}
/// <summary>
/// Returns a <see cref = "System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref = "System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("{0}{1}", Expression, RawOptions);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class File_Move : FileSystemTest
{
#region Utilities
public virtual void Move(string sourceFile, string destFile)
{
File.Move(sourceFile, destFile);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Move(null, "."));
Assert.Throws<ArgumentNullException>(() => Move(".", null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Move(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Move(".", string.Empty));
}
[Fact]
public virtual void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Move(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<FileNotFoundException>(() => Move(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
[Theory MemberData(nameof(PathsWithInvalidCharacters))]
public void PathWithIllegalCharacters(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
// Under legacy normalization we kick \\?\ paths back as invalid with ArgumentException
// New style we don't prevalidate \\?\ at all
if (invalidPath.Contains(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization())
Assert.Throws<IOException>(() => Move(testFile.FullName, invalidPath));
else
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
}
[Fact]
public void BasicMove()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveNonEmptyFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
using (var stream = testFileSource.Create())
{
var writer = new StreamWriter(stream);
writer.Write("testing\nwrite\n");
writer.Flush();
}
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
Assert.Equal("testing\nwrite\n", File.ReadAllText(testFileDest));
}
[Fact]
public void MoveOntoDirectory()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFile.FullName, TestDirectory));
}
[Fact]
public void MoveOntoExistingFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(GetTestFilePath());
testFileDest.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFileSource.FullName, testFileDest.FullName));
Assert.True(File.Exists(testFileSource.FullName));
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveIntoParentDirectory()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testDir, "..", GetTestFileName()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveToSameName()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
Move(testFileSource.FullName, testFileSource.FullName);
Assert.True(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveToSameNameDifferentCasing()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, Path.GetRandomFileName().ToLowerInvariant()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testFileSource.DirectoryName, testFileSource.Name.ToUpperInvariant()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MultipleMoves()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest1 = GetTestFilePath();
string testFileDest2 = GetTestFilePath();
Move(testFileSource.FullName, testFileDest1);
Move(testFileDest1, testFileDest2);
Assert.True(File.Exists(testFileDest2));
Assert.False(File.Exists(testFileDest1));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void FileNameWithSignificantWhitespace()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
string testFileDest = Path.Combine(TestDirectory, " e n d");
File.Create(testFileSource).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // Path longer than max path limit
public void OverMaxPathWorks_Windows()
{
// Create a destination path longer than the traditional Windows limit of 256 characters,
// but under the long path limitation (32K).
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.True(File.Exists(testFileSource), "test file should exist");
Assert.All(IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()), (path) =>
{
string baseDestinationPath = Path.GetDirectoryName(path);
if (!Directory.Exists(baseDestinationPath))
{
Directory.CreateDirectory(baseDestinationPath);
}
Assert.True(Directory.Exists(baseDestinationPath), "base destination path should exist");
Move(testFileSource, path);
Assert.True(File.Exists(path), "moved test file should exist");
File.Delete(testFileSource);
Assert.False(File.Exists(testFileSource), "source test file should not exist");
Move(path, testFileSource);
Assert.True(File.Exists(testFileSource), "restored test file should exist");
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void LongPath()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.All(IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()), (path) =>
{
AssertExtensions.ThrowsAny<PathTooLongException, FileNotFoundException, DirectoryNotFoundException>(() => Move(testFileSource, path));
File.Delete(testFileSource);
AssertExtensions.ThrowsAny<PathTooLongException, FileNotFoundException, DirectoryNotFoundException>(() => Move(path, testFileSource));
});
}
#endregion
#region PlatformSpecific
[Theory MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Versions of netfx older than 4.6.2 throw an ArgumentException instead of NotSupportedException. Until all of our machines run netfx against the actual latest version, these will fail.")]
public void WindowsPathWithIllegalColons(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<NotSupportedException>(() => Move(testFile.FullName, invalidPath));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Wild characters in path throw ArgumentException
public void WindowsWildCharacterPath()
{
Assert.Throws<ArgumentException>(() => Move("*", GetTestFilePath()));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "Test*t"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*Test"));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Wild characters in path are allowed
public void UnixWildCharacterPath()
{
string testDir = GetTestFilePath();
string testFileSource = Path.Combine(testDir, "*");
string testFileShouldntMove = Path.Combine(testDir, "*t");
string testFileDest = Path.Combine(testDir, "*" + GetTestFileName());
Directory.CreateDirectory(testDir);
File.Create(testFileSource).Dispose();
File.Create(testFileShouldntMove).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
Move(testFileDest, testFileSource);
Assert.False(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace in path throws ArgumentException
public void WindowsWhitespacePath(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace in path allowed
public void UnixWhitespacePath(string whitespace)
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
Move(testFileSource.FullName, Path.Combine(TestDirectory, whitespace));
Move(Path.Combine(TestDirectory, whitespace), testFileSource.FullName);
}
#endregion
}
}
| |
namespace Palantir.Numeric.UnitTests
{
using System;
using FluentAssertions;
using Xunit;
public sealed class MoneyTests
{
private Currency zar = new Currency("ZAR", "R", 0.01);
private Currency usd = new Currency("USD", "$", 0.01);
[Fact]
public void MoneyWithDifferentCurrencies_ShouldNotBeCompatible()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, usd);
money1.IsCompatibleWith(money2).Should().BeFalse();
}
[Fact]
public void MoneyWithDifferentMinorUnits_ShouldNotBeCompatible()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, new Currency("ZAR", "R", 0.001));
money1.IsCompatibleWith(money2).Should().BeFalse();
money1 = new Money(10, zar);
money2 = new Money(20, zar, 0.001);
money1.IsCompatibleWith(money2).Should().BeFalse();
}
[Fact]
public void MoneyWithSameMinorUnitAndCurrency_ShouldBeCompatible()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, zar);
money1.IsCompatibleWith(money2).Should().BeTrue();
money1 = new Money(10, zar, 0.001);
money2 = new Money(20, zar, 0.001);
money1.IsCompatibleWith(money2).Should().BeTrue();
}
[Fact]
public void MoneyEmpty_ShouldNotBeCompatibleWithNewMoney()
{
var money1 = new Money();
money1.IsCompatibleWith(Money.Empty).Should().BeFalse();
}
[Fact]
public void AddTwoCompatibleMonies_ShouldHaveCorrectResult()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, zar);
Money result = (money1 + money2);
result.Amount.Should().Be(30);
result.Currency.MinorUnit.Should().Be(0.01M);
result.Currency.Code.Should().Be("ZAR");
}
[Fact]
public void AddMoneyToEmpty_ShouldNotChangeResult()
{
var money1 = new Money(10, zar);
Money result = (money1 + Money.Empty);
result.Amount.Should().Be(10);
result.Currency.MinorUnit.Should().Be(0.01M);
result.Currency.Code.Should().Be("ZAR");
}
[Fact]
public void AddTwoIncompatibleCurrencyMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, usd);
Action action = () => { Money result = money1 + money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void AddTwoIncompatibleMinorUnitMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, new Currency("ZAR", "R", 0.001));
Action action = () => { Money result = money1 + money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void SubtractTwoCompatibleMonies_ShouldHaveCorrectResult()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, zar);
Money result = (money1 - money2);
result.Amount.Should().Be(-10);
result.Currency.MinorUnit.Should().Be(0.01M);
result.Currency.Code.Should().Be("ZAR");
}
[Fact]
public void SubtractTwoIncompatibleCurrencyMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, usd);
Action action = () => { Money result = money1 - money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void SubtractTwoIncompatibleMinorUnitMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, new Currency("ZAR", "R", 0.001));
Action action = () => { Money result = money1 - money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void DivideTwoCompatibleMonies_ShouldHaveCorrectResult()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, zar);
var result = (money1 / money2);
result.Amount.Should().Be(0.5M);
result.Currency.MinorUnit.Should().Be(0.01M);
result.IsPure.Should().BeTrue();
result.Currency.Code.Should().Be("ZAR");
}
[Fact]
public void DivideTwoCompatibleMonies_ShouldHaveCorrectQuotient()
{
var money1 = new Money(49, zar);
var money2 = new Money(19, zar);
var result = (money1 / money2);
result.Amount.Should().Be(2.5789473684210526315789473684M);
result.IsPure.Should().BeFalse();
result.Currency.MinorUnit.Should().Be(0.01M);
result.Currency.Code.Should().Be("ZAR");
}
[Fact]
public void DivideTwoIncompatibleCurrencyMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, usd);
Action action = () => { var result = money1 / money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void DivideTwoIncompatibleMinorUnitMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, new Currency("ZAR", "R", 0.001));
Action action = () => { var result = money1 / money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void MultiplyTwoCompatibleMonies_ShouldHaveCorrectResult()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, zar);
var result = (money1 * money2);
result.Amount.Should().Be(200);
result.Currency.MinorUnit.Should().Be(0.01M);
result.IsPure.Should().BeTrue();
result.Currency.Code.Should().Be("ZAR");
}
[Fact]
public void MultiplyTwoIncompatibleCurrencyMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, usd);
Action action = () => { var result = money1 * money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
[Fact]
public void MultiplyTwoIncompatibleMinorUnitMonies_ShouldThrowException()
{
var money1 = new Money(10, zar);
var money2 = new Money(20, new Currency("ZAR", "R", 0.001));
Action action = () => { var result = money1 * money2; };
action.ShouldThrow<IncompatibleUnitException>();
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Media;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Editors;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Core.Templates;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.PropertyEditors
{
/// <summary>
/// Represents a grid property and parameter editor.
/// </summary>
[DataEditor(
Constants.PropertyEditors.Aliases.Grid,
"Grid layout",
"grid",
HideLabel = true,
ValueType = ValueTypes.Json,
Icon = "icon-layout",
Group = Constants.PropertyEditors.Groups.RichContent)]
public class GridPropertyEditor : DataEditor
{
private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor;
private readonly IIOHelper _ioHelper;
private readonly HtmlImageSourceParser _imageSourceParser;
private readonly RichTextEditorPastedImages _pastedImages;
private readonly HtmlLocalLinkParser _localLinkParser;
private readonly IImageUrlGenerator _imageUrlGenerator;
public GridPropertyEditor(
IDataValueEditorFactory dataValueEditorFactory,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
HtmlImageSourceParser imageSourceParser,
RichTextEditorPastedImages pastedImages,
HtmlLocalLinkParser localLinkParser,
IIOHelper ioHelper,
IImageUrlGenerator imageUrlGenerator)
: base(dataValueEditorFactory)
{
_backOfficeSecurityAccessor = backOfficeSecurityAccessor;
_ioHelper = ioHelper;
_imageSourceParser = imageSourceParser;
_pastedImages = pastedImages;
_localLinkParser = localLinkParser;
_imageUrlGenerator = imageUrlGenerator;
}
public override IPropertyIndexValueFactory PropertyIndexValueFactory => new GridPropertyIndexValueFactory();
/// <summary>
/// Overridden to ensure that the value is validated
/// </summary>
/// <returns></returns>
protected override IDataValueEditor CreateValueEditor() => DataValueEditorFactory.Create<GridPropertyValueEditor>(Attribute);
protected override IConfigurationEditor CreateConfigurationEditor() => new GridConfigurationEditor(_ioHelper);
internal class GridPropertyValueEditor : DataValueEditor, IDataValueReference
{
private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor;
private readonly HtmlImageSourceParser _imageSourceParser;
private readonly RichTextEditorPastedImages _pastedImages;
private readonly RichTextPropertyEditor.RichTextPropertyValueEditor _richTextPropertyValueEditor;
private readonly MediaPickerPropertyEditor.MediaPickerPropertyValueEditor _mediaPickerPropertyValueEditor;
private readonly IImageUrlGenerator _imageUrlGenerator;
public GridPropertyValueEditor(
IDataValueEditorFactory dataValueEditorFactory,
DataEditorAttribute attribute,
IBackOfficeSecurityAccessor backOfficeSecurityAccessor,
ILocalizedTextService localizedTextService,
HtmlImageSourceParser imageSourceParser,
RichTextEditorPastedImages pastedImages,
IShortStringHelper shortStringHelper,
IImageUrlGenerator imageUrlGenerator,
IJsonSerializer jsonSerializer,
IIOHelper ioHelper)
: base(localizedTextService, shortStringHelper, jsonSerializer, ioHelper, attribute)
{
_backOfficeSecurityAccessor = backOfficeSecurityAccessor;
_imageSourceParser = imageSourceParser;
_pastedImages = pastedImages;
_richTextPropertyValueEditor =
dataValueEditorFactory.Create<RichTextPropertyEditor.RichTextPropertyValueEditor>(attribute);
_mediaPickerPropertyValueEditor =
dataValueEditorFactory.Create<MediaPickerPropertyEditor.MediaPickerPropertyValueEditor>(attribute);
_imageUrlGenerator = imageUrlGenerator;
}
/// <summary>
/// Format the data for persistence
/// This to ensure if a RTE is used in a Grid cell/control that we parse it for tmp stored images
/// to persist to the media library when we go to persist this to the DB
/// </summary>
/// <param name="editorValue"></param>
/// <param name="currentValue"></param>
/// <returns></returns>
public override object FromEditor(ContentPropertyData editorValue, object currentValue)
{
if (editorValue.Value == null)
return null;
// editorValue.Value is a JSON string of the grid
var rawJson = editorValue.Value.ToString();
if (rawJson.IsNullOrWhiteSpace())
return null;
var config = editorValue.DataTypeConfiguration as GridConfiguration;
var mediaParent = config?.MediaParentId;
var mediaParentId = mediaParent == null ? Guid.Empty : mediaParent.Guid;
var grid = DeserializeGridValue(rawJson, out var rtes, out _);
var userId = _backOfficeSecurityAccessor?.BackOfficeSecurity?.CurrentUser?.Id ?? Constants.Security.SuperUserId;
// Process the rte values
foreach (var rte in rtes)
{
// Parse the HTML
var html = rte.Value?.ToString();
var parseAndSavedTempImages = _pastedImages.FindAndPersistPastedTempImages(html, mediaParentId, userId, _imageUrlGenerator);
var editorValueWithMediaUrlsRemoved = _imageSourceParser.RemoveImageSources(parseAndSavedTempImages);
rte.Value = editorValueWithMediaUrlsRemoved;
}
// Convert back to raw JSON for persisting
return JsonConvert.SerializeObject(grid, Formatting.None);
}
/// <summary>
/// Ensures that the rich text editor values are processed within the grid
/// </summary>
/// <param name="property"></param>
/// <param name="dataTypeService"></param>
/// <param name="culture"></param>
/// <param name="segment"></param>
/// <returns></returns>
public override object ToEditor(IProperty property, string culture = null, string segment = null)
{
var val = property.GetValue(culture, segment)?.ToString();
if (val.IsNullOrWhiteSpace())
return string.Empty;
var grid = DeserializeGridValue(val, out var rtes, out _);
//process the rte values
foreach (var rte in rtes.ToList())
{
var html = rte.Value?.ToString();
var propertyValueWithMediaResolved = _imageSourceParser.EnsureImageSources(html);
rte.Value = propertyValueWithMediaResolved;
}
return grid;
}
private GridValue DeserializeGridValue(string rawJson, out IEnumerable<GridValue.GridControl> richTextValues, out IEnumerable<GridValue.GridControl> mediaValues)
{
var grid = JsonConvert.DeserializeObject<GridValue>(rawJson);
// Find all controls that use the RTE editor
var controls = grid.Sections.SelectMany(x => x.Rows.SelectMany(r => r.Areas).SelectMany(a => a.Controls)).ToArray();
richTextValues = controls.Where(x => x.Editor.Alias.ToLowerInvariant() == "rte");
mediaValues = controls.Where(x => x.Editor.Alias.ToLowerInvariant() == "media");
return grid;
}
/// <summary>
/// Resolve references from <see cref="IDataValueEditor"/> values
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public IEnumerable<UmbracoEntityReference> GetReferences(object value)
{
var rawJson = value == null ? string.Empty : value is string str ? str : value.ToString();
if (rawJson.IsNullOrWhiteSpace())
yield break;
DeserializeGridValue(rawJson, out var richTextEditorValues, out var mediaValues);
foreach (var umbracoEntityReference in richTextEditorValues.SelectMany(x =>
_richTextPropertyValueEditor.GetReferences(x.Value)))
yield return umbracoEntityReference;
foreach (var umbracoEntityReference in mediaValues.Where(x => x.Value.HasValues)
.SelectMany(x => _mediaPickerPropertyValueEditor.GetReferences(x.Value["udi"])))
yield return umbracoEntityReference;
}
}
}
}
| |
namespace Nancy.Bootstrappers.Autofac
{
using System;
using System.Collections.Generic;
using global::Autofac;
using global::Autofac.Core.Lifetime;
using Configuration;
using Diagnostics;
using Bootstrapper;
public abstract class AutofacNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<ILifetimeScope>
{
protected override IDiagnostics GetDiagnostics()
{
return this.ApplicationContainer.Resolve<IDiagnostics>();
}
/// <summary>
/// Gets all registered application startup tasks
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns>
protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()
{
return this.ApplicationContainer.Resolve<IEnumerable<IApplicationStartup>>();
}
/// <summary>
/// Gets all registered request startup tasks
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns>
protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(ILifetimeScope container, Type[] requestStartupTypes)
{
container.Update(builder =>
{
foreach (var requestStartupType in requestStartupTypes)
{
builder.RegisterType(requestStartupType).As<IRequestStartup>().PreserveExistingDefaults().InstancePerDependency();
}
});
return container.Resolve<IEnumerable<IRequestStartup>>();
}
/// <summary>
/// Gets all registered application registration tasks
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns>
protected override IEnumerable<IRegistrations> GetRegistrationTasks()
{
return this.ApplicationContainer.Resolve<IEnumerable<IRegistrations>>();
}
/// <summary>
/// Get INancyEngine
/// </summary>
/// <returns>INancyEngine implementation</returns>
protected override INancyEngine GetEngineInternal()
{
return this.ApplicationContainer.Resolve<INancyEngine>();
}
/// <summary>
/// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th.
/// </summary>
/// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns>
protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()
{
return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>();
}
/// <summary>
/// Get the <see cref="INancyEnvironment" /> instance.
/// </summary>
/// <returns>An configured <see cref="INancyEnvironment" /> instance.</returns>
/// <remarks>The boostrapper must be initialised (<see cref="INancyBootstrapper.Initialise" />) prior to calling this.</remarks>
public override INancyEnvironment GetEnvironment()
{
return this.ApplicationContainer.Resolve<INancyEnvironment>();
}
/// <summary>
/// Registers an <see cref="INancyEnvironment"/> instance in the container.
/// </summary>
/// <param name="container">The container to register into.</param>
/// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param>
protected override void RegisterNancyEnvironment(ILifetimeScope container, INancyEnvironment environment)
{
container.Update(builder => builder.RegisterInstance(environment));
}
/// <summary>
/// Create a default, unconfigured, container
/// </summary>
/// <returns>Container instance</returns>
protected override ILifetimeScope GetApplicationContainer()
{
return new ContainerBuilder().Build();
}
/// <summary>
/// Bind the bootstrapper's implemented types into the container.
/// This is necessary so a user can pass in a populated container but not have
/// to take the responsibility of registering things like INancyModuleCatalog manually.
/// </summary>
/// <param name="applicationContainer">Application container to register into</param>
protected override void RegisterBootstrapperTypes(ILifetimeScope applicationContainer)
{
applicationContainer.Update(builder => builder.RegisterInstance(this).As<INancyModuleCatalog>());
}
/// <summary>
/// Bind the default implementations of internally used types into the container as singletons
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="typeRegistrations">Type registrations to register</param>
protected override void RegisterTypes(ILifetimeScope container, IEnumerable<TypeRegistration> typeRegistrations)
{
container.Update(builder =>
{
foreach (var typeRegistration in typeRegistrations)
{
switch (typeRegistration.Lifetime)
{
case Lifetime.Transient:
builder.RegisterType(typeRegistration.ImplementationType).As(typeRegistration.RegistrationType).InstancePerDependency();
break;
case Lifetime.Singleton:
builder.RegisterType(typeRegistration.ImplementationType).As(typeRegistration.RegistrationType).SingleInstance();
break;
case Lifetime.PerRequest:
throw new InvalidOperationException("Unable to directly register a per request lifetime.");
default:
throw new ArgumentOutOfRangeException();
}
}
});
}
/// <summary>
/// Bind the various collections into the container as singletons to later be resolved
/// by IEnumerable{Type} constructor dependencies.
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="collectionTypeRegistrations">Collection type registrations to register</param>
protected override void RegisterCollectionTypes(ILifetimeScope container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)
{
container.Update(builder =>
{
foreach (var collectionTypeRegistration in collectionTypeRegistrations)
{
foreach (var implementationType in collectionTypeRegistration.ImplementationTypes)
{
switch (collectionTypeRegistration.Lifetime)
{
case Lifetime.Transient:
builder.RegisterType(implementationType).As(collectionTypeRegistration.RegistrationType).PreserveExistingDefaults().InstancePerDependency();
break;
case Lifetime.Singleton:
builder.RegisterType(implementationType).As(collectionTypeRegistration.RegistrationType).PreserveExistingDefaults().SingleInstance();
break;
case Lifetime.PerRequest:
throw new InvalidOperationException("Unable to directly register a per request lifetime.");
default:
throw new ArgumentOutOfRangeException();
}
}
}
});
}
/// <summary>
/// Bind the given instances into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="instanceRegistrations">Instance registration types</param>
protected override void RegisterInstances(ILifetimeScope container, IEnumerable<InstanceRegistration> instanceRegistrations)
{
container.Update(builder =>
{
foreach (var instanceRegistration in instanceRegistrations)
{
builder.RegisterInstance(instanceRegistration.Implementation).As(instanceRegistration.RegistrationType);
}
});
}
/// <summary>
/// Creates a per request child/nested container
/// </summary>
/// <param name="context">Current context</param>
/// <returns>Request container instance</returns>
protected override ILifetimeScope CreateRequestContainer(NancyContext context)
{
return ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
}
/// <summary>
/// Bind the given module types into the container
/// </summary>
/// <param name="container">Container to register into</param>
/// <param name="moduleRegistrationTypes"><see cref="INancyModule"/> types</param>
protected override void RegisterRequestContainerModules(ILifetimeScope container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)
{
container.Update(builder =>
{
foreach (var moduleRegistrationType in moduleRegistrationTypes)
{
builder.RegisterType(moduleRegistrationType.ModuleType).As<INancyModule>();
}
});
}
/// <summary>
/// Retrieve all module instances from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <returns>Collection of <see cref="INancyModule"/> instances</returns>
protected override IEnumerable<INancyModule> GetAllModules(ILifetimeScope container)
{
return container.Resolve<IEnumerable<INancyModule>>();
}
/// <summary>
/// Retreive a specific module instance from the container
/// </summary>
/// <param name="container">Container to use</param>
/// <param name="moduleType">Type of the module</param>
/// <returns>An <see cref="INancyModule"/> instance</returns>
protected override INancyModule GetModule(ILifetimeScope container, Type moduleType)
{
return container.Update(builder => builder.RegisterType(moduleType).As<INancyModule>()).Resolve<INancyModule>();
}
}
}
| |
using System;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Abp.Application.Features;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Domain.Entities;
using Abp.Domain.Uow;
using Abp.Events.Bus;
using Abp.Events.Bus.Exceptions;
using Abp.Localization;
using Abp.Localization.Sources;
using Abp.Logging;
using Abp.ObjectMapping;
using Abp.Reflection;
using Abp.Runtime.Session;
using Abp.Runtime.Validation;
using Abp.Web.Configuration;
using Abp.Web.Models;
using Abp.Web.Mvc.Alerts;
using Abp.Web.Mvc.Configuration;
using Abp.Web.Mvc.Controllers.Results;
using Abp.Web.Mvc.Extensions;
using Abp.Web.Mvc.Helpers;
using Abp.Web.Mvc.Models;
using Castle.Core.Logging;
namespace Abp.Web.Mvc.Controllers
{
/// <summary>
/// Base class for all MVC Controllers in Abp system.
/// </summary>
public abstract class AbpController : Controller
{
/// <summary>
/// Gets current session information.
/// </summary>
public IAbpSession AbpSession { get; set; }
/// <summary>
/// Gets the event bus.
/// </summary>
public IEventBus EventBus { get; set; }
/// <summary>
/// Reference to the permission manager.
/// </summary>
public IPermissionManager PermissionManager { get; set; }
/// <summary>
/// Reference to the setting manager.
/// </summary>
public ISettingManager SettingManager { get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IPermissionChecker PermissionChecker { protected get; set; }
/// <summary>
/// Reference to the feature manager.
/// </summary>
public IFeatureManager FeatureManager { protected get; set; }
/// <summary>
/// Reference to the permission checker.
/// </summary>
public IFeatureChecker FeatureChecker { protected get; set; }
/// <summary>
/// Reference to the localization manager.
/// </summary>
public ILocalizationManager LocalizationManager { protected get; set; }
/// <summary>
/// Reference to the error info builder.
/// </summary>
public IErrorInfoBuilder ErrorInfoBuilder { protected get; set; }
/// <summary>
/// Gets/sets name of the localization source that is used in this application service.
/// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods.
/// </summary>
protected string LocalizationSourceName { get; set; }
/// <summary>
/// Gets localization source.
/// It's valid if <see cref="LocalizationSourceName"/> is set.
/// </summary>
protected ILocalizationSource LocalizationSource
{
get
{
if (LocalizationSourceName == null)
{
throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource");
}
if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName)
{
_localizationSource = LocalizationManager.GetSource(LocalizationSourceName);
}
return _localizationSource;
}
}
public IAlertManager AlertManager { get; set; }
public AlertList Alerts => AlertManager.Alerts;
private ILocalizationSource _localizationSource;
/// <summary>
/// Reference to the logger to write logs.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Reference to the object to object mapper.
/// </summary>
public IObjectMapper ObjectMapper { get; set; }
/// <summary>
/// Reference to <see cref="IUnitOfWorkManager"/>.
/// </summary>
public IUnitOfWorkManager UnitOfWorkManager
{
get
{
if (_unitOfWorkManager == null)
{
throw new AbpException("Must set UnitOfWorkManager before use it.");
}
return _unitOfWorkManager;
}
set { _unitOfWorkManager = value; }
}
private IUnitOfWorkManager _unitOfWorkManager;
/// <summary>
/// Gets current unit of work.
/// </summary>
protected IActiveUnitOfWork CurrentUnitOfWork { get { return UnitOfWorkManager.Current; } }
public IAbpMvcConfiguration AbpMvcConfiguration { get; set; }
public IAbpWebCommonModuleConfiguration AbpWebCommonModuleConfiguration { get; set; }
/// <summary>
/// MethodInfo for currently executing action.
/// </summary>
private MethodInfo _currentMethodInfo;
/// <summary>
/// WrapResultAttribute for currently executing action.
/// </summary>
private WrapResultAttribute _wrapResultAttribute;
/// <summary>
/// Constructor.
/// </summary>
protected AbpController()
{
AbpSession = NullAbpSession.Instance;
Logger = NullLogger.Instance;
LocalizationManager = NullLocalizationManager.Instance;
PermissionChecker = NullPermissionChecker.Instance;
EventBus = NullEventBus.Instance;
ObjectMapper = NullObjectMapper.Instance;
}
/// <summary>
/// Gets localized string for given key name and current language.
/// </summary>
/// <param name="name">Key name</param>
/// <returns>Localized string</returns>
protected virtual string L(string name)
{
return LocalizationSource.GetString(name);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, params object[] args)
{
return LocalizationSource.GetString(name, args);
}
/// <summary>
/// Gets localized string for given key name and specified culture information.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture)
{
return LocalizationSource.GetString(name, culture);
}
/// <summary>
/// Gets localized string for given key name and current language with formatting strings.
/// </summary>
/// <param name="name">Key name</param>
/// <param name="culture">culture information</param>
/// <param name="args">Format arguments</param>
/// <returns>Localized string</returns>
protected virtual string L(string name, CultureInfo culture, params object[] args)
{
return LocalizationSource.GetString(name, culture, args);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected Task<bool> IsGrantedAsync(string permissionName)
{
return PermissionChecker.IsGrantedAsync(permissionName);
}
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionName">Name of the permission</param>
protected bool IsGranted(string permissionName)
{
return PermissionChecker.IsGranted(permissionName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual Task<bool> IsEnabledAsync(string featureName)
{
return FeatureChecker.IsEnabledAsync(featureName);
}
/// <summary>
/// Checks if given feature is enabled for current tenant.
/// </summary>
/// <param name="featureName">Name of the feature</param>
/// <returns></returns>
protected virtual bool IsEnabled(string featureName)
{
return FeatureChecker.IsEnabled(featureName);
}
/// <summary>
/// Json the specified data, contentType, contentEncoding and behavior.
/// </summary>
/// <param name="data">Data.</param>
/// <param name="contentType">Content type.</param>
/// <param name="contentEncoding">Content encoding.</param>
/// <param name="behavior">Behavior.</param>
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
if (
Request.Url != null &&
AbpWebCommonModuleConfiguration.WrapResultFilters.HasFilterForWrapOnSuccess(Request?.Url?.AbsolutePath, out var wrapOnSuccess)
)
{
if (!wrapOnSuccess)
{
return base.Json(data, contentType, contentEncoding, behavior);
}
return AbpJson(data, contentType, contentEncoding, behavior);
}
if (_wrapResultAttribute != null && !_wrapResultAttribute.WrapOnSuccess)
{
return base.Json(data, contentType, contentEncoding, behavior);
}
return AbpJson(data, contentType, contentEncoding, behavior);
}
protected virtual AbpJsonResult AbpJson(
object data,
string contentType = null,
Encoding contentEncoding = null,
JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet,
bool wrapResult = true,
bool camelCase = true,
bool indented = false)
{
if (wrapResult)
{
if (data == null)
{
data = new AjaxResponse();
}
else if (!(data is AjaxResponseBase))
{
data = new AjaxResponse(data);
}
}
return new AbpJsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
CamelCase = camelCase,
Indented = indented
};
}
#region OnActionExecuting / OnActionExecuted
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
SetCurrentMethodInfoAndWrapResultAttribute(filterContext);
base.OnActionExecuting(filterContext);
}
private void SetCurrentMethodInfoAndWrapResultAttribute(ActionExecutingContext filterContext)
{
//Prevent overriding for child actions
if (_currentMethodInfo != null)
{
return;
}
_currentMethodInfo = filterContext.ActionDescriptor.GetMethodInfoOrNull();
_wrapResultAttribute =
ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(
_currentMethodInfo,
AbpMvcConfiguration.DefaultWrapResultAttribute
);
}
#endregion
#region Exception handling
protected override void OnException(ExceptionContext context)
{
void HandleError()
{
//We handled the exception!
context.ExceptionHandled = true;
//Return an error response to the client.
context.HttpContext.Response.Clear();
context.HttpContext.Response.StatusCode = GetStatusCodeForException(context, _wrapResultAttribute.WrapOnError);
context.Result = MethodInfoHelper.IsJsonResult(_currentMethodInfo)
? GenerateJsonExceptionResult(context)
: GenerateNonJsonExceptionResult(context);
// Certain versions of IIS will sometimes use their own error page when
// they detect a server error. Setting this property indicates that we
// want it to try to render ASP.NET MVC's error page instead.
context.HttpContext.Response.TrySkipIisCustomErrors = true;
//Trigger an event, so we can register it.
EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
//If exception handled before, do nothing.
//If this is child action, exception should be handled by main action.
if (context.ExceptionHandled || context.IsChildAction)
{
base.OnException(context);
return;
}
//Log exception
if (_wrapResultAttribute == null || _wrapResultAttribute.LogError)
{
LogHelper.LogException(Logger, context.Exception);
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (!context.HttpContext.IsCustomErrorEnabled)
{
base.OnException(context);
return;
}
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, context.Exception).GetHttpCode() != 500)
{
base.OnException(context);
return;
}
if (context.HttpContext.Request.Url != null)
{
var url = context.HttpContext.Request.Url?.AbsolutePath;
if (AbpWebCommonModuleConfiguration.WrapResultFilters.HasFilterForWrapOnError(url, out var wrapOnError))
{
if (!wrapOnError)
{
base.OnException(context);
context.HttpContext.Response.StatusCode = GetStatusCodeForException(context, false);
return;
}
HandleError();
return;
}
}
//Check WrapResultAttribute
if (_wrapResultAttribute == null || !_wrapResultAttribute.WrapOnError)
{
base.OnException(context);
context.HttpContext.Response.StatusCode = GetStatusCodeForException(context, _wrapResultAttribute.WrapOnError);
return;
}
HandleError();
}
protected virtual int GetStatusCodeForException(ExceptionContext context, bool wrapOnError)
{
if (context.Exception is AbpAuthorizationException)
{
return context.HttpContext.User.Identity.IsAuthenticated
? (int)HttpStatusCode.Forbidden
: (int)HttpStatusCode.Unauthorized;
}
if (context.Exception is AbpValidationException)
{
return (int)HttpStatusCode.BadRequest;
}
if (context.Exception is EntityNotFoundException)
{
return (int)HttpStatusCode.NotFound;
}
if (wrapOnError)
{
return (int)HttpStatusCode.InternalServerError;
}
return context.HttpContext.Response.StatusCode;
}
protected virtual ActionResult GenerateJsonExceptionResult(ExceptionContext context)
{
context.HttpContext.Items.Add("IgnoreJsonRequestBehaviorDenyGet", "true");
return new AbpJsonResult(
new AjaxResponse(
ErrorInfoBuilder.BuildForException(context.Exception),
context.Exception is AbpAuthorizationException
)
);
}
protected virtual ActionResult GenerateNonJsonExceptionResult(ExceptionContext context)
{
return new ViewResult
{
ViewName = "Error",
MasterName = string.Empty,
ViewData = new ViewDataDictionary<ErrorViewModel>(new ErrorViewModel(ErrorInfoBuilder.BuildForException(context.Exception), context.Exception)),
TempData = context.Controller.TempData
};
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: XContainer.cs
//
// 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.Collections;
using System.Collections.Generic;
using Dot42;
namespace System.Xml.Linq
{
public abstract class XContainer : XNode
{
internal object content;
/// <summary>
/// Default ctor
/// </summary>
internal XContainer()
{
}
/// <summary>
/// Clone ctor
/// </summary>
internal XContainer(XContainer source)
{
content = source.content as string;
if ((content == null) && (source.content is XNode))
{
foreach (var node in source.Nodes())
{
Add(node.Clone(), false);
}
}
}
/// <summary>
/// Gets the first node of this container.
/// </summary>
public XNode FirstNode
{
get
{
var last = LastNode;
return (last != null) ? last.next : null;
}
}
/// <summary>
/// Gets the last node of this container.
/// </summary>
public XNode LastNode
{
get
{
if (content == null)
return null;
var node = content as XNode;
if (node != null)
return node;
var text = content as string;
if (text != null)
{
if (text.Length == 0)
return null;
var textNode = new XText(text) { parent = this };
textNode.next = textNode;
content = textNode;
}
return (XNode) content;
}
}
/// <summary>
/// Add given content as children of this container.
/// </summary>
public void Add(object value)
{
Add(value, true);
}
/// <summary>
/// Add given content as children of this container.
/// </summary>
public void Add(params object[] value)
{
if (value == null)
return;
for (var i = 0; i < value.Length; i++)
{
Add(value[i], true);
}
}
/// <summary>
/// Remove all child nodes from this container.
/// </summary>
public void RemoveNodes()
{
RemoveNodes(true);
}
/// <summary>
/// Remove all child nodes from this container.
/// </summary>
internal void RemoveNodes(bool notify)
{
if (content is string)
{
notify = notify && (this is XElement);
var hasHandlers = notify && NotifyChanging(this, XObjectChangeEventArgs.Value);
content = null;
if (hasHandlers)
NotifyChanged(this, XObjectChangeEventArgs.Value);
return;
}
while (content != null)
{
var node = content as XNode;
if (node != null)
{
Remove(node.next, notify);
}
}
}
/// <summary>
/// Remove the given node from it's parent
/// </summary>
internal void Remove(XNode node, bool notify)
{
if (node.parent != this)
{
throw new InvalidOperationException("Invalid parent");
}
var hasHandlers = NotifyChanging(this, XObjectChangeEventArgs.Remove);
var iterator = content as XNode;
if ((iterator == node) && (node.next == node))
{
// Last remaining node
content = null;
}
else
{
XNode next;
while ((next = iterator.next) != node)
{
iterator = next;
}
if (content == node)
{
content = iterator;
}
iterator.next = node.next;
}
node.parent = null;
node.next = null;
if (hasHandlers)
{
NotifyChanged(this, XObjectChangeEventArgs.Remove);
}
}
/// <summary>
/// Return a collection of child nodes in document order.
/// </summary>
public IEnumerable<XNode> Nodes()
{
var x = LastNode;
if (x != null)
{
do
{
x = x.next;
yield return x;
} while ((x.parent == this) && (content != x));
}
}
/// <summary>
/// Return a collection of child elements in document order.
/// </summary>
public IEnumerable<XElement> Elements()
{
foreach (var node in Nodes())
{
var element = node as XElement;
if (element != null)
yield return element;
}
}
/// <summary>
/// Return a collection of child elements with given name in document order.
/// </summary>
public IEnumerable<XElement> Elements(XName name)
{
if (ReferenceEquals(name, null))
yield break;
foreach (var node in Nodes())
{
var element = node as XElement;
if ((element != null) && (element.name == name))
yield return element;
}
}
/// <summary>
/// Get the first child elements with given name in document order.
/// </summary>
public XElement Element(XName name)
{
foreach (var node in Nodes())
{
var element = node as XElement;
if ((element != null) && (element.name == name))
return element;
}
return null;
}
/// <summary>
/// Add given content as children of this container.
/// </summary>
internal void Add(object value, bool notify)
{
if (value == null)
return;
var node = value as XNode;
if (node != null)
{
Add(node, notify);
return;
}
var text = value as string;
if (text != null)
{
Add(text, notify);
return;
}
var attr = value as XAttribute;
if (attr != null)
{
Add(attr, notify);
return;
}
var array = value as object[];
if (array != null)
{
for (var i = 0; i < array.Length; i++)
{
Add(array[i], notify);
}
return;
}
var enumerable = value as IEnumerable;
if (enumerable != null)
{
foreach (var x in enumerable)
{
Add(x, notify);
}
return;
}
Add(ConvertToString(value), notify);
}
/// <summary>
/// Add the given node
/// </summary>
internal void Add(XNode node, bool notify)
{
if ((node.parent != null) || (Root == node))
{
node = node.Clone();
}
ConvertText2Node();
Append(node, notify);
}
/// <summary>
/// Add the given node to the end of the list
/// </summary>
internal void Append(XNode node, bool notify)
{
if (node.parent != null)
{
throw new InvalidOperationException("Invalid parent");
}
var hasHandlers = notify && NotifyChanging(node, XObjectChangeEventArgs.Add);
// Add now
node.parent = this;
if ((content == null) || (content is string))
{
node.next = node;
}
else
{
var last = (XNode) content;
node.next = last.next;
last.next = node;
}
content = node;
// Notify if needed
if (hasHandlers) NotifyChanged(node, XObjectChangeEventArgs.Add);
}
/// <summary>
/// Convert any string content to XText.
/// </summary>
internal void ConvertText2Node()
{
var text = content as string;
if ((text != null) && (text.Length > 0))
{
var node = new XText(text);
node.next = node;
node.parent = this;
content = node;
}
}
/// <summary>
/// Add the given attribute
/// </summary>
internal virtual void Add(XAttribute attribute, bool notify)
{
// Override me
}
/// <summary>
/// Add the given text
/// </summary>
[Todo]
internal void Add(string text, bool notify)
{
if (text.Length > 0)
{
Add(new XText(text), notify);
}
}
/// <summary>
/// Returns a collection of the descendant elements for this document or element, in document order.
/// </summary>
/// <remarks>
/// Note that this method will not return itself in the result.
/// </remarks>
public IEnumerable<XElement> Descendants()
{
var childElements = Elements().GetEnumerator();
var hasNext = childElements.MoveNext();
var stack = new Stack<IEnumerator<XElement>>();
while (true)
{
if (hasNext)
{
yield return childElements.Current;
stack.Push(childElements);
childElements = childElements.Current.Elements().GetEnumerator();
hasNext = childElements.MoveNext();
}
else
{
if (stack.Count > 0)
{
childElements = stack.Pop();
}
else
{
break;
}
}
}
}
/// <summary>
/// Returns a collection of the descendant elements for this document or element, in document order.
/// </summary>
/// <remarks>
/// Note that this method will not return itself in the result.
/// </remarks>
public IEnumerable<XElement> Descendants(XName name)
{
var childElements = Elements(name).GetEnumerator();
var hasNext = childElements.MoveNext();
var stack = new Stack<IEnumerator<XElement>>();
while (true)
{
if (hasNext)
{
yield return childElements.Current;
stack.Push(childElements);
childElements = childElements.Current.Elements(name).GetEnumerator();
hasNext = childElements.MoveNext();
}
else
{
if (stack.Count > 0)
{
childElements = stack.Pop();
}
else
{
break;
}
}
}
}
/// <summary>
/// Returns a collection of the descendant nodes for this document or element, in document order.
/// </summary>
public IEnumerable<XNode> DescendantNodes()
{
foreach (XNode node in Nodes())
{
yield return node;
var container = node as XContainer;
if (container != null)
foreach (var d in container.DescendantNodes())
yield return d;
}
}
/// <summary>
/// Append string content to the given buffer.
/// </summary>
internal override void AppendTextTo(Java.Lang.StringBuffer buffer)
{
var text = content as string;
if (text != null)
{
buffer.Append(text);
}
else if (content is XNode)
{
foreach (var node in Nodes())
{
node.AppendTextTo(buffer);
}
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ToolKit.Validation;
namespace ToolKit.Cryptography
{
/// <summary>
/// Represents encryption/decryption methods that utilize a RSA keys to encrypt/decrypt a
/// password used to symmetrically encrypt the payload.
/// </summary>
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Encryption tend to have names not in standard dictionaries...")]
public class ASymmetricEncryption
{
private readonly RsaPrivateKey _privateKey;
private readonly RsaPublicKey _publicKey;
private EncryptionData _password;
/// <summary>
/// Initializes a new instance of the <see cref="ASymmetricEncryption"/> class.
/// </summary>
/// <param name="key">
/// The private key that will be used to decrypt the password used to decrypt the password.
/// </param>
/// <exception cref="ArgumentNullException">An RSA public key must be provided.</exception>
public ASymmetricEncryption(RsaPublicKey key)
{
_publicKey = key ?? throw
new ArgumentNullException(
nameof(key),
"An RSA public key must be provided!");
var random = CryptoRandomNumber.Next();
var generator = new PasswordGenerator(random)
{
IncludeExtended = false
};
_password = new EncryptionData(generator.Generate(32));
EncryptedPassword = new RsaEncryption().Encrypt(_password, _publicKey);
}
/// <summary>
/// Initializes a new instance of the <see cref="ASymmetricEncryption"/> class.
/// </summary>
/// <param name="key">
/// The private key that will be used to decrypt the password used to decrypt the password.
/// </param>
/// <param name="password">The password to use during the symmetric part of the encryption.</param>
/// <exception cref="ArgumentNullException">
/// password - A password must be provided! or key - An RSA public key must be provided.
/// </exception>
public ASymmetricEncryption(RsaPublicKey key, EncryptionData password)
{
password = Check.NotNull(password, nameof(password));
if (password.IsEmpty)
{
throw new ArgumentNullException(nameof(password), "A password must be provided!");
}
if (password.Text.Length > 32)
{
throw new ArgumentOutOfRangeException(
nameof(password),
"RSA Encryption limits the password to 32 characters");
}
_publicKey = key ?? throw
new ArgumentNullException(
nameof(key),
"An RSA private key must be provided!");
_password = Equals(password.EncodingToUse, Encoding.UTF8)
? password
: new EncryptionData(password.Text, Encoding.UTF8);
EncryptedPassword = new RsaEncryption().Encrypt(_password, _publicKey);
}
/// <summary>
/// Initializes a new instance of the <see cref="ASymmetricEncryption"/> class.
/// </summary>
/// <param name="key">
/// The private key that will be used to decrypt the password used to decrypt the payload.
/// </param>
/// <exception cref="ArgumentNullException">An RSA private key must be provided.</exception>
public ASymmetricEncryption(RsaPrivateKey key)
{
_privateKey = key ?? throw
new ArgumentNullException(
nameof(key),
"An RSA private key must be provided!");
EncryptedPassword = new EncryptionData(new byte[256]);
}
/// <summary>
/// Gets the encrypted password.
/// </summary>
public EncryptionData EncryptedPassword
{
get;
}
/// <summary>
/// Decrypts the specified data using preset key and preset initialization vector.
/// </summary>
/// <param name="encryptedData">The encrypted data.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// The specified separator between password and payload wasn't found.
/// </exception>
/// <returns>the decrypted data.</returns>
public EncryptionData Decrypt(EncryptionData encryptedData)
{
encryptedData = Check.NotNull(encryptedData, nameof(encryptedData));
if (_privateKey == null)
{
throw new InvalidOperationException(
"In order to decrypt, you must provide the private key.");
}
var iv = new byte[16];
EncryptionData payload;
try
{
payload = ExtractParts(encryptedData);
}
catch (CryptographicException ex)
{
throw new CryptographicException("Wrong RSA Private Key Provided!", ex);
}
var password = _password.Bytes;
Buffer.BlockCopy(password, 0, iv, 0, 16);
using (var decrypt = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
Key = new EncryptionData(password),
InitializationVector = new EncryptionData(iv)
})
{
var decryptedData = decrypt.Decrypt(payload);
return decryptedData;
}
}
/// <summary>
/// Decrypts the specified stream using preset key and preset initialization vector.
/// </summary>
/// <param name="encryptedStream">The encrypted stream.</param>
/// <returns>the decrypted data.</returns>
public EncryptionData Decrypt(Stream encryptedStream)
{
encryptedStream = Check.NotNull(encryptedStream, nameof(encryptedStream));
if (_privateKey == null)
{
throw new InvalidOperationException(
"In order to decrypt, you must provide the private key.");
}
var b = new byte[encryptedStream.Length];
_ = encryptedStream.Read(b, 0, (int)encryptedStream.Length);
return Decrypt(new EncryptionData(b));
}
/// <summary>
/// Encrypts the specified Data using preset key and preset initialization vector.
/// </summary>
/// <param name="plainData">The data to encrypt.</param>
/// <returns>the encrypted data.</returns>
public EncryptionData Encrypt(EncryptionData plainData)
{
plainData = Check.NotNull(plainData, nameof(plainData));
if (plainData.IsEmpty)
{
throw new ArgumentException("Invalid Encrypted Data!");
}
if (_publicKey == null)
{
throw new InvalidOperationException(
"In order to encrypt, you must provide the public key.");
}
var iv = new byte[16];
var password = _password.Bytes;
if (password.Length < 32)
{
password = password.Concat(new byte[32 - password.Length]).ToArray();
}
Buffer.BlockCopy(password, 0, iv, 0, 16);
using (var encrypt = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
Key = new EncryptionData(password),
InitializationVector = new EncryptionData(iv)
})
{
var encryptedData = encrypt.Encrypt(plainData);
return CombineEncrypted(encryptedData);
}
}
/// <summary>
/// Encrypts the stream to memory using provided key and provided initialization vector.
/// </summary>
/// <param name="plainStream">The stream to preform the cryptographic function on.</param>
/// <returns>the encrypted data.</returns>
public EncryptionData Encrypt(Stream plainStream)
{
plainStream = Check.NotNull(plainStream, nameof(plainStream));
if (!plainStream.CanRead)
{
throw new ArgumentException("Can not read from the stream!");
}
if (_publicKey == null)
{
throw new InvalidOperationException(
"In order to encrypt, you must provide the public key.");
}
var iv = new byte[16];
var password = _password.Bytes;
Buffer.BlockCopy(password, 0, iv, 0, 16);
using (var encrypt = new SymmetricEncryption(SymmetricEncryption.Provider.Rijndael)
{
Key = new EncryptionData(password),
InitializationVector = new EncryptionData(iv)
})
{
var encryptedData = encrypt.Encrypt(plainStream);
return CombineEncrypted(encryptedData);
}
}
private EncryptionData CombineEncrypted(EncryptionData payload)
{
var passwordLength = EncryptedPassword.Bytes.Length;
var payloadLength = payload.Bytes.Length;
var b = new byte[passwordLength + payloadLength];
Buffer.BlockCopy(EncryptedPassword.Bytes, 0, b, 0, passwordLength);
Buffer.BlockCopy(payload.Bytes, 0, b, passwordLength, payloadLength);
return new EncryptionData(b);
}
private EncryptionData ExtractParts(EncryptionData encryptedData)
{
if (encryptedData.IsEmpty)
{
throw new ArgumentException("Encrypted data is empty!");
}
if (encryptedData.Bytes.Length < 257)
{
throw new ArgumentException("Improper Encryption Data!");
}
var password = new byte[256];
Buffer.BlockCopy(encryptedData.Bytes, 0, password, 0, 256);
var payloadLength = encryptedData.Bytes.Length - 256;
var payload = new byte[payloadLength];
Buffer.BlockCopy(encryptedData.Bytes, 256, payload, 0, payloadLength);
_password = new RsaEncryption().Decrypt(new EncryptionData(password), _privateKey);
return new EncryptionData(payload);
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Google.ProtocolBuffers;
using Grpc.Core;
using Grpc.Core.Utils;
using NUnit.Framework;
using grpc.testing;
namespace Grpc.IntegrationTesting
{
public class InteropClient
{
private class ClientOptions
{
public bool help;
public string serverHost;
public string serverHostOverride;
public int? serverPort;
public string testCase;
public bool useTls;
public bool useTestCa;
}
ClientOptions options;
private InteropClient(ClientOptions options)
{
this.options = options;
}
public static void Run(string[] args)
{
Console.WriteLine("gRPC C# interop testing client");
ClientOptions options = ParseArguments(args);
if (options.serverHost == null || !options.serverPort.HasValue || options.testCase == null)
{
Console.WriteLine("Missing required argument.");
Console.WriteLine();
options.help = true;
}
if (options.help)
{
Console.WriteLine("Usage:");
Console.WriteLine(" --server_host=HOSTNAME");
Console.WriteLine(" --server_host_override=HOSTNAME");
Console.WriteLine(" --server_port=PORT");
Console.WriteLine(" --test_case=TESTCASE");
Console.WriteLine(" --use_tls=BOOLEAN");
Console.WriteLine(" --use_test_ca=BOOLEAN");
Console.WriteLine();
Environment.Exit(1);
}
var interopClient = new InteropClient(options);
interopClient.Run();
}
private void Run()
{
GrpcEnvironment.Initialize();
string addr = string.Format("{0}:{1}", options.serverHost, options.serverPort);
using (Channel channel = new Channel(addr))
{
TestServiceGrpc.ITestServiceClient client = new TestServiceGrpc.TestServiceClientStub(channel);
RunTestCase(options.testCase, client);
}
GrpcEnvironment.Shutdown();
}
private void RunTestCase(string testCase, TestServiceGrpc.ITestServiceClient client)
{
switch (testCase)
{
case "empty_unary":
RunEmptyUnary(client);
break;
case "large_unary":
RunLargeUnary(client);
break;
case "client_streaming":
RunClientStreaming(client);
break;
case "server_streaming":
RunServerStreaming(client);
break;
case "ping_pong":
RunPingPong(client);
break;
case "empty_stream":
RunEmptyStream(client);
break;
case "benchmark_empty_unary":
RunBenchmarkEmptyUnary(client);
break;
default:
throw new ArgumentException("Unknown test case " + testCase);
}
}
public static void RunEmptyUnary(TestServiceGrpc.ITestServiceClient client)
{
Console.WriteLine("running empty_unary");
var response = client.EmptyCall(Empty.DefaultInstance);
Assert.IsNotNull(response);
Console.WriteLine("Passed!");
}
public static void RunLargeUnary(TestServiceGrpc.ITestServiceClient client)
{
Console.WriteLine("running large_unary");
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Console.WriteLine("Passed!");
}
public static void RunClientStreaming(TestServiceGrpc.ITestServiceClient client)
{
Console.WriteLine("running client_streaming");
var bodySizes = new List<int>{27182, 8, 1828, 45904};
var context = client.StreamingInputCall();
foreach (var size in bodySizes)
{
context.Inputs.OnNext(
StreamingInputCallRequest.CreateBuilder().SetPayload(CreateZerosPayload(size)).Build());
}
context.Inputs.OnCompleted();
var response = context.Task.Result;
Assert.AreEqual(74922, response.AggregatedPayloadSize);
Console.WriteLine("Passed!");
}
public static void RunServerStreaming(TestServiceGrpc.ITestServiceClient client)
{
Console.WriteLine("running server_streaming");
var bodySizes = new List<int>{31415, 9, 2653, 58979};
var request = StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddRangeResponseParameters(bodySizes.ConvertAll(
(size) => ResponseParameters.CreateBuilder().SetSize(size).Build()))
.Build();
var recorder = new RecordingObserver<StreamingOutputCallResponse>();
client.StreamingOutputCall(request, recorder);
var responseList = recorder.ToList().Result;
foreach (var res in responseList)
{
Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type);
}
CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length));
Console.WriteLine("Passed!");
}
public static void RunPingPong(TestServiceGrpc.ITestServiceClient client)
{
Console.WriteLine("running ping_pong");
var recorder = new RecordingQueue<StreamingOutputCallResponse>();
var inputs = client.FullDuplexCall(recorder);
StreamingOutputCallResponse response;
inputs.OnNext(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
.SetPayload(CreateZerosPayload(27182)).Build());
response = recorder.Queue.Take();
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(31415, response.Payload.Body.Length);
inputs.OnNext(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(9))
.SetPayload(CreateZerosPayload(8)).Build());
response = recorder.Queue.Take();
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(9, response.Payload.Body.Length);
inputs.OnNext(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(2653))
.SetPayload(CreateZerosPayload(1828)).Build());
response = recorder.Queue.Take();
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(2653, response.Payload.Body.Length);
inputs.OnNext(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(58979))
.SetPayload(CreateZerosPayload(45904)).Build());
response = recorder.Queue.Take();
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(58979, response.Payload.Body.Length);
inputs.OnCompleted();
recorder.Finished.Wait();
Assert.AreEqual(0, recorder.Queue.Count);
Console.WriteLine("Passed!");
}
public static void RunEmptyStream(TestServiceGrpc.ITestServiceClient client)
{
Console.WriteLine("running empty_stream");
var recorder = new RecordingObserver<StreamingOutputCallResponse>();
var inputs = client.FullDuplexCall(recorder);
inputs.OnCompleted();
var responseList = recorder.ToList().Result;
Assert.AreEqual(0, responseList.Count);
Console.WriteLine("Passed!");
}
// This is not an official interop test, but it's useful.
public static void RunBenchmarkEmptyUnary(TestServiceGrpc.ITestServiceClient client)
{
BenchmarkUtil.RunBenchmark(10000, 10000,
() => { client.EmptyCall(Empty.DefaultInstance);});
}
private static Payload CreateZerosPayload(int size) {
return Payload.CreateBuilder().SetBody(ByteString.CopyFrom(new byte[size])).Build();
}
private static ClientOptions ParseArguments(string[] args)
{
var options = new ClientOptions();
foreach(string arg in args)
{
ParseArgument(arg, options);
if (options.help)
{
break;
}
}
return options;
}
private static void ParseArgument(string arg, ClientOptions options)
{
Match match;
match = Regex.Match(arg, "--server_host=(.*)");
if (match.Success)
{
options.serverHost = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--server_host_override=(.*)");
if (match.Success)
{
options.serverHostOverride = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--server_port=(.*)");
if (match.Success)
{
options.serverPort = int.Parse(match.Groups[1].Value.Trim());
return;
}
match = Regex.Match(arg, "--test_case=(.*)");
if (match.Success)
{
options.testCase = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--use_tls=(.*)");
if (match.Success)
{
options.useTls = bool.Parse(match.Groups[1].Value.Trim());
return;
}
match = Regex.Match(arg, "--use_test_ca=(.*)");
if (match.Success)
{
options.useTestCa = bool.Parse(match.Groups[1].Value.Trim());
return;
}
Console.WriteLine(string.Format("Unrecognized argument \"{0}\"", arg));
options.help = true;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class StopAllReplaysRequestEncoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 19;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private StopAllReplaysRequestEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public StopAllReplaysRequestEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public StopAllReplaysRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public StopAllReplaysRequestEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public StopAllReplaysRequestEncoder ControlSessionId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public StopAllReplaysRequestEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public StopAllReplaysRequestEncoder RecordingId(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
StopAllReplaysRequestDecoder writer = new StopAllReplaysRequestDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using Amazon.Auth.AccessControlPolicy;
using Amazon.Auth.AccessControlPolicy.ActionIdentifiers;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.Lambda;
using Amazon.Lambda.Model;
using Amazon.Runtime;
using CommonTests.Framework;
using NUnit.Framework;
using System.IO.Compression;
using System.Text;
namespace CommonTests.IntegrationTests
{
[TestFixture]
public class LambdaTests : TestBase<AmazonLambdaClient>
{
static IAmazonIdentityManagementService iamClient = TestBase.CreateClient<AmazonIdentityManagementServiceClient>();
static List<string> createdFunctionNames = new List<string>();
[OneTimeTearDown]
public void Cleanup()
{
BaseClean();
}
[TearDown]
public void TestCleanup()
{
DeleteCreatedFunctions(Client);
}
public static void DeleteCreatedFunctions(IAmazonLambda lambdaClient)
{
var deletedFunctions = new List<string>();
foreach(var function in createdFunctionNames)
{
try
{
lambdaClient.DeleteFunctionAsync(function).Wait();
deletedFunctions.Add(function);
}
catch { }
}
foreach (var df in deletedFunctions)
createdFunctionNames.Remove(df);
}
[Test]
public void ListFunctionsTest()
{
var result = Client.ListFunctionsAsync().Result;
Assert.IsNotNull(result);
Assert.IsNotNull(result.ResponseMetadata);
Assert.IsNotNull(result.ResponseMetadata.RequestId);
}
static readonly string LAMBDA_ASSUME_ROLE_POLICY =
@"
{
""Version"": ""2012-10-17"",
""Statement"": [
{
""Sid"": """",
""Effect"": ""Allow"",
""Principal"": {
""Service"": ""lambda.amazonaws.com""
},
""Action"": ""sts:AssumeRole""
}
]
}
".Trim();
[Test]
public void LambdaFunctionTest()
{
string functionName;
string iamRoleName = null;
bool iamRoleCreated = false;
try
{
string iamRoleArn;
string functionArn;
CreateLambdaFunction(out functionName, out functionArn, out iamRoleName, out iamRoleArn);
// List all the functions and make sure the newly uploaded function is in the collection
var listResponse = Client.ListFunctionsAsync().Result;
var function = listResponse.Functions.FirstOrDefault(x => x.FunctionName == functionName);
Assert.IsNotNull(function);
Assert.AreEqual("helloworld.handler", function.Handler);
Assert.AreEqual(iamRoleArn, function.Role);
// Get the function with a presigned URL to the uploaded code
var getFunctionResponse = Client.GetFunctionAsync(functionName).Result;
Assert.AreEqual("helloworld.handler", getFunctionResponse.Configuration.Handler);
Assert.IsNotNull(getFunctionResponse.Code.Location);
// Get the function's configuration only
var getFunctionConfiguration = Client.GetFunctionConfigurationAsync(functionName).Result;
Assert.AreEqual("helloworld.handler", getFunctionConfiguration.Handler);
// Call the function
#pragma warning disable 618
var invokeAsyncResponse = Client.InvokeAsyncAsync(new InvokeAsyncRequest
{
FunctionName = functionName,
InvokeArgs = "{}"
}).Result;
#pragma warning restore 618
Assert.AreEqual(invokeAsyncResponse.Status, 202); // Status Code Accepted
var clientContext = @"{""System"": ""Windows""}";
var clientContextBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(clientContext));
var request = new InvokeRequest
{
FunctionName = functionName,
InvocationType = InvocationType.RequestResponse,
LogType = LogType.None,
ClientContext = clientContext,
Payload = @"{""Key"": ""testing""}"
};
Assert.AreEqual(clientContext, request.ClientContext);
Assert.AreEqual(clientContextBase64, request.ClientContextBase64);
// Call the function sync
var invokeSyncResponse = Client.InvokeAsync(request).Result;
Assert.IsNull(invokeSyncResponse.FunctionError);
Assert.IsNull(invokeSyncResponse.LogResult);
Assert.IsNotNull(invokeSyncResponse.Payload);
Assert.AreNotEqual(0, invokeSyncResponse.Payload.Length);
Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
// Call the function sync, dry run, no payload
invokeSyncResponse = Client.InvokeAsync(new InvokeRequest
{
FunctionName = functionName,
InvocationType = InvocationType.DryRun,
LogType = LogType.None,
ClientContext = clientContext,
Payload = @"{""Key"": ""testing""}"
}).Result;
Assert.IsNull(invokeSyncResponse.FunctionError);
Assert.IsNull(invokeSyncResponse.LogResult);
Assert.IsNotNull(invokeSyncResponse.Payload);
Assert.AreEqual(0, invokeSyncResponse.Payload.Length);
Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
// Call the function sync, pass non-JSON payload
invokeSyncResponse = Client.InvokeAsync(new InvokeRequest
{
FunctionName = functionName,
InvocationType = InvocationType.RequestResponse,
LogType = LogType.None,
ClientContext = clientContext,
Payload = @"""Key"": ""testing"""
}).Result;
Assert.IsNotNull(invokeSyncResponse.FunctionError);
Assert.IsNull(invokeSyncResponse.LogResult);
Assert.IsNotNull(invokeSyncResponse.Payload);
Assert.AreNotEqual(0, invokeSyncResponse.Payload.Length);
Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
}
finally
{
if (iamRoleCreated)
iamClient.DeleteRoleAsync(new DeleteRoleRequest { RoleName = iamRoleName }).Wait();
}
}
public void CreateLambdaFunction(out string functionName, out string functionArn, out string iamRoleName, out string iamRoleArn)
{
functionName = "HelloWorld-" + DateTime.Now.Ticks;
iamRoleName = "Lambda-" + DateTime.Now.Ticks;
CreateLambdaFunction(functionName, iamRoleName, out iamRoleArn, out functionArn);
}
public void CreateLambdaFunction(string functionName, string iamRoleName, out string iamRoleArn, out string functionArn)
{
var iamCreateResponse = iamClient.CreateRoleAsync(new CreateRoleRequest
{
RoleName = iamRoleName,
AssumeRolePolicyDocument = LAMBDA_ASSUME_ROLE_POLICY
}).Result;
iamRoleArn = iamCreateResponse.Role.Arn;
var statement = new Amazon.Auth.AccessControlPolicy.Statement(
Amazon.Auth.AccessControlPolicy.Statement.StatementEffect.Allow);
statement.Actions.Add(S3ActionIdentifiers.PutObject);
statement.Actions.Add(S3ActionIdentifiers.GetObject);
statement.Resources.Add(new Resource("*"));
var policy = new Amazon.Auth.AccessControlPolicy.Policy();
policy.Statements.Add(statement);
iamClient.PutRolePolicyAsync(new PutRolePolicyRequest
{
RoleName = iamRoleName,
PolicyName = "admin",
PolicyDocument = policy.ToJson()
}).Wait();
MemoryStream stream = GetScriptStream();
var uploadRequest = new CreateFunctionRequest
{
FunctionName = functionName,
Code = new FunctionCode
{
ZipFile = stream
},
Handler = "helloworld.handler",
//Mode = Mode.Event,
Runtime = Runtime.Nodejs,
Role = iamCreateResponse.Role.Arn
};
var uploadResponse = UtilityMethods.WaitUntilSuccess(() => Client.CreateFunctionAsync(uploadRequest).Result);
createdFunctionNames.Add(functionName);
Assert.IsTrue(uploadResponse.CodeSize > 0);
Assert.IsNotNull(uploadResponse.FunctionArn);
functionArn = uploadResponse.FunctionArn;
}
private static MemoryStream GetScriptStream()
{
return new MemoryStream(Convert.FromBase64String(HELLO_SCRIPT_BYTES_BASE64));
}
private static string HELLO_SCRIPT_BYTES_BASE64 = "UEsDBBQAAAAIANZsA0emOtZ2nwAAANoAAAANAAAAaGVsbG93b3JsZC5qc1XMQQuCQBCG4bvgfxj2opKs96STBEHdJDovOqkwzoS7mhL999Qw6DYfzPMWwlYINUkVBhcxZcMV4IDsgij1PRwf0jmra8MlYQcHuPdcuEY4XJ9iKIQdji6Cl+/Bsn45NRjqcSYKdt+kPuO0VGFTuhTGkHuiGNQJiQRu0lG5/yPzreK1srF8sg7bKAVIEsivWXbMc3g2roYWrTUV+t77A1BLAQIUABQAAAAIANZsA0emOtZ2nwAAANoAAAANAAAAAAAAAAAAAAAAAAAAAABoZWxsb3dvcmxkLmpzUEsFBgAAAAABAAEAOwAAAMoAAAAAAA==";
// The above base64 string was generated by calling the below function in a 4.5 application with name="helloworld" and script=HELLO_SCRIPT
// private static string HELLO_SCRIPT =
//@"console.log('Loading event');
//exports.handler = function(event, context) {
// console.log(""value = "" + event.Key);
// context.done(null, ""Hello World:"" + event.Key + "", "" + context.System); // SUCCESS with message
//}";
//private static string CreateScriptBytesBase64(string name, string script)
//{
// using (var stream = new MemoryStream())
// {
// using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
// {
// var entry = archive.CreateEntry(name + ".js");
// using (var entryStream = entry.Open())
// using (var writer = new StreamWriter(entryStream))
// {
// writer.Write(script);
// }
// }
// var bytes = stream.ToArray();
// var base64 = Convert.ToBase64String(bytes);
// return base64;
// }
//}
//#endif
}
}
| |
namespace Azure.Storage.Queues
{
public partial class QueueClient
{
protected QueueClient() { }
public QueueClient(string connectionString, string queueName) { }
public QueueClient(string connectionString, string queueName, Azure.Storage.Queues.QueueClientOptions options) { }
public QueueClient(System.Uri queueUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueClient(System.Uri queueUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public virtual string AccountName { get { throw null; } }
public virtual int MaxPeekableMessages { get { throw null; } }
public virtual int MessageMaxBytes { get { throw null; } }
protected virtual System.Uri MessagesUri { get { throw null; } }
public virtual string Name { get { throw null; } }
public virtual System.Uri Uri { get { throw null; } }
public virtual Azure.Response ClearMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> ClearMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Create(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CreateAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response CreateIfNotExists(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CreateIfNotExistsAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response Delete(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<bool> DeleteIfExists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<bool>> DeleteIfExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteMessage(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteMessageAsync(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<bool> Exists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>> GetAccessPolicy(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>>> GetAccessPolicyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]> PeekMessages(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]>> PeekMessagesAsync(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages() { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync() { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetAccessPolicy(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetAccessPolicyAsync(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetMetadata(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetMetadataAsync(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class QueueClientOptions : Azure.Core.ClientOptions
{
public QueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2019_12_12) { }
public System.Uri GeoRedundantSecondaryUri { get { throw null; } set { } }
public Azure.Storage.Queues.QueueClientOptions.ServiceVersion Version { get { throw null; } }
public enum ServiceVersion
{
V2019_02_02 = 1,
V2019_07_07 = 2,
V2019_12_12 = 3,
}
}
public partial class QueueServiceClient
{
protected QueueServiceClient() { }
public QueueServiceClient(string connectionString) { }
public QueueServiceClient(string connectionString, Azure.Storage.Queues.QueueClientOptions options) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Storage.Queues.QueueClientOptions options = null) { }
public QueueServiceClient(System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { }
public virtual string AccountName { get { throw null; } }
public virtual System.Uri Uri { get { throw null; } }
public virtual Azure.Response<Azure.Storage.Queues.QueueClient> CreateQueue(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.QueueClient>> CreateQueueAsync(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteQueue(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteQueueAsync(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Storage.Queues.QueueClient GetQueueClient(string queueName) { throw null; }
public virtual Azure.Pageable<Azure.Storage.Queues.Models.QueueItem> GetQueues(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Storage.Queues.Models.QueueItem> GetQueuesAsync(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics> GetStatistics(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics>> GetStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetProperties(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetPropertiesAsync(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class QueueUriBuilder
{
public QueueUriBuilder(System.Uri uri) { }
public string AccountName { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public string MessageId { get { throw null; } set { } }
public bool Messages { get { throw null; } set { } }
public int Port { get { throw null; } set { } }
public string Query { get { throw null; } set { } }
public string QueueName { get { throw null; } set { } }
public Azure.Storage.Sas.SasQueryParameters Sas { get { throw null; } set { } }
public string Scheme { get { throw null; } set { } }
public override string ToString() { throw null; }
public System.Uri ToUri() { throw null; }
}
}
namespace Azure.Storage.Queues.Models
{
public partial class PeekedMessage
{
internal PeekedMessage() { }
public long DequeueCount { get { throw null; } }
public System.DateTimeOffset? ExpiresOn { get { throw null; } }
public System.DateTimeOffset? InsertedOn { get { throw null; } }
public string MessageId { get { throw null; } }
public string MessageText { get { throw null; } }
}
public partial class QueueAccessPolicy
{
public QueueAccessPolicy() { }
public System.DateTimeOffset? ExpiresOn { get { throw null; } set { } }
public string Permissions { get { throw null; } set { } }
public System.DateTimeOffset? StartsOn { get { throw null; } set { } }
}
public partial class QueueAnalyticsLogging
{
public QueueAnalyticsLogging() { }
public bool Delete { get { throw null; } set { } }
public bool Read { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
public bool Write { get { throw null; } set { } }
}
public partial class QueueCorsRule
{
public QueueCorsRule() { }
public string AllowedHeaders { get { throw null; } set { } }
public string AllowedMethods { get { throw null; } set { } }
public string AllowedOrigins { get { throw null; } set { } }
public string ExposedHeaders { get { throw null; } set { } }
public int MaxAgeInSeconds { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct QueueErrorCode : System.IEquatable<Azure.Storage.Queues.Models.QueueErrorCode>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public QueueErrorCode(string value) { throw null; }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountBeingCreated { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AccountIsDisabled { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthenticationFailed { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationFailure { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationPermissionMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationProtocolMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationResourceTypeMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationServiceMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationSourceIPMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ConditionHeadersNotSupported { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ConditionNotMet { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode EmptyMetadataKey { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode FeatureVersionMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InsufficientAccountPermissions { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InternalError { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidAuthenticationInfo { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHeaderValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHttpVerb { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidInput { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMarker { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMd5 { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMetadata { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidQueryParameterValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidRange { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidResourceName { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidUri { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlDocument { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlNodeValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode Md5Mismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MessageNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MessageTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MetadataTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingContentLengthHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredQueryParameter { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredXmlNode { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode MultipleConditionHeadersNotSupported { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OperationTimedOut { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeInput { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeQueryParameterValue { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode PopReceiptMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueBeingDeleted { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueDisabled { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotEmpty { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode RequestBodyTooLarge { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode RequestUrlFailedToParse { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceAlreadyExists { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceNotFound { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ResourceTypeMismatch { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode ServerBusy { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHeader { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHttpVerb { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedQueryParameter { get { throw null; } }
public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedXmlNode { get { throw null; } }
public bool Equals(Azure.Storage.Queues.Models.QueueErrorCode other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; }
public static implicit operator Azure.Storage.Queues.Models.QueueErrorCode (string value) { throw null; }
public static bool operator !=(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; }
public override string ToString() { throw null; }
}
public partial class QueueGeoReplication
{
internal QueueGeoReplication() { }
public System.DateTimeOffset? LastSyncedOn { get { throw null; } }
public Azure.Storage.Queues.Models.QueueGeoReplicationStatus Status { get { throw null; } }
}
public enum QueueGeoReplicationStatus
{
Live = 0,
Bootstrap = 1,
Unavailable = 2,
}
public partial class QueueItem
{
internal QueueItem() { }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
public string Name { get { throw null; } }
}
public partial class QueueMessage
{
internal QueueMessage() { }
public long DequeueCount { get { throw null; } }
public System.DateTimeOffset? ExpiresOn { get { throw null; } }
public System.DateTimeOffset? InsertedOn { get { throw null; } }
public string MessageId { get { throw null; } }
public string MessageText { get { throw null; } }
public System.DateTimeOffset? NextVisibleOn { get { throw null; } }
public string PopReceipt { get { throw null; } }
public Azure.Storage.Queues.Models.QueueMessage Update(Azure.Storage.Queues.Models.UpdateReceipt updated) { throw null; }
}
public partial class QueueMetrics
{
public QueueMetrics() { }
public bool Enabled { get { throw null; } set { } }
public bool? IncludeApis { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
}
public partial class QueueProperties
{
public QueueProperties() { }
public int ApproximateMessagesCount { get { throw null; } }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } }
}
public partial class QueueRetentionPolicy
{
public QueueRetentionPolicy() { }
public int? Days { get { throw null; } set { } }
public bool Enabled { get { throw null; } set { } }
}
public partial class QueueServiceProperties
{
public QueueServiceProperties() { }
public System.Collections.Generic.IList<Azure.Storage.Queues.Models.QueueCorsRule> Cors { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueMetrics HourMetrics { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueAnalyticsLogging Logging { get { throw null; } set { } }
public Azure.Storage.Queues.Models.QueueMetrics MinuteMetrics { get { throw null; } set { } }
}
public partial class QueueServiceStatistics
{
internal QueueServiceStatistics() { }
public Azure.Storage.Queues.Models.QueueGeoReplication GeoReplication { get { throw null; } }
}
public partial class QueueSignedIdentifier
{
public QueueSignedIdentifier() { }
public Azure.Storage.Queues.Models.QueueAccessPolicy AccessPolicy { get { throw null; } set { } }
public string Id { get { throw null; } set { } }
}
public static partial class QueuesModelFactory
{
public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, string messageText, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueGeoReplication QueueGeoReplication(Azure.Storage.Queues.Models.QueueGeoReplicationStatus status, System.DateTimeOffset? lastSyncedOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueItem QueueItem(string name, System.Collections.Generic.IDictionary<string, string> metadata = null) { throw null; }
public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, string messageText, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; }
public static Azure.Storage.Queues.Models.QueueProperties QueueProperties(System.Collections.Generic.IDictionary<string, string> metadata, int approximateMessagesCount) { throw null; }
public static Azure.Storage.Queues.Models.QueueServiceStatistics QueueServiceStatistics(Azure.Storage.Queues.Models.QueueGeoReplication geoReplication = null) { throw null; }
public static Azure.Storage.Queues.Models.SendReceipt SendReceipt(string messageId, System.DateTimeOffset insertionTime, System.DateTimeOffset expirationTime, string popReceipt, System.DateTimeOffset timeNextVisible) { throw null; }
public static Azure.Storage.Queues.Models.UpdateReceipt UpdateReceipt(string popReceipt, System.DateTimeOffset nextVisibleOn) { throw null; }
}
[System.FlagsAttribute]
public enum QueueTraits
{
None = 0,
Metadata = 1,
}
public partial class SendReceipt
{
internal SendReceipt() { }
public System.DateTimeOffset ExpirationTime { get { throw null; } }
public System.DateTimeOffset InsertionTime { get { throw null; } }
public string MessageId { get { throw null; } }
public string PopReceipt { get { throw null; } }
public System.DateTimeOffset TimeNextVisible { get { throw null; } }
}
public partial class UpdateReceipt
{
internal UpdateReceipt() { }
public System.DateTimeOffset NextVisibleOn { get { throw null; } }
public string PopReceipt { get { throw null; } }
}
}
namespace Azure.Storage.Queues.Specialized
{
public partial class ClientSideDecryptionFailureEventArgs
{
internal ClientSideDecryptionFailureEventArgs() { }
public System.Exception Exception { get { throw null; } }
}
public partial class QueueClientSideEncryptionOptions : Azure.Storage.ClientSideEncryptionOptions
{
public QueueClientSideEncryptionOptions(Azure.Storage.ClientSideEncryptionVersion version) : base (default(Azure.Storage.ClientSideEncryptionVersion)) { }
public event System.EventHandler<Azure.Storage.Queues.Specialized.ClientSideDecryptionFailureEventArgs> DecryptionFailed { add { } remove { } }
}
public partial class SpecializedQueueClientOptions : Azure.Storage.Queues.QueueClientOptions
{
public SpecializedQueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2019_12_12) : base (default(Azure.Storage.Queues.QueueClientOptions.ServiceVersion)) { }
public Azure.Storage.ClientSideEncryptionOptions ClientSideEncryption { get { throw null; } set { } }
}
public static partial class SpecializedQueueExtensions
{
public static Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptions(this Azure.Storage.Queues.QueueClient client, Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; }
}
}
namespace Azure.Storage.Sas
{
[System.FlagsAttribute]
public enum QueueAccountSasPermissions
{
All = -1,
Read = 1,
Write = 2,
Delete = 4,
List = 8,
Add = 16,
Update = 32,
Process = 64,
}
public partial class QueueSasBuilder
{
public QueueSasBuilder() { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
public string Identifier { get { throw null; } set { } }
public Azure.Storage.Sas.SasIPRange IPRange { get { throw null; } set { } }
public string Permissions { get { throw null; } }
public Azure.Storage.Sas.SasProtocol Protocol { get { throw null; } set { } }
public string QueueName { get { throw null; } set { } }
public System.DateTimeOffset StartsOn { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public void SetPermissions(Azure.Storage.Sas.QueueAccountSasPermissions permissions) { }
public void SetPermissions(Azure.Storage.Sas.QueueSasPermissions permissions) { }
public void SetPermissions(string rawPermissions) { }
public void SetPermissions(string rawPermissions, bool normalize = false) { }
public Azure.Storage.Sas.SasQueryParameters ToSasQueryParameters(Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum QueueSasPermissions
{
All = -1,
Read = 1,
Add = 2,
Update = 4,
Process = 8,
}
}
namespace Microsoft.Extensions.Azure
{
public static partial class QueueClientBuilderExtensions
{
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; }
public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; }
}
}
| |
/*
* Copyright 2001-2010 Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Quartz.Impl.Matchers;
using Quartz.Logging;
using Quartz.Spi;
using Quartz.Util;
using Quartz.Xml.JobSchedulingData20;
namespace Quartz.Xml
{
/// <summary>
/// Parses an XML file that declares Jobs and their schedules (Triggers).
/// </summary>
/// <remarks>
/// <para>
/// The xml document must conform to the format defined in "job_scheduling_data_2_0.xsd"
/// </para>
///
/// <para>
/// After creating an instance of this class, you should call one of the <see cref="ProcessFile(CancellationToken)" />
/// functions, after which you may call the ScheduledJobs()
/// function to get a handle to the defined Jobs and Triggers, which can then be
/// scheduled with the <see cref="IScheduler" />. Alternatively, you could call
/// the <see cref="ProcessFileAndScheduleJobs(Quartz.IScheduler, CancellationToken)" /> function to do all of this
/// in one step.
/// </para>
///
/// <para>
/// The same instance can be used again and again, with the list of defined Jobs
/// being cleared each time you call a <see cref="ProcessFile(CancellationToken)" /> method,
/// however a single instance is not thread-safe.
/// </para>
/// </remarks>
/// <author><a href="mailto:bonhamcm@thirdeyeconsulting.com">Chris Bonham</a></author>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
/// <author>Christian Krumm (.NET Bugfix)</author>
public class XMLSchedulingDataProcessor
{
public const string QuartzXmlFileName = "quartz_jobs.xml";
public const string QuartzXsdResourceName = "Quartz.Xml.job_scheduling_data_2_0.xsd";
// pre-processing commands
private readonly List<string> jobGroupsToDelete = new List<string>();
private readonly List<string> triggerGroupsToDelete = new List<string>();
private readonly List<JobKey> jobsToDelete = new List<JobKey>();
private readonly List<TriggerKey> triggersToDelete = new List<TriggerKey>();
// scheduling commands
private readonly List<IJobDetail> loadedJobs = new List<IJobDetail>();
private readonly List<ITrigger> loadedTriggers = new List<ITrigger>();
// directives
private readonly List<Exception> validationExceptions = new List<Exception>();
private readonly List<string> jobGroupsToNeverDelete = new List<string>();
private readonly List<string> triggerGroupsToNeverDelete = new List<string>();
/// <summary>
/// Constructor for XMLSchedulingDataProcessor.
/// </summary>
public XMLSchedulingDataProcessor(ITypeLoadHelper typeLoadHelper)
{
OverWriteExistingData = true;
IgnoreDuplicates = false;
Log = LogProvider.GetLogger(GetType());
TypeLoadHelper = typeLoadHelper;
}
/// <summary>
/// Whether the existing scheduling data (with same identifiers) will be
/// overwritten.
/// </summary>
/// <remarks>
/// If false, and <see cref="IgnoreDuplicates" /> is not false, and jobs or
/// triggers with the same names already exist as those in the file, an
/// error will occur.
/// </remarks>
/// <seealso cref="IgnoreDuplicates" />
public virtual bool OverWriteExistingData { get; set; }
/// <summary>
/// If true (and <see cref="OverWriteExistingData" /> is false) then any
/// job/triggers encountered in this file that have names that already exist
/// in the scheduler will be ignored, and no error will be produced.
/// </summary>
/// <seealso cref="OverWriteExistingData"/>
public virtual bool IgnoreDuplicates { get; set; }
/// <summary>
/// If true (and <see cref="OverWriteExistingData" /> is true) then any
/// job/triggers encountered in this file that already exist is scheduler
/// will be updated with start time relative to old trigger. Effectively
/// new trigger's last fire time will be updated to old trigger's last fire time
/// and trigger's next fire time will updated to be next from this last fire time.
/// </summary>
public virtual bool ScheduleTriggerRelativeToReplacedTrigger { get; set; }
/// <summary>
/// Gets the log.
/// </summary>
/// <value>The log.</value>
private ILog Log { get; }
protected virtual IReadOnlyList<IJobDetail> LoadedJobs => loadedJobs.AsReadOnly();
protected virtual IReadOnlyList<ITrigger> LoadedTriggers => loadedTriggers.AsReadOnly();
protected ITypeLoadHelper TypeLoadHelper { get; }
/// <summary>
/// Process the xml file in the default location (a file named
/// "quartz_jobs.xml" in the current working directory).
/// </summary>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual Task ProcessFile(CancellationToken cancellationToken = default)
{
return ProcessFile(QuartzXmlFileName, cancellationToken);
}
/// <summary>
/// Process the xml file named <see param="fileName" />.
/// </summary>
/// <param name="fileName">meta data file name.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual Task ProcessFile(
string fileName,
CancellationToken cancellationToken = default)
{
return ProcessFile(fileName, fileName, cancellationToken);
}
/// <summary>
/// Process the xmlfile named <see param="fileName" /> with the given system
/// ID.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="systemId">The system id.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual async Task ProcessFile(
string fileName,
string systemId,
CancellationToken cancellationToken = default)
{
// resolve file name first
fileName = FileUtil.ResolveFile(fileName) ?? fileName;
Log.InfoFormat("Parsing XML file: {0} with systemId: {1}", fileName, systemId);
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader sr = new StreamReader(stream))
{
ProcessInternal(await sr.ReadToEndAsync().ConfigureAwait(false));
}
}
/// <summary>
/// Process the xmlfile named <see param="fileName" /> with the given system
/// ID.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="systemId">The system id.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual async Task ProcessStream(
Stream stream,
string? systemId,
CancellationToken cancellationToken = default)
{
Log.InfoFormat("Parsing XML from stream with systemId: {0}", systemId);
using StreamReader sr = new StreamReader(stream);
ProcessInternal(await sr.ReadToEndAsync().ConfigureAwait(false));
}
protected virtual void PrepForProcessing()
{
ClearValidationExceptions();
OverWriteExistingData = true;
IgnoreDuplicates = false;
jobGroupsToDelete.Clear();
jobsToDelete.Clear();
triggerGroupsToDelete.Clear();
triggersToDelete.Clear();
loadedJobs.Clear();
loadedTriggers.Clear();
}
protected virtual void ProcessInternal(string xml)
{
PrepForProcessing();
ValidateXml(xml);
MaybeThrowValidationException();
// deserialize as object model
var xs = new XmlSerializer(typeof (QuartzXmlConfiguration20));
var data = (QuartzXmlConfiguration20?) xs.Deserialize(new StringReader(xml));
if (data == null)
{
throw new SchedulerConfigException("Job definition data from XML was null after deserialization");
}
//
// Extract pre-processing commands
//
if (data.preprocessingcommands != null)
{
foreach (preprocessingcommandsType command in data.preprocessingcommands)
{
if (command.deletejobsingroup != null)
{
foreach (string s in command.deletejobsingroup)
{
var deleteJobGroup = s.NullSafeTrim();
if (!string.IsNullOrEmpty(deleteJobGroup))
{
jobGroupsToDelete.Add(deleteJobGroup);
}
}
}
if (command.deletetriggersingroup != null)
{
foreach (string s in command.deletetriggersingroup)
{
var deleteTriggerGroup = s.NullSafeTrim();
if (!string.IsNullOrEmpty(deleteTriggerGroup))
{
triggerGroupsToDelete.Add(deleteTriggerGroup);
}
}
}
if (command.deletejob != null)
{
foreach (preprocessingcommandsTypeDeletejob s in command.deletejob)
{
var name = s.name.TrimEmptyToNull();
var group = s.group.TrimEmptyToNull();
if (name == null)
{
throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified.");
}
jobsToDelete.Add(new JobKey(name, group!));
}
}
if (command.deletetrigger != null)
{
foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger)
{
var name = s.name.TrimEmptyToNull();
var group = s.group.TrimEmptyToNull();
if (name == null)
{
throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified.");
}
triggersToDelete.Add(new TriggerKey(name, group!));
}
}
}
}
if (Log.IsDebugEnabled())
{
Log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands.");
Log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands.");
Log.Debug("Found " + jobsToDelete.Count + " delete job commands.");
Log.Debug("Found " + triggersToDelete.Count + " delete trigger commands.");
}
//
// Extract directives
//
if (data.processingdirectives != null && data.processingdirectives.Length > 0)
{
bool overWrite = data.processingdirectives[0].overwriteexistingdata;
Log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite);
OverWriteExistingData = overWrite;
}
else
{
Log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData);
}
if (data.processingdirectives != null && data.processingdirectives.Length > 0)
{
bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates;
Log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates);
IgnoreDuplicates = ignoreduplicates;
}
else
{
Log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates);
}
if (data.processingdirectives != null && data.processingdirectives.Length > 0)
{
bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger;
Log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative);
ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative;
}
else
{
Log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger);
}
//
// Extract Job definitions...
//
List<jobdetailType> jobNodes = new List<jobdetailType>();
if (data.schedule != null)
{
foreach (var schedule in data.schedule)
{
if (schedule?.job != null)
{
jobNodes.AddRange(schedule.job);
}
}
}
Log.Debug("Found " + jobNodes.Count + " job definitions.");
foreach (jobdetailType jobDetailType in jobNodes)
{
var jobName = jobDetailType.name.TrimEmptyToNull();
var jobGroup = jobDetailType.group.TrimEmptyToNull();
var jobDescription = jobDetailType.description.TrimEmptyToNull();
var jobTypeName = jobDetailType.jobtype.TrimEmptyToNull();
bool jobDurability = jobDetailType.durable;
bool jobRecoveryRequested = jobDetailType.recover;
Type jobType = TypeLoadHelper.LoadType(jobTypeName!)!;
IJobDetail jobDetail = JobBuilder.Create(jobType!)
.WithIdentity(jobName!, jobGroup!)
.WithDescription(jobDescription)
.StoreDurably(jobDurability)
.RequestRecovery(jobRecoveryRequested)
.Build();
if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null)
{
foreach (entryType entry in jobDetailType.jobdatamap.entry)
{
var key = entry.key.Trim();
var value = entry.value.TrimEmptyToNull();
jobDetail.JobDataMap.Add(key, value!);
}
}
if (Log.IsDebugEnabled())
{
Log.Debug("Parsed job definition: " + jobDetail);
}
AddJobToSchedule(jobDetail);
}
//
// Extract Trigger definitions...
//
List<triggerType> triggerEntries = new List<triggerType>();
if (data.schedule != null)
{
foreach (var schedule in data.schedule)
{
if (schedule != null && schedule.trigger != null)
{
triggerEntries.AddRange(schedule.trigger);
}
}
}
Log.Debug("Found " + triggerEntries.Count + " trigger definitions.");
foreach (triggerType triggerNode in triggerEntries)
{
var triggerName = triggerNode.Item.name.TrimEmptyToNull()!;
var triggerGroup = triggerNode.Item.group.TrimEmptyToNull()!;
var triggerDescription = triggerNode.Item.description.TrimEmptyToNull();
var triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull();
string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull()!;
string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull()!;
int triggerPriority = TriggerConstants.DefaultPriority;
if (!triggerNode.Item.priority.IsNullOrWhiteSpace())
{
triggerPriority = Convert.ToInt32(triggerNode.Item.priority);
}
DateTimeOffset triggerStartTime = SystemTime.UtcNow();
if (triggerNode.Item.Item != null)
{
if (triggerNode.Item.Item is DateTime time)
{
triggerStartTime = new DateTimeOffset(time);
}
else
{
triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item));
}
}
DateTime? triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?) null;
IScheduleBuilder sched;
if (triggerNode.Item is simpleTriggerType simpleTrigger)
{
var repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull();
var repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull();
int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString!);
TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString));
sched = SimpleScheduleBuilder.Create()
.WithInterval(repeatInterval)
.WithRepeatCount(repeatCount);
if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((SimpleScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction));
}
}
else if (triggerNode.Item is cronTriggerType)
{
cronTriggerType cronTrigger = (cronTriggerType) triggerNode.Item;
var cronExpression = cronTrigger.cronexpression.TrimEmptyToNull();
var timezoneString = cronTrigger.timezone.TrimEmptyToNull();
TimeZoneInfo? tz = timezoneString != null ? TimeZoneUtil.FindTimeZoneById(timezoneString) : null;
sched = CronScheduleBuilder.CronSchedule(cronExpression!)
.InTimeZone(tz!);
if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((CronScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction));
}
}
else if (triggerNode.Item is calendarIntervalTriggerType)
{
calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType) triggerNode.Item;
var repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull();
IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull());
int repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString);
sched = CalendarIntervalScheduleBuilder.Create()
.WithInterval(repeatInterval, intervalUnit);
if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace())
{
((CalendarIntervalScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction));
}
}
else
{
throw new SchedulerConfigException("Unknown trigger type in XML configuration");
}
IMutableTrigger trigger = (IMutableTrigger) TriggerBuilder.Create()
.WithIdentity(triggerName, triggerGroup)
.WithDescription(triggerDescription)
.ForJob(triggerJobName, triggerJobGroup)
.StartAt(triggerStartTime)
.EndAt(triggerEndTime)
.WithPriority(triggerPriority)
.ModifiedByCalendar(triggerCalendarRef)
.WithSchedule(sched)
.Build();
if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null)
{
foreach (entryType entry in triggerNode.Item.jobdatamap.entry)
{
string key = entry.key.TrimEmptyToNull()!;
var value = entry.value.TrimEmptyToNull();
trigger.JobDataMap.Add(key, value!);
}
}
if (Log.IsDebugEnabled())
{
Log.Debug("Parsed trigger definition: " + trigger);
}
AddTriggerToSchedule(trigger);
}
}
protected virtual void AddJobToSchedule(IJobDetail job)
{
loadedJobs.Add(job);
}
protected virtual void AddTriggerToSchedule(IMutableTrigger trigger)
{
loadedTriggers.Add(trigger);
}
protected virtual int ParseSimpleTriggerRepeatCount(string repeatcount)
{
int value = Convert.ToInt32(repeatcount, CultureInfo.InvariantCulture);
return value;
}
protected virtual int ReadMisfireInstructionFromString(string misfireinstruction)
{
Constants c = new Constants(typeof (MisfireInstruction), typeof (MisfireInstruction.CronTrigger),
typeof (MisfireInstruction.SimpleTrigger));
return c.AsNumber(misfireinstruction);
}
protected virtual IntervalUnit ParseDateIntervalTriggerIntervalUnit(string? intervalUnit)
{
if (string.IsNullOrEmpty(intervalUnit))
{
return IntervalUnit.Day;
}
if (!TryParseEnum(intervalUnit, out IntervalUnit retValue))
{
throw new SchedulerConfigException("Unknown interval unit for DateIntervalTrigger: " + intervalUnit);
}
return retValue;
}
protected virtual bool TryParseEnum<T>(string str, out T value) where T : struct
{
var names = Enum.GetNames(typeof (T));
value = (T) Enum.GetValues(typeof (T)).GetValue(0)!;
foreach (var name in names)
{
if (name == str)
{
value = (T) Enum.Parse(typeof (T), name);
return true;
}
}
return false;
}
private void ValidateXml(string xml)
{
try
{
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema
| XmlSchemaValidationFlags.ProcessSchemaLocation
| XmlSchemaValidationFlags.ReportValidationWarnings
};
using var stream = typeof(XMLSchedulingDataProcessor).Assembly.GetManifestResourceStream(QuartzXsdResourceName);
if (stream is null)
{
throw new Exception("Could not read XSD from embedded resource");
}
var schema = XmlSchema.Read(stream, XmlValidationCallBack);
settings.Schemas.Add(schema!);
settings.ValidationEventHandler += XmlValidationCallBack;
// stream to validate
using var reader = XmlReader.Create(new StringReader(xml), settings);
while (reader.Read())
{
}
}
catch (Exception ex)
{
Log.WarnException("Unable to validate XML with schema: " + ex.Message, ex);
}
}
private void XmlValidationCallBack(object? sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error)
{
validationExceptions.Add(e.Exception);
}
else
{
Log.Warn(e.Message);
}
}
/// <summary>
/// Process the xml file in the default location, and schedule all of the jobs defined within it.
/// </summary>
/// <remarks>Note that we will set overWriteExistingJobs after the default xml is parsed.</remarks>
public async Task ProcessFileAndScheduleJobs(
IScheduler sched,
bool overWriteExistingJobs,
CancellationToken cancellationToken = default)
{
await ProcessFile(QuartzXmlFileName, QuartzXmlFileName, cancellationToken).ConfigureAwait(false);
// The overWriteExistingJobs flag was set by processFile() -> prepForProcessing(), then by xml parsing, and then now
// we need to reset it again here by this method parameter to override it.
OverWriteExistingData = overWriteExistingJobs;
await ExecutePreProcessCommands(sched, cancellationToken).ConfigureAwait(false);
await ScheduleJobs(sched, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Process the xml file in the default location, and schedule all of the
/// jobs defined within it.
/// </summary>
public virtual Task ProcessFileAndScheduleJobs(
IScheduler sched,
CancellationToken cancellationToken = default)
{
return ProcessFileAndScheduleJobs(QuartzXmlFileName, sched, cancellationToken);
}
/// <summary>
/// Process the xml file in the given location, and schedule all of the
/// jobs defined within it.
/// </summary>
/// <param name="fileName">meta data file name.</param>
/// <param name="sched">The scheduler.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual Task ProcessFileAndScheduleJobs(
string fileName,
IScheduler sched,
CancellationToken cancellationToken = default)
{
return ProcessFileAndScheduleJobs(fileName, fileName, sched, cancellationToken);
}
/// <summary>
/// Process the xml file in the given location, and schedule all of the
/// jobs defined within it.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="systemId">The system id.</param>
/// <param name="sched">The sched.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual async Task ProcessFileAndScheduleJobs(
string fileName,
string systemId,
IScheduler sched,
CancellationToken cancellationToken = default)
{
await ProcessFile(fileName, systemId, cancellationToken).ConfigureAwait(false);
await ExecutePreProcessCommands(sched, cancellationToken).ConfigureAwait(false);
await ScheduleJobs(sched, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Process the xml file in the given location, and schedule all of the
/// jobs defined within it.
/// </summary>
/// <param name="stream">stream to read XML data from.</param>
/// <param name="sched">The sched.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual async Task ProcessStreamAndScheduleJobs(
Stream stream,
IScheduler sched,
CancellationToken cancellationToken = default)
{
using (var sr = new StreamReader(stream))
{
ProcessInternal(await sr.ReadToEndAsync().ConfigureAwait(false));
}
await ExecutePreProcessCommands(sched, cancellationToken).ConfigureAwait(false);
await ScheduleJobs(sched, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Schedules the given sets of jobs and triggers.
/// </summary>
/// <param name="sched">The sched.</param>
/// <param name="cancellationToken">The cancellation instruction.</param>
public virtual async Task ScheduleJobs(
IScheduler sched,
CancellationToken cancellationToken = default)
{
List<IJobDetail> jobs = new List<IJobDetail>(LoadedJobs);
List<ITrigger> triggers = new List<ITrigger>(LoadedTriggers);
Log.Info("Adding " + jobs.Count + " jobs, " + triggers.Count + " triggers.");
IDictionary<JobKey, List<IMutableTrigger>> triggersByFQJobName = BuildTriggersByFQJobNameMap(triggers);
// add each job, and it's associated triggers
while (jobs.Count > 0)
{
// remove jobs as we handle them...
IJobDetail detail = jobs[0];
jobs.Remove(detail);
IJobDetail? dupeJ = null;
try
{
// The existing job could have been deleted, and Quartz API doesn't allow us to query this without
// loading the job class, so use try/catch to handle it.
dupeJ = await sched.GetJobDetail(detail.Key, cancellationToken).ConfigureAwait(false);
}
catch (JobPersistenceException e)
{
if (e.InnerException is TypeLoadException && OverWriteExistingData)
{
// We are going to replace jobDetail anyway, so just delete it first.
Log.Info("Removing job: " + detail.Key);
await sched.DeleteJob(detail.Key, cancellationToken).ConfigureAwait(false);
}
else
{
throw;
}
}
if (dupeJ != null)
{
if (!OverWriteExistingData && IgnoreDuplicates)
{
Log.Info("Not overwriting existing job: " + dupeJ.Key);
continue; // just ignore the entry
}
if (!OverWriteExistingData && !IgnoreDuplicates)
{
throw new ObjectAlreadyExistsException(detail);
}
}
if (dupeJ != null)
{
Log.Info("Replacing job: " + detail.Key);
}
else
{
Log.Info("Adding job: " + detail.Key);
}
triggersByFQJobName.TryGetValue(detail.Key, out var triggersOfJob);
if (!detail.Durable && (triggersOfJob == null || triggersOfJob.Count == 0))
{
if (dupeJ == null)
{
throw new SchedulerException(
"A new job defined without any triggers must be durable: " +
detail.Key);
}
if (dupeJ.Durable && (await sched.GetTriggersOfJob(detail.Key, cancellationToken).ConfigureAwait(false)).Count == 0)
{
throw new SchedulerException(
"Can't change existing durable job without triggers to non-durable: " +
detail.Key);
}
}
if (dupeJ != null || detail.Durable)
{
if (triggersOfJob != null && triggersOfJob.Count > 0)
{
await sched.AddJob(detail, true, true, cancellationToken).ConfigureAwait(false); // add the job regardless is durable or not b/c we have trigger to add
}
else
{
await sched.AddJob(detail, true, false, cancellationToken).ConfigureAwait(false); // add the job only if a replacement or durable, else exception will throw!
}
}
else
{
bool addJobWithFirstSchedule = true;
// Add triggers related to the job...
while (triggersOfJob!.Count > 0)
{
IMutableTrigger trigger = triggersOfJob[0];
// remove triggers as we handle them...
triggersOfJob.Remove(trigger);
ITrigger? dupeT = await sched.GetTrigger(trigger.Key, cancellationToken).ConfigureAwait(false);
if (dupeT != null)
{
if (OverWriteExistingData)
{
if (Log.IsDebugEnabled())
{
Log.DebugFormat("Rescheduling job: {0} with updated trigger: {1}", trigger.JobKey, trigger.Key);
}
}
else if (IgnoreDuplicates)
{
Log.Info("Not overwriting existing trigger: " + dupeT.Key);
continue; // just ignore the trigger (and possibly job)
}
else
{
throw new ObjectAlreadyExistsException(trigger);
}
if (!dupeT.JobKey.Equals(trigger.JobKey))
{
ReportDuplicateTrigger(trigger);
}
await DoRescheduleJob(sched, trigger, dupeT, cancellationToken).ConfigureAwait(false);
}
else
{
if (Log.IsDebugEnabled())
{
Log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key);
}
try
{
if (addJobWithFirstSchedule)
{
await sched.ScheduleJob(detail, trigger, cancellationToken).ConfigureAwait(false); // add the job if it's not in yet...
addJobWithFirstSchedule = false;
}
else
{
await sched.ScheduleJob(trigger, cancellationToken).ConfigureAwait(false);
}
}
catch (ObjectAlreadyExistsException)
{
if (Log.IsDebugEnabled())
{
Log.DebugFormat("Adding trigger: {0} for job: {1} failed because the trigger already existed. "
+ "This is likely due to a race condition between multiple instances "
+ "in the cluster. Will try to reschedule instead.", trigger.Key, detail.Key);
}
// Let's try one more time as reschedule.
var oldTrigger = await sched.GetTrigger(trigger.Key, cancellationToken).ConfigureAwait(false);
await DoRescheduleJob(sched, trigger, oldTrigger, cancellationToken).ConfigureAwait(false);
}
}
}
}
}
// add triggers that weren't associated with a new job... (those we already handled were removed above)
foreach (IMutableTrigger trigger in triggers)
{
ITrigger? dupeT = await sched.GetTrigger(trigger.Key, cancellationToken).ConfigureAwait(false);
if (dupeT != null)
{
if (OverWriteExistingData)
{
if (Log.IsDebugEnabled())
{
Log.DebugFormat("Rescheduling job: " + trigger.JobKey + " with updated trigger: " + trigger.Key);
}
}
else if (IgnoreDuplicates)
{
Log.Info("Not overwriting existing trigger: " + dupeT.Key);
continue; // just ignore the trigger
}
else
{
throw new ObjectAlreadyExistsException(trigger);
}
if (!dupeT.JobKey.Equals(trigger.JobKey))
{
ReportDuplicateTrigger(trigger);
}
await DoRescheduleJob(sched, trigger, dupeT, cancellationToken).ConfigureAwait(false);
}
else
{
if (Log.IsDebugEnabled())
{
Log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key);
}
try
{
await sched.ScheduleJob(trigger, cancellationToken).ConfigureAwait(false);
}
catch (ObjectAlreadyExistsException)
{
if (Log.IsDebugEnabled())
{
Log.Debug(
"Adding trigger: " + trigger.Key + " for job: " + trigger.JobKey +
" failed because the trigger already existed. " +
"This is likely due to a race condition between multiple instances " +
"in the cluster. Will try to reschedule instead.");
}
// Let's rescheduleJob one more time.
var oldTrigger = await sched.GetTrigger(trigger.Key, cancellationToken).ConfigureAwait(false);
await DoRescheduleJob(sched, trigger, oldTrigger, cancellationToken).ConfigureAwait(false);
}
}
}
}
private void ReportDuplicateTrigger(IMutableTrigger trigger)
{
Log.WarnFormat("Possibly duplicately named ({0}) trigger in configuration, this can be caused by not having a fixed job key for targeted jobs", trigger.Key);
}
private Task DoRescheduleJob(
IScheduler sched,
IMutableTrigger trigger,
ITrigger? oldTrigger,
CancellationToken cancellationToken = default)
{
// if this is a trigger with default start time we can consider relative scheduling
if (oldTrigger != null && trigger.StartTimeUtc - SystemTime.UtcNow() < TimeSpan.FromSeconds(5) && ScheduleTriggerRelativeToReplacedTrigger)
{
Log.DebugFormat("Using relative scheduling for trigger with key {0}", trigger.Key);
var oldTriggerPreviousFireTime = oldTrigger.GetPreviousFireTimeUtc();
trigger.StartTimeUtc = oldTrigger.StartTimeUtc;
((IOperableTrigger)trigger).SetPreviousFireTimeUtc(oldTriggerPreviousFireTime);
((IOperableTrigger)trigger).SetNextFireTimeUtc(trigger.GetFireTimeAfter(oldTriggerPreviousFireTime));
}
return sched.RescheduleJob(trigger.Key, trigger, cancellationToken);
}
protected virtual IDictionary<JobKey, List<IMutableTrigger>> BuildTriggersByFQJobNameMap(List<ITrigger> triggers)
{
Dictionary<JobKey, List<IMutableTrigger>> triggersByFQJobName = new Dictionary<JobKey, List<IMutableTrigger>>();
foreach (IMutableTrigger trigger in triggers)
{
if (!triggersByFQJobName.TryGetValue(trigger.JobKey, out var triggersOfJob))
{
triggersOfJob = new List<IMutableTrigger>();
triggersByFQJobName[trigger.JobKey] = triggersOfJob;
}
triggersOfJob.Add(trigger);
}
return triggersByFQJobName;
}
protected async Task ExecutePreProcessCommands(
IScheduler scheduler,
CancellationToken cancellationToken = default)
{
foreach (string group in jobGroupsToDelete)
{
if (group.Equals("*"))
{
Log.Info("Deleting all jobs in ALL groups.");
foreach (string groupName in await scheduler.GetJobGroupNames(cancellationToken).ConfigureAwait(false))
{
if (!jobGroupsToNeverDelete.Contains(groupName))
{
foreach (JobKey key in await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName), cancellationToken).ConfigureAwait(false))
{
await scheduler.DeleteJob(key, cancellationToken).ConfigureAwait(false);
}
}
}
}
else
{
if (!jobGroupsToNeverDelete.Contains(group))
{
Log.InfoFormat("Deleting all jobs in group: {0}", group);
foreach (JobKey key in await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(group), cancellationToken).ConfigureAwait(false))
{
await scheduler.DeleteJob(key, cancellationToken).ConfigureAwait(false);
}
}
}
}
foreach (string group in triggerGroupsToDelete)
{
if (group.Equals("*"))
{
Log.Info("Deleting all triggers in ALL groups.");
foreach (string groupName in await scheduler.GetTriggerGroupNames(cancellationToken).ConfigureAwait(false))
{
if (!triggerGroupsToNeverDelete.Contains(groupName))
{
foreach (TriggerKey key in await scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(groupName), cancellationToken).ConfigureAwait(false))
{
await scheduler.UnscheduleJob(key, cancellationToken).ConfigureAwait(false);
}
}
}
}
else
{
if (!triggerGroupsToNeverDelete.Contains(group))
{
Log.InfoFormat("Deleting all triggers in group: {0}", group);
foreach (TriggerKey key in await scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(group), cancellationToken).ConfigureAwait(false))
{
await scheduler.UnscheduleJob(key, cancellationToken).ConfigureAwait(false);
}
}
}
}
foreach (JobKey key in jobsToDelete)
{
if (!jobGroupsToNeverDelete.Contains(key.Group))
{
Log.InfoFormat("Deleting job: {0}", key);
await scheduler.DeleteJob(key, cancellationToken).ConfigureAwait(false);
}
}
foreach (TriggerKey key in triggersToDelete)
{
if (!triggerGroupsToNeverDelete.Contains(key.Group))
{
Log.InfoFormat("Deleting trigger: {0}", key);
await scheduler.UnscheduleJob(key, cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>
/// Adds a detected validation exception.
/// </summary>
/// <param name="e">The exception.</param>
protected virtual void AddValidationException(XmlException e)
{
validationExceptions.Add(e);
}
/// <summary>
/// Resets the number of detected validation exceptions.
/// </summary>
protected virtual void ClearValidationExceptions()
{
validationExceptions.Clear();
}
/// <summary>
/// Throws a ValidationException if the number of validationExceptions
/// detected is greater than zero.
/// </summary>
/// <exception cref="ValidationException">
/// DTD validation exception.
/// </exception>
protected virtual void MaybeThrowValidationException()
{
if (validationExceptions.Count > 0)
{
throw new ValidationException(validationExceptions);
}
}
public void AddJobGroupToNeverDelete(string jobGroupName)
{
jobGroupsToNeverDelete.Add(jobGroupName);
}
public void AddTriggerGroupToNeverDelete(string triggerGroupName)
{
triggerGroupsToNeverDelete.Add(triggerGroupName);
}
/// <summary>
/// Helper class to map constant names to their values.
/// </summary>
internal class Constants
{
private readonly Type[] types;
public Constants(params Type[] reflectedTypes)
{
types = reflectedTypes;
}
public int AsNumber(string field)
{
foreach (Type type in types)
{
FieldInfo? fi = type.GetField(field);
if (fi != null)
{
return Convert.ToInt32(fi.GetValue(null), CultureInfo.InvariantCulture);
}
}
// not found
throw new Exception($"Unknown field '{field}'");
}
}
}
}
| |
/*
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 java.lang;
using java.util;
using org.eclipse.jface.preference;
using org.eclipse.jface.util;
using org.eclipse.swt;
using org.eclipse.swt.graphics;
namespace cnatural.eclipse.editors {
public enum TextStyle {
Bold,
Italic,
Strikethrough,
Underline
}
public enum SemanticStyle {
Preprocessor(new RGB(20, 170, 240), null),
SkippedSource(new RGB(180, 180, 180), null),
SingleLineComment(new RGB(155, 155, 155), null),
DelimitedComment(new RGB(128, 128, 128), null),
Keyword(new RGB(75, 0, 150), null, TextStyle.Bold),
NumberLiteral(new RGB(208, 66, 0), null),
CharacterLiteral(new RGB(210, 105, 0), null),
StringLiteral(new RGB(210, 105, 0), null),
Label(new RGB(0, 0, 0), null, TextStyle.Bold),
Class(new RGB(0, 0, 255), null, TextStyle.Bold),
Interface(new RGB(128, 0, 128), null, TextStyle.Bold),
Enum(new RGB(128, 128, 255), null, TextStyle.Bold),
GenericParameter(new RGB(0, 128, 255), null, TextStyle.Bold),
ConstantField(new RGB(170, 55, 0), null),
StaticField(new RGB(75, 150, 150), null, TextStyle.Italic),
Field(new RGB(75, 150, 150), null),
MethodDeclaration(new RGB(100, 0, 200), null, TextStyle.Bold),
StaticMethod(new RGB(100, 0, 200), null, TextStyle.Italic),
Method(new RGB(100, 0, 200), null),
PropertyDeclaration(new RGB(50, 180, 100), null, TextStyle.Bold),
StaticProperty(new RGB(50, 180, 100), null, TextStyle.Italic),
Property(new RGB(50, 180, 100), null),
Parameter(new RGB(0, 128, 0), null),
Local(new RGB(128, 128, 0), null)
;
private static IPropertyChangeListener propertyChangeListener;
public static void installListener(IPreferenceStore store) {
foreach (var value in values()) {
var keyPrefix = value.PreferenceKeyPrefix;
var key = keyPrefix + "foreground";
if (store.contains(key) && !store.isDefault(key)) {
value.foreground = PreferenceConverter.getColor(store, key);
}
key = keyPrefix + "background";
if (store.contains(key) && !store.isDefault(key)) {
value.background = PreferenceConverter.getColor(store, key);
}
key = keyPrefix + "bold";
if (!store.isDefault(key)) {
updateTextStyle(value, TextStyle.Bold, store.getBoolean(key));
}
key = keyPrefix + "italic";
if (!store.isDefault(key)) {
updateTextStyle(value, TextStyle.Italic, store.getBoolean(key));
}
key = keyPrefix + "underline";
if (!store.isDefault(key)) {
updateTextStyle(value, TextStyle.Underline, store.getBoolean(key));
}
key = keyPrefix + "strikethrough";
if (!store.isDefault(key)) {
updateTextStyle(value, TextStyle.Strikethrough, store.getBoolean(key));
}
}
propertyChangeListener = p => {
foreach (var value in values()) {
if (p.getProperty().startsWith(value.PreferenceKeyPrefix)) {
switch (p.getProperty().substring(value.PreferenceKeyPrefix.length())) {
case "foreground":
value.foreground = (RGB)p.getNewValue();
break;
case "background":
value.background = (RGB)p.getNewValue();
break;
case "bold":
updateTextStyle(value, TextStyle.Bold, (Boolean)p.getNewValue());
break;
case "italic":
updateTextStyle(value, TextStyle.Italic, (Boolean)p.getNewValue());
break;
case "underline":
updateTextStyle(value, TextStyle.Underline, (Boolean)p.getNewValue());
break;
case "strikethrough":
updateTextStyle(value, TextStyle.Strikethrough, (Boolean)p.getNewValue());
break;
}
}
}
};
store.addPropertyChangeListener(propertyChangeListener);
}
public static void uninstallListener(IPreferenceStore store) {
if (propertyChangeListener != null) {
store.removePropertyChangeListener(propertyChangeListener);
propertyChangeListener = null;
}
}
static void updateTextStyle(SemanticStyle value, TextStyle textStyle, bool add) {
var ts = value.TextStyles;
if (add) {
ts.add(TextStyle.Bold);
} else {
ts.remove(TextStyle.Bold);
}
value.TextStyles = ts;
}
private RGB foreground;
private RGB background;
private EnumSet<TextStyle> defaultTextStyles;
private EnumSet<TextStyle> textStyles;
private SemanticStyle(RGB defaultForeground, RGB defaultBackground, params TextStyle[] textStyles) {
this.DefaultForeground = defaultForeground;
this.DefaultBackground = defaultBackground;
this.defaultTextStyles = EnumSet.noneOf(typeof(TextStyle));
foreach (var style in textStyles) {
this.defaultTextStyles.add(style);
}
this.textStyles = this.defaultTextStyles;
this.PreferenceKeyPrefix = getClass().getName() + "." + name() + ".";
}
public String PreferenceKeyPrefix^;
public RGB DefaultForeground^;
public RGB DefaultBackground^;
public RGB Foreground {
get {
return foreground ?? this.DefaultForeground;
}
set {
foreground = value;
}
}
public RGB Background {
get {
return background ?? this.DefaultBackground;
}
set {
background = value;
}
}
public EnumSet<TextStyle> DefaultTextStyles {
get {
return defaultTextStyles.clone();
}
}
public EnumSet<TextStyle> TextStyles {
get {
return textStyles.clone();
}
set {
textStyles = value.clone();
}
}
public int FontStyle {
get {
int result = SWT.NORMAL;
if (textStyles.contains(TextStyle.Bold)) {
result |= SWT.BOLD;
}
if (textStyles.contains(TextStyle.Italic)) {
result |= SWT.ITALIC;
}
return result;
}
}
public bool IsBold {
get {
return textStyles.contains(TextStyle.Bold);
}
}
public bool IsItalic {
get {
return textStyles.contains(TextStyle.Italic);
}
}
public bool Strikethrough {
get {
return textStyles.contains(TextStyle.Strikethrough);
}
}
public bool Underline {
get {
return textStyles.contains(TextStyle.Underline);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using GuiLabs.Canvas.DrawStyle;
using GuiLabs.Utils;
using System.Drawing;
using System.Diagnostics;
namespace GuiLabs.Canvas.DrawOperations
{
internal class GDIDrawOperations : AbstractDrawOperations, IDrawOperations
{
public GDIDrawOperations(IntPtr InitialDC)
{
hDC = InitialDC;
API.SetBkMode(hDC, 1);
}
private IntPtr hDC = IntPtr.Zero;
private API.POINT NULLPOINT;
#region Rectangle
public void DrawShadow(Rect theRect)
{
API.SetROP2(hDC, 9);
const int depth = 10;
const int depth2 = depth * 2;
const double gray = 0.85;
System.Drawing.Color white = System.Drawing.Color.White;
if (theRect.Width < depth2)
{
return;
}
Rect Rounding = new Rect();
for (int i = depth; i >= 0; i--)
{
System.Drawing.Color col = Colors.ScaleColor(System.Drawing.Color.White, (float)(gray + (1.0 - gray) * ((double)i / depth)));
Rounding.Size.Set(i * 2);
// upper right rounding
Rounding.Location.Set(theRect.Right - i + 1, theRect.Top + depth2 - i + 1);
API.SetROP2(hDC, 15);
DrawPie(Rounding, 0, 90, white, white);
API.SetROP2(hDC, 9);
DrawPie(Rounding, 0, 90, col, col);
// lower right rounding
Rounding.Location.Set(theRect.Right - i + 1, theRect.Bottom - i + 1);
API.SetROP2(hDC, 15);
DrawPie(Rounding, 270, 360, white, white);
API.SetROP2(hDC, 9);
DrawPie(Rounding, 270, 360, col, col);
// lower left rounding
//Rounding.Location.Set(theRect.Left + depth2 - i + 1, theRect.Bottom - i + 1);
//API.SetROP2(hDC, rop);
//rop = (rop + 1) % 16;
////DrawPie(Rounding, 180, 270, white, white);
//DrawPie(Rounding, 180, 270, col, col);
API.SetROP2(hDC, 9);
int y = theRect.Bottom + i;
GradientLine(
theRect.Left + depth + i,
y,
theRect.Left + depth2,
y,
white,
col,
1);
// horizontal
DrawLine(
theRect.Left + depth2,
y,
theRect.Right,
y,
col);
// vertical
DrawLine(
theRect.Right + i,
theRect.Top + depth2 + 1,
theRect.Right + i,
theRect.Bottom + 1,
col);
}
API.SetROP2(hDC, 13);
}
public void DrawFilledRectangle(Rect theRect, ILineStyleInfo Line, IFillStyleInfo Fill)
{
GDILineStyle LineStyle = (GDILineStyle)Line;
GDIFillStyle FillStyle = (GDIFillStyle)Fill;
if (FillStyle.Mode != GuiLabs.Canvas.DrawStyle.FillMode.Solid)
{
GradientFillRectangle(
theRect,
FillStyle.FillColor,
FillStyle.GradientColor,
FillStyle.Mode ==
GuiLabs.Canvas.DrawStyle.FillMode.HorizontalGradient
? System.Drawing.Drawing2D.LinearGradientMode.Horizontal
: LinearGradientMode.Vertical);
DrawRectangle(theRect, Line);
return;
}
IntPtr hPen = API.CreatePen(0, Line.Width, LineStyle.Win32ForeColor);
IntPtr hOldPen = API.SelectObject(hDC, hPen);
IntPtr hBrush = API.CreateSolidBrush(FillStyle.Win32FillColor);
IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Rectangle(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
API.SelectObject(hDC, hOldBrush);
API.DeleteObject(hBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
public void FillRectangle(Rect theRect, IFillStyleInfo theStyle)
{
if (theStyle.FillColor == System.Drawing.Color.Transparent)
{
return;
}
switch (theStyle.Mode)
{
case GuiLabs.Canvas.DrawStyle.FillMode.Solid:
FillRectangle(
theRect,
theStyle.FillColor);
break;
case GuiLabs.Canvas.DrawStyle.FillMode.HorizontalGradient:
GradientFillRectangle(
theRect,
theStyle.FillColor,
theStyle.GradientColor,
LinearGradientMode.Horizontal);
break;
case GuiLabs.Canvas.DrawStyle.FillMode.VerticalGradient:
GradientFillRectangle(
theRect,
theStyle.FillColor,
theStyle.GradientColor,
LinearGradientMode.Vertical);
break;
default:
break;
}
}
public void FillRectangle(Rect theRect, System.Drawing.Color fillColor)
{
if (fillColor != System.Drawing.Color.Transparent)
{
API.FillRectangle(hDC, fillColor, theRect.GetRectangle());
}
}
public void DrawRectangle(Rect theRect, System.Drawing.Color lineColor)
{
if (lineColor == System.Drawing.Color.Transparent)
{
return;
}
IntPtr hPen = API.CreatePen(API.PenStyle.PS_SOLID, 1, System.Drawing.ColorTranslator.ToWin32(lineColor));
IntPtr hOldPen = API.SelectObject(hDC, hPen);
IntPtr hBrush = API.GetStockObject(5); // NULL_BRUSH
IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Rectangle(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
API.SelectObject(hDC, hOldBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
public void DrawDotRectangle(Rect theRect, System.Drawing.Color lineColor)
{
if (lineColor == System.Drawing.Color.Transparent)
{
return;
}
IntPtr hPen = API.CreatePen(API.PenStyle.PS_DOT, 1, System.Drawing.ColorTranslator.ToWin32(lineColor));
IntPtr hOldPen = API.SelectObject(hDC, hPen);
IntPtr hBrush = API.GetStockObject(5); // NULL_BRUSH
IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Rectangle(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
API.SelectObject(hDC, hOldBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
public void DrawRectangle(Rect theRect, System.Drawing.Color lineColor, int lineWidth)
{
if (lineColor == System.Drawing.Color.Transparent)
{
return;
}
SetPenBrush(lineColor, lineWidth, System.Drawing.Color.Transparent);
//IntPtr hPen = API.CreatePen(API.PenStyle.PS_SOLID, lineWidth, ColorTranslator.ToWin32(lineColor));
//IntPtr hOldPen = API.SelectObject(hDC, hPen);
//IntPtr hBrush = API.GetStockObject(5); // NULL_BRUSH
//IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Rectangle(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
ResetPenBrush();
//API.SelectObject(hDC, hOldBrush);
//API.SelectObject(hDC, hOldPen);
//API.DeleteObject(hPen);
}
public void DrawRectangle(Rect theRect, ILineStyleInfo theStyle)
{
if (theStyle.ForeColor == System.Drawing.Color.Transparent)
{
return;
}
GDILineStyle Style = (GDILineStyle)theStyle;
IntPtr hPen = API.CreatePen(0, theStyle.Width, Style.Win32ForeColor);
IntPtr hOldPen = API.SelectObject(hDC, hPen);
IntPtr hBrush = API.GetStockObject(5); // NULL_BRUSH
IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Rectangle(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
API.SelectObject(hDC, hOldBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
// int hPen = API.CreatePen(0, theStyle.Width, theStyle.Win32ForeColor);
// int hOldPen = API.SelectObject(hDC, hPen);
//
// int left = theRect.Location.X;
// int top = theRect.Location.Y;
// int right = theRect.Right;
// int bottom = theRect.Bottom;
//
// API.MoveToEx(hDC, left, top, ref NULLPOINTAPI);
// API.LineTo(hDC, right, top);
// API.LineTo(hDC, right, bottom);
// API.LineTo(hDC, left, bottom);
// API.LineTo(hDC, left, top);
//
// API.SelectObject(hDC, hOldPen);
// API.DeleteObject(hPen);
}
#endregion
#region Ellipse
public void DrawEllipse(Rect theRect, ILineStyleInfo theStyle)
{
GDILineStyle Style = theStyle as GDILineStyle;
if (Style == null)
{
Log.Instance.WriteWarning("DrawEllipse: Style == null");
return;
}
IntPtr hPen = API.CreatePen(0, theStyle.Width, Style.Win32ForeColor);
IntPtr hOldPen = API.SelectObject(hDC, hPen);
IntPtr hBrush = API.GetStockObject(5); // NULL_BRUSH
IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Ellipse(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
API.SelectObject(hDC, hOldBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
public void DrawFilledEllipse(Rect theRect, ILineStyleInfo Line, IFillStyleInfo Fill)
{
GDILineStyle LineStyle = (GDILineStyle)Line;
GDIFillStyle FillStyle = (GDIFillStyle)Fill;
IntPtr hPen = API.CreatePen(0, Line.Width, LineStyle.Win32ForeColor);
IntPtr hOldPen = API.SelectObject(hDC, hPen);
IntPtr hBrush = API.CreateSolidBrush(FillStyle.Win32FillColor);
IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Ellipse(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
API.SelectObject(hDC, hOldBrush);
API.DeleteObject(hBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
public void DrawPie(
Rect theRect,
double startAngleDegrees,
double endAngleDegrees,
System.Drawing.Color borderColor,
System.Drawing.Color fillColor)
{
SetPenBrush(borderColor, 1, fillColor);
API.Pie(
hDC,
theRect.Location.X,
theRect.Location.Y,
theRect.Right,
theRect.Bottom,
constructRadialX(theRect.CenterX, theRect.HalfSizeX, startAngleDegrees),
constructRadialY(theRect.CenterY, theRect.HalfSizeY, startAngleDegrees),
constructRadialX(theRect.CenterX, theRect.HalfSizeX, endAngleDegrees),
constructRadialY(theRect.CenterY, theRect.HalfSizeY, endAngleDegrees));
ResetPenBrush();
}
#endregion
private int constructRadialX(int center, int xRadius, double angleDegrees)
{
return (int)(center + (double)xRadius * Math.Cos(ToRadians(angleDegrees)));
}
private int constructRadialY(int center, int yRadius, double angleDegrees)
{
return (int)(center - (double)yRadius * Math.Sin(ToRadians(angleDegrees)));
}
public const double PI = 3.141592653589793238462643383;
public double ToRadians(double degrees)
{
return degrees * PI / 180;
}
#region Gradients
public void GradientFillRectangle(Rect theRect, System.Drawing.Color Color1, System.Drawing.Color Color2, LinearGradientMode GradientType)
{
int ColorR1 = Color1.R;
int ColorG1 = Color1.G;
int ColorB1 = Color1.B;
int ColorR2 = Color2.R - ColorR1;
int ColorG2 = Color2.G - ColorG1;
int ColorB2 = Color2.B - ColorB1;
int Width = theRect.Size.X;
int Height = theRect.Size.Y;
int x0 = theRect.Location.X;
int y0 = theRect.Location.Y;
int x1 = theRect.Right;
int y1 = theRect.Bottom;
if (Width <= 0 || Height <= 0)
return;
double Coeff;
int StepSize;
API.RECT R = new API.RECT();
int NumberOfSteps = 128; // number of steps
if (GradientType == System.Drawing.Drawing2D.LinearGradientMode.Horizontal)
{
double InvWidth = 1.0 / Width;
StepSize = Width / NumberOfSteps;
if (StepSize < 1)
StepSize = 1;
R.Top = y0;
R.Bottom = y1;
for (int i = x0; i <= x1; i += StepSize)
{
R.Left = i;
R.Right = i + StepSize;
if (R.Right > x1)
{
R.Right = x1;
}
Coeff = (i - x0) * InvWidth;
IntPtr hBrush = API.CreateSolidBrush((int)
(int)(ColorR1 + (double)ColorR2 * Coeff) |
(int)(ColorG1 + (double)ColorG2 * Coeff) << 8 |
(int)(ColorB1 + (double)ColorB2 * Coeff) << 16
);
API.FillRect(hDC, ref R, hBrush);
API.DeleteObject(hBrush);
}
}
else
{
double InvHeight = 1.0 / Height;
StepSize = Height / NumberOfSteps;
if (StepSize < 1)
StepSize = 1;
R.Left = x0;
R.Right = x1;
for (int i = y0; i <= y1; i += StepSize)
{
R.Top = i;
R.Bottom = i + StepSize;
if (R.Bottom > y1)
{
R.Bottom = y1;
}
Coeff = (i - y0) * InvHeight;
IntPtr hBrush = API.CreateSolidBrush(
(int)(ColorR1 + (double)ColorR2 * Coeff) |
(int)(ColorG1 + (double)ColorG2 * Coeff) << 8 |
(int)(ColorB1 + (double)ColorB2 * Coeff) << 16
);
API.FillRect(hDC, ref R, hBrush);
API.DeleteObject(hBrush);
}
}
}
public void GradientFill4(
Rect rect,
Color leftTop,
Color rightTop,
Color leftBottom,
Color rightBottom)
{
GradientFill4(rect, leftTop, rightTop, leftBottom, rightBottom, 128);
}
public void GradientFill4(
Rect rect,
Color leftTop,
Color rightTop,
Color leftBottom,
Color rightBottom,
int steps)
{
//long startTime = Stopwatch.GetTimestamp();
GuiLabs.Utils.API.RECT r = new API.RECT();
Color upper, lower, final;
final = Color.WhiteSmoke;
for (int i = 0; i < steps; i++)
{
float xratio = (float)i / steps;
r.Left = (int)(rect.Left + rect.Width * xratio);
r.Right = (int)(rect.Left + rect.Width * (float)(i + 1) / steps);
for (int j = 0; j < steps; j++)
{
float yratio = (float)j / steps;
r.Top = (int)(rect.Top + rect.Height * yratio);
r.Bottom = (int)(rect.Top + rect.Height * (float)(j + 1) / steps);
upper = Colors.Interpolate(leftTop, rightTop, xratio);
lower = Colors.Interpolate(leftBottom, rightBottom, xratio);
final = Colors.Interpolate(upper, lower, yratio);
API.FillRectangle(hDC, final, r);
}
}
//long stopTime = Stopwatch.GetTimestamp();
//DrawString(
// ((stopTime - startTime) / (double)Stopwatch.Frequency).ToString(),
// rect);
}
#endregion
public override void DrawLine(int x1, int y1, int x2, int y2, System.Drawing.Color lineColor, int lineWidth)
{
if (lineColor == System.Drawing.Color.Transparent)
{
return;
}
IntPtr hPen = API.CreatePen(API.PenStyle.PS_SOLID, lineWidth, System.Drawing.ColorTranslator.ToWin32(lineColor));
IntPtr hOldPen = API.SelectObject(hDC, hPen);
API.MoveToEx(hDC, x1, y1, ref NULLPOINT);
API.LineTo(hDC, x2, y2);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
public void FillPolygon(IList<Point> Points, ILineStyleInfo LineStyle, IFillStyleInfo FillStyle)
{
GDILineStyle Line = (GDILineStyle)LineStyle;
GDIFillStyle Fill = (GDIFillStyle)FillStyle;
API.POINT[] P = new API.POINT[Points.Count];
for (int i = 0; i < Points.Count; i++)
{
P[i].x = Points[i].X;
P[i].y = Points[i].Y;
}
SetPenBrush(Line.ForeColor, Line.Width, Fill.FillColor);
//IntPtr hPen = API.CreatePen(0, Line.Width, Line.Win32ForeColor);
//IntPtr hOldPen = API.SelectObject(hDC, hPen);
//IntPtr hBrush = API.CreateSolidBrush(Fill.Win32FillColor);
//IntPtr hOldBrush = API.SelectObject(hDC, hBrush);
API.Polygon(hDC, P, Points.Count);
ResetPenBrush();
//API.SelectObject(hDC, hOldBrush);
//API.DeleteObject(hBrush);
//API.SelectObject(hDC, hOldPen);
//API.DeleteObject(hPen);
}
private API.POINT[] trianglePoints = new API.POINT[3];
public void DrawTriangle(
int x1,
int y1,
int x2,
int y2,
int x3,
int y3,
System.Drawing.Color borderColor,
System.Drawing.Color fillColor)
{
trianglePoints[0].x = x1;
trianglePoints[0].y = y1;
trianglePoints[1].x = x2;
trianglePoints[1].y = y2;
trianglePoints[2].x = x3;
trianglePoints[2].y = y3;
SetPenBrush(borderColor, 1, fillColor);
API.Polygon(hDC, trianglePoints, 3);
ResetPenBrush();
}
#region Pen Brush
private void SetPenBrush(
System.Drawing.Color penColor,
int lineWidth,
System.Drawing.Color brushColor)
{
#region Pen
if (penColor != System.Drawing.Color.Transparent)
{
hPen = API.CreatePen(API.PenStyle.PS_SOLID, lineWidth, System.Drawing.ColorTranslator.ToWin32(penColor));
}
else
{
hPen = API.CreatePen(API.PenStyle.PS_NULL, 1, 0);
}
hOldPen = API.SelectObject(hDC, hPen);
#endregion
#region Brush
if (brushColor != System.Drawing.Color.Transparent)
{
hBrush = API.CreateSolidBrush(System.Drawing.ColorTranslator.ToWin32(brushColor));
}
else
{
hBrush = API.GetStockObject(API.NULL_BRUSH);
}
hOldBrush = API.SelectObject(hDC, hBrush);
#endregion
}
private IntPtr hPen;
private IntPtr hOldPen;
private IntPtr hBrush;
private IntPtr hOldBrush;
private void ResetPenBrush()
{
API.SelectObject(hDC, hOldBrush);
API.DeleteObject(hBrush);
API.SelectObject(hDC, hOldPen);
API.DeleteObject(hPen);
}
#endregion
#region Factory
private IDrawInfoFactory mFactory = new GDIDrawInfoFactory();
public IDrawInfoFactory Factory
{
get
{
return mFactory;
}
set
{
mFactory = value;
}
}
#endregion
#region DrawString
private int CurrentTextColor = 0;
public void DrawString(string Text, Rect theRect, IFontStyleInfo theFont)
{
GDIFontStyle FontStyle = (GDIFontStyle)theFont;
if (CurrentTextColor != FontStyle.Win32ForeColor)
{
CurrentTextColor = FontStyle.Win32ForeColor;
API.SetTextColor(hDC, FontStyle.Win32ForeColor);
}
IntPtr hOldFont = API.SelectObject(hDC, ((GDIFont)FontStyle.Font).hFont);
API.RECT r = new API.RECT();
r.Left = theRect.Location.X;
r.Top = theRect.Location.Y;
r.Right = theRect.Right;
r.Bottom = theRect.Bottom;
// API.DrawText(hDC, Text, Text.Length, ref r, 2368);
API.ExtTextOut(hDC, r.Left, r.Top, 4, ref r, Text, (uint)Text.Length, null);
API.SelectObject(hDC, hOldFont);
// No need to Delete hFont because we're going to reuse it
// it is being saved in GDIFontStyle FontStyle
// API.DeleteObject(hFont);
// No need to restore old text color
// because we're setting it new each time anyway
// API.SetTextColor(hDC, hOldColor);
}
public void DrawString(string text, Rect rect)
{
GuiLabs.Utils.API.RECT R = rect.ToRECT();
API.ExtTextOut(
hDC,
rect.Left,
rect.Top,
4,
ref R,
text,
(uint)text.Length,
null);
}
private Point stringPos = new Point();
private Point stringSize = new Point();
private Rect stringRect = new Rect();
public void DrawStringWithSelection
(
Rect Block,
int StartSelPos,
int CaretPosition,
string Text,
IFontStyleInfo FontStyle
)
{
// API.SetROP2(hDC, 14);
// API.Rectangle(hDC, theRect.Location.X, theRect.Location.Y, theRect.Right, theRect.Bottom);
// FillRectangle(theRect, selectionFillStyle);
DrawString(Text, Block, FontStyle);
if (StartSelPos == CaretPosition) return;
int SelStart, SelEnd;
if (CaretPosition > StartSelPos)
{
SelStart = StartSelPos;
SelEnd = CaretPosition;
}
else
{
SelStart = CaretPosition;
SelEnd = StartSelPos;
}
if (SelStart < 0)
{
SelStart = 0;
}
if (SelEnd > Text.Length)
{
SelEnd = Text.Length;
}
// Added the if-statement to check if the selection borders
// are within the textlength
string select = "";
if ((SelStart < Text.Length) && (SelEnd <= Text.Length))
select = Text.Substring(SelStart, SelEnd - SelStart);
stringSize.Set(StringSize(Text.Substring(0, SelStart), FontStyle.Font));
stringPos.Set(Block.Location.X + stringSize.X, Block.Location.Y);
stringRect.Set(stringPos, StringSize(select, FontStyle.Font));
FillRectangle(stringRect, System.Drawing.SystemColors.Highlight);
System.Drawing.Color OldColor = FontStyle.ForeColor;
FontStyle.ForeColor = System.Drawing.SystemColors.HighlightText;
DrawString(select, stringRect, FontStyle);
FontStyle.ForeColor = OldColor;
}
public Point StringSize(string Text, IFontInfo theFont)
{
IntPtr hOldFont = API.SelectObject(hDC, ((GDIFont)theFont).hFont);
API.SIZE theSize = new API.SIZE();
API.GetTextExtentPoint32(hDC, Text, Text.Length, out theSize);
Point result = new Point(theSize.x, theSize.y);
API.SelectObject(hDC, hOldFont);
return result;
}
#endregion
#region DrawImage
public void DrawImage(IPicture picture, Point p)
{
Picture pict = picture as Picture;
if (pict == null)
{
return;
}
if (pict.Transparent)
{
DrawImageTransparent(pict, p);
return;
}
IntPtr hPictureDC = API.CreateCompatibleDC(hDC);
IntPtr hOldBitmap = API.SelectObject(hPictureDC, pict.hBitmap);
API.BitBlt(
hDC,
p.X,
p.Y,
picture.Size.X,
picture.Size.Y,
hPictureDC,
0,
0,
API.SRCCOPY);
API.SelectObject(hPictureDC, hOldBitmap);
API.DeleteDC(hPictureDC);
}
private void DrawImageTransparent(Picture pict, Point p)
{
IntPtr hPictureDC = API.CreateCompatibleDC(hDC);
IntPtr hOldBitmap = API.SelectObject(hPictureDC, pict.hBitmap);
API.TransparentBlt(
hDC,
p.X,
p.Y,
pict.Size.X,
pict.Size.Y,
hPictureDC,
0,
0,
pict.Size.X,
pict.Size.Y,
pict.Win32TransparentColor
);
API.SelectObject(hPictureDC, hOldBitmap);
API.DeleteDC(hPictureDC);
}
#endregion
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Crypto.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count).
* see: http://www.burtleburtle.net/bob/rand/isaacafa.html
*/
public class IsaacEngine
: IStreamCipher
{
// Constants
private static readonly int sizeL = 8,
stateArraySize = sizeL<<5; // 256
// Cipher's internal state
private uint[] engineState = null, // mm
results = null; // randrsl
private uint a = 0, b = 0, c = 0;
// Engine state
private int index = 0;
private byte[] keyStream = new byte[stateArraySize<<2], // results expanded into bytes
workingKey = null;
private bool initialised = false;
/**
* initialise an ISAAC cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param params the parameters required to set up the cipher.
* @exception ArgumentException if the params argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException(
"invalid parameter passed to ISAAC Init - " + parameters.GetType().Name,
"parameters");
/*
* ISAAC encryption and decryption is completely
* symmetrical, so the 'forEncryption' is
* irrelevant.
*/
KeyParameter p = (KeyParameter) parameters;
setKey(p.GetKey());
}
public byte ReturnByte(
byte input)
{
if (index == 0)
{
isaac();
keyStream = Pack.UInt32_To_BE(results);
}
byte output = (byte)(keyStream[index]^input);
index = (index + 1) & 1023;
return output;
}
public void ProcessBytes(
byte[] input,
int inOff,
int len,
byte[] output,
int outOff)
{
if (!initialised)
throw new InvalidOperationException(AlgorithmName + " not initialised");
if ((inOff + len) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + len) > output.Length)
throw new DataLengthException("output buffer too short");
for (int i = 0; i < len; i++)
{
if (index == 0)
{
isaac();
keyStream = Pack.UInt32_To_BE(results);
}
output[i+outOff] = (byte)(keyStream[index]^input[i+inOff]);
index = (index + 1) & 1023;
}
}
public string AlgorithmName
{
get { return "ISAAC"; }
}
public void Reset()
{
setKey(workingKey);
}
// Private implementation
private void setKey(
byte[] keyBytes)
{
workingKey = keyBytes;
if (engineState == null)
{
engineState = new uint[stateArraySize];
}
if (results == null)
{
results = new uint[stateArraySize];
}
int i, j, k;
// Reset state
for (i = 0; i < stateArraySize; i++)
{
engineState[i] = results[i] = 0;
}
a = b = c = 0;
// Reset index counter for output
index = 0;
// Convert the key bytes to ints and put them into results[] for initialization
byte[] t = new byte[keyBytes.Length + (keyBytes.Length & 3)];
Array.Copy(keyBytes, 0, t, 0, keyBytes.Length);
for (i = 0; i < t.Length; i+=4)
{
results[i >> 2] = Pack.LE_To_UInt32(t, i);
}
// It has begun?
uint[] abcdefgh = new uint[sizeL];
for (i = 0; i < sizeL; i++)
{
abcdefgh[i] = 0x9e3779b9; // Phi (golden ratio)
}
for (i = 0; i < 4; i++)
{
mix(abcdefgh);
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < stateArraySize; j+=sizeL)
{
for (k = 0; k < sizeL; k++)
{
abcdefgh[k] += (i<1) ? results[j+k] : engineState[j+k];
}
mix(abcdefgh);
for (k = 0; k < sizeL; k++)
{
engineState[j+k] = abcdefgh[k];
}
}
}
isaac();
initialised = true;
}
private void isaac()
{
uint x, y;
b += ++c;
for (int i = 0; i < stateArraySize; i++)
{
x = engineState[i];
switch (i & 3)
{
case 0: a ^= (a << 13); break;
case 1: a ^= (a >> 6); break;
case 2: a ^= (a << 2); break;
case 3: a ^= (a >> 16); break;
}
a += engineState[(i+128) & 0xFF];
engineState[i] = y = engineState[(int)((uint)x >> 2) & 0xFF] + a + b;
results[i] = b = engineState[(int)((uint)y >> 10) & 0xFF] + x;
}
}
private void mix(uint[] x)
{
x[0]^=x[1]<< 11; x[3]+=x[0]; x[1]+=x[2];
x[1]^=x[2]>> 2; x[4]+=x[1]; x[2]+=x[3];
x[2]^=x[3]<< 8; x[5]+=x[2]; x[3]+=x[4];
x[3]^=x[4]>> 16; x[6]+=x[3]; x[4]+=x[5];
x[4]^=x[5]<< 10; x[7]+=x[4]; x[5]+=x[6];
x[5]^=x[6]>> 4; x[0]+=x[5]; x[6]+=x[7];
x[6]^=x[7]<< 8; x[1]+=x[6]; x[7]+=x[0];
x[7]^=x[0]>> 9; x[2]+=x[7]; x[0]+=x[1];
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Threading.Tasks;
using Windows.Devices.PointOfService;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario2_CloseDrawer : Page
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;
CashDrawer drawer = null;
ClaimedCashDrawer claimedDrawer = null;
public Scenario2_CloseDrawer()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ResetScenarioState();
base.OnNavigatedTo(e);
}
/// <summary>
/// Invoked before the page is unloaded and is no longer the current source of a Frame.
/// </summary>
/// <param name="e">Event data describing the navigation that was requested.</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ResetScenarioState();
base.OnNavigatedFrom(e);
}
/// <summary>
/// Event handler for Initialize Drawer button.
/// Claims and enables the default cash drawer.
/// </summary>
/// <param name="sender">Button that was clicked.</param>
/// <param name="e">Event data associated with click event.</param>
private async void InitDrawerButton_Click(object sender, RoutedEventArgs e)
{
if (await CreateDefaultCashDrawerObject())
{
if (await ClaimCashDrawer())
{
if (await EnableCashDrawer())
{
drawer.StatusUpdated += drawer_StatusUpdated;
InitDrawerButton.IsEnabled = false;
DrawerWaitButton.IsEnabled = true;
UpdateStatusOutput(drawer.Status.StatusKind);
rootPage.NotifyUser("Successfully enabled cash drawer. Device ID: " + claimedDrawer.DeviceId, NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Failed to enable cash drawer.", NotifyType.ErrorMessage);
}
}
else
{
rootPage.NotifyUser("Failed to claim cash drawer.", NotifyType.ErrorMessage);
}
}
else
{
rootPage.NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType.ErrorMessage);
}
}
/// <summary>
/// Set up an alarm and wait for the drawer to close.
/// </summary>
/// <param name="sender">Button that was clicked.</param>
/// <param name="e">Event data associated with click event.</param>
private async void WaitForDrawerCloseButton_Click(object sender, RoutedEventArgs e)
{
if (claimedDrawer == null)
{
rootPage.NotifyUser("Drawer must be initialized.", NotifyType.ErrorMessage);
return;
}
var alarm = claimedDrawer.CloseAlarm;
if (alarm == null)
{
rootPage.NotifyUser("Failed to create drawer alarm.", NotifyType.ErrorMessage);
return;
}
// TimeSpan specifies a time period as (hours, minutes, seconds)
alarm.AlarmTimeout = new TimeSpan(0, 0, 30);
alarm.BeepDelay = new TimeSpan(0, 0, 3);
alarm.BeepDuration = new TimeSpan(0, 0, 1);
alarm.BeepFrequency = 700;
alarm.AlarmTimeoutExpired += drawer_AlarmExpired;
rootPage.NotifyUser("Waiting for drawer to close.", NotifyType.StatusMessage);
if (await alarm.StartAsync())
rootPage.NotifyUser("Successfully waited for drawer close.", NotifyType.StatusMessage);
else
rootPage.NotifyUser("Failed to wait for drawer close.", NotifyType.ErrorMessage);
}
/// <summary>
/// Creates the default cash drawer.
/// </summary>
/// <returns>True if the cash drawer was created, false otherwise.</returns>
private async Task<bool> CreateDefaultCashDrawerObject()
{
rootPage.NotifyUser("Creating cash drawer object.", NotifyType.StatusMessage);
if (drawer == null)
{
drawer = await DeviceHelpers.GetFirstCashDrawerAsync();
if (drawer == null)
return false;
}
return true;
}
/// <summary>
/// Attempt to claim the connected cash drawer.
/// </summary>
/// <returns>True if the cash drawer was successfully claimed, false otherwise.</returns>
private async Task<bool> ClaimCashDrawer()
{
if (drawer == null)
return false;
if (claimedDrawer == null)
{
claimedDrawer = await drawer.ClaimDrawerAsync();
if (claimedDrawer == null)
return false;
}
return true;
}
/// <summary>
/// Attempt to enabled the claimed cash drawer.
/// </summary>
/// <returns>True if the cash drawer was successfully enabled, false otherwise.</returns>
private async Task<bool> EnableCashDrawer()
{
if (claimedDrawer == null)
return false;
if (claimedDrawer.IsEnabled)
return true;
return await claimedDrawer.EnableAsync();
}
/// <summary>
/// Event callback for device status updates.
/// </summary>
/// <param name="drawer">CashDrawer object sending the status update event.</param>
/// <param name="e">Event data associated with the status update.</param>
private async void drawer_StatusUpdated(CashDrawer drawer, CashDrawerStatusUpdatedEventArgs e)
{
await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
UpdateStatusOutput(e.Status.StatusKind);
rootPage.NotifyUser("Status updated event: " + e.Status.StatusKind.ToString(), NotifyType.StatusMessage);
});
}
/// <summary>
/// Event callback for the alarm expiring.
/// </summary>
/// <param name="alarm">CashDrawerCloseAlarm that has expired.</param>
/// <param name="sender">Unused by AlarmTimeoutExpired events.</param>
private async void drawer_AlarmExpired(CashDrawerCloseAlarm alarm, object sender)
{
await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Alarm expired. Still waiting for drawer to be closed.", NotifyType.StatusMessage);
});
}
/// <summary>
/// Reset the scenario to its initial state.
/// </summary>
private void ResetScenarioState()
{
if (claimedDrawer != null)
{
claimedDrawer.Dispose();
claimedDrawer = null;
}
if (drawer != null)
{
drawer.Dispose();
drawer = null;
}
UpdateStatusOutput(CashDrawerStatusKind.Offline);
InitDrawerButton.IsEnabled = true;
DrawerWaitButton.IsEnabled = false;
rootPage.NotifyUser("Click the init drawer button to begin.", NotifyType.StatusMessage);
}
/// <summary>
/// Update the cash drawer text block.
/// </summary>
/// <param name="status">Cash drawer status to be displayed.</param>
private void UpdateStatusOutput(CashDrawerStatusKind status)
{
DrawerStatusBlock.Text = status.ToString();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using pCampBot.Interfaces;
namespace pCampBot
{
public enum BotManagerBotConnectingState
{
Initializing,
Ready,
Connecting,
Disconnecting
}
/// <summary>
/// Thread/Bot manager for the application
/// </summary>
public class BotManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int DefaultLoginDelay = 5000;
/// <summary>
/// Is pCampbot ready to connect or currently in the process of connecting or disconnecting bots?
/// </summary>
public BotManagerBotConnectingState BotConnectingState { get; private set; }
/// <summary>
/// Used to control locking as we can't lock an enum.
/// </summary>
private object BotConnectingStateChangeObject = new object();
/// <summary>
/// Delay between logins of multiple bots.
/// </summary>
/// <remarks>TODO: This value needs to be configurable by a command line argument.</remarks>
public int LoginDelay { get; set; }
/// <summary>
/// Command console
/// </summary>
protected CommandConsole m_console;
/// <summary>
/// Controls whether bots start out sending agent updates on connection.
/// </summary>
public bool InitBotSendAgentUpdates { get; set; }
/// <summary>
/// Controls whether bots request textures for the object information they receive
/// </summary>
public bool InitBotRequestObjectTextures { get; set; }
/// <summary>
/// Created bots, whether active or inactive.
/// </summary>
protected List<Bot> m_bots;
/// <summary>
/// Random number generator.
/// </summary>
public Random Rng { get; private set; }
/// <summary>
/// Track the assets we have and have not received so we don't endlessly repeat requests.
/// </summary>
public Dictionary<UUID, bool> AssetsReceived { get; private set; }
/// <summary>
/// The regions that we know about.
/// </summary>
public Dictionary<ulong, GridRegion> RegionsKnown { get; private set; }
/// <summary>
/// First name for bots
/// </summary>
private string m_firstName;
/// <summary>
/// Last name stem for bots
/// </summary>
private string m_lastNameStem;
/// <summary>
/// Password for bots
/// </summary>
private string m_password;
/// <summary>
/// Login URI for bots.
/// </summary>
private string m_loginUri;
/// <summary>
/// Start location for bots.
/// </summary>
private string m_startUri;
/// <summary>
/// Postfix bot number at which bot sequence starts.
/// </summary>
private int m_fromBotNumber;
/// <summary>
/// Wear setting for bots.
/// </summary>
private string m_wearSetting;
/// <summary>
/// Behaviour switches for bots.
/// </summary>
private HashSet<string> m_defaultBehaviourSwitches = new HashSet<string>();
/// <summary>
/// Collects general information on this server (which reveals this to be a misnamed class).
/// </summary>
private ServerStatsCollector m_serverStatsCollector;
/// <summary>
/// Constructor Creates MainConsole.Instance to take commands and provide the place to write data
/// </summary>
public BotManager()
{
// We set this to avoid issues with bots running out of HTTP connections if many are run from a single machine
// to multiple regions.
Settings.MAX_HTTP_CONNECTIONS = int.MaxValue;
// System.Threading.ThreadPool.SetMaxThreads(600, 240);
//
// int workerThreads, iocpThreads;
// System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);
// Console.WriteLine("ThreadPool.GetMaxThreads {0} {1}", workerThreads, iocpThreads);
InitBotSendAgentUpdates = true;
InitBotRequestObjectTextures = true;
LoginDelay = DefaultLoginDelay;
Rng = new Random(Environment.TickCount);
AssetsReceived = new Dictionary<UUID, bool>();
RegionsKnown = new Dictionary<ulong, GridRegion>();
m_console = CreateConsole();
MainConsole.Instance = m_console;
// Make log4net see the console
//
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
OpenSimAppender consoleAppender = null;
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
consoleAppender = (OpenSimAppender)appender;
consoleAppender.Console = m_console;
break;
}
}
m_console.Commands.AddCommand(
"Bots", false, "shutdown", "shutdown", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"Bots", false, "quit", "quit", "Shutdown bots and exit", HandleShutdown);
m_console.Commands.AddCommand(
"Bots", false, "connect", "connect [<n>]", "Connect bots",
"If an <n> is given, then the first <n> disconnected bots by postfix number are connected.\n"
+ "If no <n> is given, then all currently disconnected bots are connected.",
HandleConnect);
m_console.Commands.AddCommand(
"Bots", false, "disconnect", "disconnect [<n>]", "Disconnect bots",
"Disconnecting bots will interupt any bot connection process, including connection on startup.\n"
+ "If an <n> is given, then the last <n> connected bots by postfix number are disconnected.\n"
+ "If no <n> is given, then all currently connected bots are disconnected.",
HandleDisconnect);
m_console.Commands.AddCommand(
"Bots", false, "add behaviour", "add behaviour <abbreviated-name> [<bot-number>]",
"Add a behaviour to a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleAddBehaviour);
m_console.Commands.AddCommand(
"Bots", false, "remove behaviour", "remove behaviour <abbreviated-name> [<bot-number>]",
"Remove a behaviour from a bot",
"If no bot number is specified then behaviour is added to all bots.\n"
+ "Can be performed on connected or disconnected bots.",
HandleRemoveBehaviour);
m_console.Commands.AddCommand(
"Bots", false, "sit", "sit", "Sit all bots on the ground.",
HandleSit);
m_console.Commands.AddCommand(
"Bots", false, "stand", "stand", "Stand all bots.",
HandleStand);
m_console.Commands.AddCommand(
"Bots", false, "set bots", "set bots <key> <value>", "Set a setting for all bots.", HandleSetBots);
m_console.Commands.AddCommand(
"Bots", false, "show regions", "show regions", "Show regions known to bots", HandleShowRegions);
m_console.Commands.AddCommand(
"Bots", false, "show bots", "show bots", "Shows the status of all bots.", HandleShowBotsStatus);
m_console.Commands.AddCommand(
"Bots", false, "show bot", "show bot <bot-number>",
"Shows the detailed status and settings of a particular bot.", HandleShowBotStatus);
m_console.Commands.AddCommand(
"Debug",
false,
"debug lludp packet",
"debug lludp packet <level> <avatar-first-name> <avatar-last-name>",
"Turn on received packet logging.",
"If level > 0 then all received packets that are not duplicates are logged.\n"
+ "If level <= 0 then no received packets are logged.",
HandleDebugLludpPacketCommand);
m_console.Commands.AddCommand(
"Bots", false, "show status", "show status", "Shows pCampbot status.", HandleShowStatus);
m_bots = new List<Bot>();
Watchdog.Enabled = true;
StatsManager.RegisterConsoleCommands(m_console);
m_serverStatsCollector = new ServerStatsCollector();
m_serverStatsCollector.Initialise(null);
m_serverStatsCollector.Enabled = true;
m_serverStatsCollector.Start();
BotConnectingState = BotManagerBotConnectingState.Ready;
}
/// <summary>
/// Startup number of bots specified in the starting arguments
/// </summary>
/// <param name="botcount">How many bots to start up</param>
/// <param name="cs">The configuration for the bots to use</param>
public void CreateBots(int botcount, IConfig startupConfig)
{
m_firstName = startupConfig.GetString("firstname");
m_lastNameStem = startupConfig.GetString("lastname");
m_password = startupConfig.GetString("password");
m_loginUri = startupConfig.GetString("loginuri");
m_fromBotNumber = startupConfig.GetInt("from", 0);
m_wearSetting = startupConfig.GetString("wear", "no");
m_startUri = ParseInputStartLocationToUri(startupConfig.GetString("start", "last"));
Array.ForEach<string>(
startupConfig.GetString("behaviours", "p").Split(new char[] { ',' }), b => m_defaultBehaviourSwitches.Add(b));
for (int i = 0; i < botcount; i++)
{
lock (m_bots)
{
string lastName = string.Format("{0}_{1}", m_lastNameStem, i + m_fromBotNumber);
CreateBot(
this,
CreateBehavioursFromAbbreviatedNames(m_defaultBehaviourSwitches),
m_firstName, lastName, m_password, m_loginUri, m_startUri, m_wearSetting);
}
}
}
private List<IBehaviour> CreateBehavioursFromAbbreviatedNames(HashSet<string> abbreviatedNames)
{
// We must give each bot its own list of instantiated behaviours since they store state.
List<IBehaviour> behaviours = new List<IBehaviour>();
// Hard-coded for now
foreach (string abName in abbreviatedNames)
{
IBehaviour newBehaviour = null;
if (abName == "c")
newBehaviour = new CrossBehaviour();
if (abName == "g")
newBehaviour = new GrabbingBehaviour();
if (abName == "n")
newBehaviour = new NoneBehaviour();
if (abName == "p")
newBehaviour = new PhysicsBehaviour();
if (abName == "t")
newBehaviour = new TeleportBehaviour();
if (abName == "tw")
newBehaviour = new TwitchyBehaviour();
if (abName == "ph2")
newBehaviour = new PhysicsBehaviour2();
if (newBehaviour != null)
{
behaviours.Add(newBehaviour);
}
else
{
MainConsole.Instance.OutputFormat("No behaviour with abbreviated name {0} found", abName);
}
}
return behaviours;
}
public void ConnectBots(int botcount)
{
lock (BotConnectingStateChangeObject)
{
if (BotConnectingState != BotManagerBotConnectingState.Ready)
{
MainConsole.Instance.OutputFormat(
"Bot connecting status is {0}. Please wait for previous process to complete.", BotConnectingState);
return;
}
BotConnectingState = BotManagerBotConnectingState.Connecting;
}
Thread connectBotThread = new Thread(o => ConnectBotsInternal(botcount));
connectBotThread.Name = "Bots connection thread";
connectBotThread.Start();
}
private void ConnectBotsInternal(int botCount)
{
m_log.InfoFormat(
"[BOT MANAGER]: Starting {0} bots connecting to {1}, location {2}, named {3} {4}_<n>",
botCount,
m_loginUri,
m_startUri,
m_firstName,
m_lastNameStem);
m_log.DebugFormat("[BOT MANAGER]: Delay between logins is {0}ms", LoginDelay);
m_log.DebugFormat("[BOT MANAGER]: BotsSendAgentUpdates is {0}", InitBotSendAgentUpdates);
m_log.DebugFormat("[BOT MANAGER]: InitBotRequestObjectTextures is {0}", InitBotRequestObjectTextures);
List<Bot> botsToConnect = new List<Bot>();
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
if (bot.ConnectionState == ConnectionState.Disconnected)
botsToConnect.Add(bot);
if (botsToConnect.Count >= botCount)
break;
}
}
foreach (Bot bot in botsToConnect)
{
lock (BotConnectingStateChangeObject)
{
if (BotConnectingState != BotManagerBotConnectingState.Connecting)
{
MainConsole.Instance.Output(
"[BOT MANAGER]: Aborting bot connection due to user-initiated disconnection");
return;
}
}
bot.Connect();
// Stagger logins
Thread.Sleep(LoginDelay);
}
lock (BotConnectingStateChangeObject)
{
if (BotConnectingState == BotManagerBotConnectingState.Connecting)
BotConnectingState = BotManagerBotConnectingState.Ready;
}
}
/// <summary>
/// Parses the command line start location to a start string/uri that the login mechanism will recognize.
/// </summary>
/// <returns>
/// The input start location to URI.
/// </returns>
/// <param name='startLocation'>
/// Start location.
/// </param>
private string ParseInputStartLocationToUri(string startLocation)
{
if (startLocation == "home" || startLocation == "last")
return startLocation;
string regionName;
// Just a region name or only one (!) extra component. Like a viewer, we will stick 128/128/0 on the end
Vector3 startPos = new Vector3(128, 128, 0);
string[] startLocationComponents = startLocation.Split('/');
regionName = startLocationComponents[0];
if (startLocationComponents.Length >= 2)
{
float.TryParse(startLocationComponents[1], out startPos.X);
if (startLocationComponents.Length >= 3)
{
float.TryParse(startLocationComponents[2], out startPos.Y);
if (startLocationComponents.Length >= 4)
float.TryParse(startLocationComponents[3], out startPos.Z);
}
}
return string.Format("uri:{0}&{1}&{2}&{3}", regionName, startPos.X, startPos.Y, startPos.Z);
}
/// <summary>
/// This creates a bot but does not start it.
/// </summary>
/// <param name="bm"></param>
/// <param name="behaviours">Behaviours for this bot to perform.</param>
/// <param name="firstName">First name</param>
/// <param name="lastName">Last name</param>
/// <param name="password">Password</param>
/// <param name="loginUri">Login URI</param>
/// <param name="startLocation">Location to start the bot. Can be "last", "home" or a specific sim name.</param>
/// <param name="wearSetting"></param>
public void CreateBot(
BotManager bm, List<IBehaviour> behaviours,
string firstName, string lastName, string password, string loginUri, string startLocation, string wearSetting)
{
MainConsole.Instance.OutputFormat(
"[BOT MANAGER]: Creating bot {0} {1}, behaviours are {2}",
firstName, lastName, string.Join(",", behaviours.ConvertAll<string>(b => b.Name).ToArray()));
Bot pb = new Bot(bm, behaviours, firstName, lastName, password, startLocation, loginUri);
pb.wear = wearSetting;
pb.Client.Settings.SEND_AGENT_UPDATES = InitBotSendAgentUpdates;
pb.RequestObjectTextures = InitBotRequestObjectTextures;
pb.OnConnected += handlebotEvent;
pb.OnDisconnected += handlebotEvent;
m_bots.Add(pb);
}
/// <summary>
/// High level connnected/disconnected events so we can keep track of our threads by proxy
/// </summary>
/// <param name="callbot"></param>
/// <param name="eventt"></param>
private void handlebotEvent(Bot callbot, EventType eventt)
{
switch (eventt)
{
case EventType.CONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Connected");
break;
}
case EventType.DISCONNECTED:
{
m_log.Info("[" + callbot.FirstName + " " + callbot.LastName + "]: Disconnected");
break;
}
}
}
/// <summary>
/// Standard CreateConsole routine
/// </summary>
/// <returns></returns>
protected CommandConsole CreateConsole()
{
return new LocalConsole("pCampbot");
}
private void HandleConnect(string module, string[] cmd)
{
lock (m_bots)
{
int botsToConnect;
int disconnectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Disconnected);
if (cmd.Length == 1)
{
botsToConnect = disconnectedBots;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToConnect))
return;
botsToConnect = Math.Min(botsToConnect, disconnectedBots);
}
MainConsole.Instance.OutputFormat("Connecting {0} bots", botsToConnect);
ConnectBots(botsToConnect);
}
}
private void HandleAddBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: add behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> rawAbbreviatedSwitchesToAdd = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => rawAbbreviatedSwitchesToAdd.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursAdded = new List<IBehaviour>();
foreach (IBehaviour behaviour in CreateBehavioursFromAbbreviatedNames(rawAbbreviatedSwitchesToAdd))
{
if (bot.AddBehaviour(behaviour))
behavioursAdded.Add(behaviour);
}
MainConsole.Instance.OutputFormat(
"Added behaviours {0} to bot {1}",
string.Join(", ", behavioursAdded.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleRemoveBehaviour(string module, string[] cmd)
{
if (cmd.Length < 3 || cmd.Length > 4)
{
MainConsole.Instance.OutputFormat("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
return;
}
string rawBehaviours = cmd[2];
List<Bot> botsToEffect = new List<Bot>();
if (cmd.Length == 3)
{
lock (m_bots)
botsToEffect.AddRange(m_bots);
}
else
{
int botNumber;
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
botsToEffect.Add(bot);
}
HashSet<string> abbreviatedBehavioursToRemove = new HashSet<string>();
Array.ForEach<string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));
foreach (Bot bot in botsToEffect)
{
List<IBehaviour> behavioursRemoved = new List<IBehaviour>();
foreach (string b in abbreviatedBehavioursToRemove)
{
IBehaviour behaviour;
if (bot.TryGetBehaviour(b, out behaviour))
{
bot.RemoveBehaviour(b);
behavioursRemoved.Add(behaviour);
}
}
MainConsole.Instance.OutputFormat(
"Removed behaviours {0} from bot {1}",
string.Join(", ", behavioursRemoved.ConvertAll<string>(b => b.Name).ToArray()), bot.Name);
}
}
private void HandleDisconnect(string module, string[] cmd)
{
List<Bot> connectedBots;
int botsToDisconnectCount;
lock (m_bots)
connectedBots = m_bots.FindAll(b => b.ConnectionState == ConnectionState.Connected);
if (cmd.Length == 1)
{
botsToDisconnectCount = connectedBots.Count;
}
else
{
if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[1], out botsToDisconnectCount))
return;
botsToDisconnectCount = Math.Min(botsToDisconnectCount, connectedBots.Count);
}
lock (BotConnectingStateChangeObject)
BotConnectingState = BotManagerBotConnectingState.Disconnecting;
Thread disconnectBotThread = new Thread(o => DisconnectBotsInternal(connectedBots, botsToDisconnectCount));
disconnectBotThread.Name = "Bots disconnection thread";
disconnectBotThread.Start();
}
private void DisconnectBotsInternal(List<Bot> connectedBots, int disconnectCount)
{
MainConsole.Instance.OutputFormat("Disconnecting {0} bots", disconnectCount);
int disconnectedBots = 0;
for (int i = connectedBots.Count - 1; i >= 0; i--)
{
if (disconnectedBots >= disconnectCount)
break;
Bot thisBot = connectedBots[i];
if (thisBot.ConnectionState == ConnectionState.Connected)
{
ThreadPool.QueueUserWorkItem(o => thisBot.Disconnect());
disconnectedBots++;
}
}
lock (BotConnectingStateChangeObject)
BotConnectingState = BotManagerBotConnectingState.Ready;
}
private void HandleSit(string module, string[] cmd)
{
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
if (bot.ConnectionState == ConnectionState.Connected)
{
MainConsole.Instance.OutputFormat("Sitting bot {0} on ground.", bot.Name);
bot.SitOnGround();
}
}
}
}
private void HandleStand(string module, string[] cmd)
{
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
if (bot.ConnectionState == ConnectionState.Connected)
{
MainConsole.Instance.OutputFormat("Standing bot {0} from ground.", bot.Name);
bot.Stand();
}
}
}
}
private void HandleShutdown(string module, string[] cmd)
{
lock (m_bots)
{
int connectedBots = m_bots.Count(b => b.ConnectionState == ConnectionState.Connected);
if (connectedBots > 0)
{
MainConsole.Instance.OutputFormat("Please disconnect {0} connected bots first", connectedBots);
return;
}
}
MainConsole.Instance.Output("Shutting down");
m_serverStatsCollector.Close();
Environment.Exit(0);
}
private void HandleSetBots(string module, string[] cmd)
{
string key = cmd[2];
string rawValue = cmd[3];
if (key == "SEND_AGENT_UPDATES")
{
bool newSendAgentUpdatesSetting;
if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newSendAgentUpdatesSetting))
return;
MainConsole.Instance.OutputFormat(
"Setting SEND_AGENT_UPDATES to {0} for all bots", newSendAgentUpdatesSetting);
lock (m_bots)
m_bots.ForEach(b => b.Client.Settings.SEND_AGENT_UPDATES = newSendAgentUpdatesSetting);
}
else
{
MainConsole.Instance.Output("Error: Only setting currently available is SEND_AGENT_UPDATES");
}
}
private void HandleDebugLludpPacketCommand(string module, string[] args)
{
if (args.Length != 6)
{
MainConsole.Instance.OutputFormat("Usage: debug lludp packet <level> <bot-first-name> <bot-last-name>");
return;
}
int level;
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[3], out level))
return;
string botFirstName = args[4];
string botLastName = args[5];
Bot bot;
lock (m_bots)
bot = m_bots.FirstOrDefault(b => b.FirstName == botFirstName && b.LastName == botLastName);
if (bot == null)
{
MainConsole.Instance.OutputFormat("No bot named {0} {1}", botFirstName, botLastName);
return;
}
bot.PacketDebugLevel = level;
MainConsole.Instance.OutputFormat("Set debug level of {0} to {1}", bot.Name, bot.PacketDebugLevel);
}
private void HandleShowRegions(string module, string[] cmd)
{
string outputFormat = "{0,-30} {1, -20} {2, -5} {3, -5}";
MainConsole.Instance.OutputFormat(outputFormat, "Name", "Handle", "X", "Y");
lock (RegionsKnown)
{
foreach (GridRegion region in RegionsKnown.Values)
{
MainConsole.Instance.OutputFormat(
outputFormat, region.Name, region.RegionHandle, region.X, region.Y);
}
}
}
private void HandleShowStatus(string module, string[] cmd)
{
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Bot connecting state", BotConnectingState);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowBotsStatus(string module, string[] cmd)
{
ConsoleDisplayTable cdt = new ConsoleDisplayTable();
cdt.AddColumn("Name", 24);
cdt.AddColumn("Region", 24);
cdt.AddColumn("Status", 13);
cdt.AddColumn("Conns", 5);
cdt.AddColumn("Behaviours", 20);
Dictionary<ConnectionState, int> totals = new Dictionary<ConnectionState, int>();
foreach (object o in Enum.GetValues(typeof(ConnectionState)))
totals[(ConnectionState)o] = 0;
lock (m_bots)
{
foreach (Bot bot in m_bots)
{
Simulator currentSim = bot.Client.Network.CurrentSim;
totals[bot.ConnectionState]++;
cdt.AddRow(
bot.Name,
currentSim != null ? currentSim.Name : "(none)",
bot.ConnectionState,
bot.SimulatorsCount,
string.Join(",", bot.Behaviours.Keys.ToArray()));
}
}
MainConsole.Instance.Output(cdt.ToString());
ConsoleDisplayList cdl = new ConsoleDisplayList();
foreach (KeyValuePair<ConnectionState, int> kvp in totals)
cdl.AddRow(kvp.Key, kvp.Value);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleShowBotStatus(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: show bot <n>");
return;
}
int botNumber;
if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, cmd[2], out botNumber))
return;
Bot bot = GetBotFromNumber(botNumber);
if (bot == null)
{
MainConsole.Instance.OutputFormat("Error: No bot found with number {0}", botNumber);
return;
}
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Name", bot.Name);
cdl.AddRow("Status", bot.ConnectionState);
Simulator currentSim = bot.Client.Network.CurrentSim;
cdl.AddRow("Region", currentSim != null ? currentSim.Name : "(none)");
List<Simulator> connectedSimulators = bot.Simulators;
List<string> simulatorNames = connectedSimulators.ConvertAll<string>(cs => cs.Name);
cdl.AddRow("Connections", string.Join(", ", simulatorNames.ToArray()));
MainConsole.Instance.Output(cdl.ToString());
MainConsole.Instance.Output("Settings");
ConsoleDisplayList statusCdl = new ConsoleDisplayList();
statusCdl.AddRow(
"Behaviours",
string.Join(", ", bot.Behaviours.Values.ToList().ConvertAll<string>(b => b.Name).ToArray()));
GridClient botClient = bot.Client;
statusCdl.AddRow("SEND_AGENT_UPDATES", botClient.Settings.SEND_AGENT_UPDATES);
MainConsole.Instance.Output(statusCdl.ToString());
}
/// <summary>
/// Get a specific bot from its number.
/// </summary>
/// <returns>null if no bot was found</returns>
/// <param name='botNumber'></param>
private Bot GetBotFromNumber(int botNumber)
{
string name = GenerateBotNameFromNumber(botNumber);
Bot bot;
lock (m_bots)
bot = m_bots.Find(b => b.Name == name);
return bot;
}
private string GenerateBotNameFromNumber(int botNumber)
{
return string.Format("{0} {1}_{2}", m_firstName, m_lastNameStem, botNumber);
}
internal void Grid_GridRegion(object o, GridRegionEventArgs args)
{
lock (RegionsKnown)
{
GridRegion newRegion = args.Region;
if (RegionsKnown.ContainsKey(newRegion.RegionHandle))
{
return;
}
else
{
m_log.DebugFormat(
"[BOT MANAGER]: Adding {0} {1} to known regions", newRegion.Name, newRegion.RegionHandle);
RegionsKnown[newRegion.RegionHandle] = newRegion;
}
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests
{
public class IdentifiersShouldHaveCorrectSuffixTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new IdentifiersShouldHaveCorrectSuffixAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new IdentifiersShouldHaveCorrectSuffixAnalyzer();
}
[Fact]
public void CA1710_AllScenarioDiagnostics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
public class EventsItemsEventArgs : EventArgs { }
public class EventsItemsDerived : EventsItemsEventArgs { }
public class EventsItems : EventArgs { }
public delegate void EventCallback(object sender, EventArgs e);
public class EventHandlerTest
{
public event EventCallback EventOne;
}
[Serializable]
public class DiskError : Exception
{
public DiskError() { }
public DiskError(string message) : base(message) { }
public DiskError(string message, Exception innerException) : base(message, innerException) { }
protected DiskError(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class Verifiable : Attribute
{
}
public class ConditionClass : IMembershipCondition
{
public bool Check(Evidence evidence) { return false; }
public IMembershipCondition Copy() { return (IMembershipCondition)null; }
public void FromXml(SecurityElement e, PolicyLevel level) { }
public SecurityElement ToXml(PolicyLevel level) { return (SecurityElement)null; }
public void FromXml(SecurityElement e) { }
public SecurityElement ToXml() { return (SecurityElement)null; }
}
[Serializable]
public class MyTable<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
{
protected MyTable(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class MyStringObjectHashtable : System.Collections.Generic.Dictionary<string, object>
{
protected MyStringObjectHashtable(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
public class MyList<T> : System.Collections.ObjectModel.Collection<T> { }
public class StringGrouping<T> : System.Collections.ObjectModel.Collection<T> { }
public class LastInFirstOut<T> : System.Collections.Generic.Stack<T> { }
public class StackOfIntegers : System.Collections.Generic.Stack<int> { }
public class FirstInFirstOut<T> : System.Collections.Generic.Queue<T> { }
public class QueueOfNumbers : System.Collections.Generic.Queue<int> { }
public class MyDataStructure : Stack { }
public class AnotherDataStructure : Queue { }
public class WronglyNamedPermissionClass : CodeAccessPermission
{
public override IPermission Copy() { return (IPermission)null; }
public override void FromXml(SecurityElement e) { }
public override IPermission Intersect(IPermission target) { return (IPermission)null; }
public override bool IsSubsetOf(IPermission target) { return false; }
public override SecurityElement ToXml() { return (SecurityElement)null; }
}
public class WronglyNamedIPermissionClass : IPermission
{
public IPermission Copy() { return (IPermission)null; }
public void FromXml(SecurityElement e) { }
public IPermission Intersect(IPermission target) { return (IPermission)null; }
public bool IsSubsetOf(IPermission target) { return false; }
public SecurityElement ToXml() { return (SecurityElement)null; }
public IPermission Union(IPermission target) { return (IPermission)null; }
public void Demand() { }
}
public class WronglyNamedType : Stream
{
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { return 0; } }
public override long Position { get { return 0; } set { } }
public override void Close() { base.Close(); }
public override void Flush() { }
public override int Read(byte[] buffer, int offset, int count) { return 0; }
public override long Seek(long offset, SeekOrigin origin) { return 0; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
}
public class MyCollectionIsEnumerable : IEnumerable
{
public void CopyTo(Array destination, int index)
{
System.Console.WriteLine(this);
System.Console.WriteLine(destination);
System.Console.WriteLine(index);
}
public int Count
{
get
{
Console.WriteLine(this);
return 0;
}
set
{
System.Console.WriteLine(this);
System.Console.WriteLine(value);
}
}
public bool IsSynchronized
{
get
{
Console.WriteLine(this);
return true;
}
set
{
System.Console.WriteLine(this);
System.Console.WriteLine(value);
}
}
public object SyncRoot
{
get
{
return this;
}
set
{
System.Console.WriteLine(this);
System.Console.WriteLine(value);
}
}
public IEnumerator GetEnumerator() { return null; }
}
public class CollectionDoesNotEndInCollectionClass : StringCollection { }
[Serializable]
public class DictionaryDoesNotEndInDictionaryClass : Hashtable
{
protected DictionaryDoesNotEndInDictionaryClass(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
public class MyTest<T> : List<T>
{
}
[Serializable]
public class DataSetWithWrongSuffix : DataSet
{
protected DataSetWithWrongSuffix(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
[Serializable]
public class DataTableWithWrongSuffix : DataTable
{
protected DataTableWithWrongSuffix(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}",
GetCA1710CSharpResultAt(line: 16, column: 14, symbolName: "EventsItemsDerived", replacementName: "EventArgs"),
GetCA1710CSharpResultAt(line: 18, column: 14, symbolName: "EventsItems", replacementName: "EventArgs"),
GetCA1710CSharpResultAt(line: 24, column: 32, symbolName: "EventCallback", replacementName: "EventHandler"),
GetCA1710CSharpResultAt(line: 28, column: 14, symbolName: "DiskError", replacementName: "Exception"),
GetCA1710CSharpResultAt(line: 39, column: 21, symbolName: "Verifiable", replacementName: "Attribute"),
GetCA1710CSharpResultAt(line: 43, column: 14, symbolName: "ConditionClass", replacementName: "Condition"),
GetCA1710CSharpResultAt(line: 54, column: 14, symbolName: "MyTable<TKey, TValue>", replacementName: "Dictionary"),
GetCA1710CSharpResultAt(line: 60, column: 14, symbolName: "MyStringObjectHashtable", replacementName: "Dictionary"),
GetCA1710CSharpResultAt(line: 65, column: 14, symbolName: "MyList<T>", replacementName: "Collection"),
GetCA1710CSharpResultAt(line: 67, column: 14, symbolName: "StringGrouping<T>", replacementName: "Collection"),
GetCA1710CSharpResultAt(line: 69, column: 14, symbolName: "LastInFirstOut<T>", replacementName: "Stack", isSpecial: true),
GetCA1710CSharpResultAt(line: 71, column: 14, symbolName: "StackOfIntegers", replacementName: "Stack", isSpecial: true),
GetCA1710CSharpResultAt(line: 73, column: 14, symbolName: "FirstInFirstOut<T>", replacementName: "Queue", isSpecial: true),
GetCA1710CSharpResultAt(line: 75, column: 14, symbolName: "QueueOfNumbers", replacementName: "Queue", isSpecial: true),
GetCA1710CSharpResultAt(line: 77, column: 14, symbolName: "MyDataStructure", replacementName: "Stack", isSpecial: true),
GetCA1710CSharpResultAt(line: 79, column: 14, symbolName: "AnotherDataStructure", replacementName: "Queue", isSpecial: true),
GetCA1710CSharpResultAt(line: 81, column: 14, symbolName: "WronglyNamedPermissionClass", replacementName: "Permission"),
GetCA1710CSharpResultAt(line: 90, column: 14, symbolName: "WronglyNamedIPermissionClass", replacementName: "Permission"),
GetCA1710CSharpResultAt(line: 101, column: 14, symbolName: "WronglyNamedType", replacementName: "Stream"),
GetCA1710CSharpResultAt(line: 116, column: 14, symbolName: "MyCollectionIsEnumerable", replacementName: "Collection"),
GetCA1710CSharpResultAt(line: 165, column: 14, symbolName: "CollectionDoesNotEndInCollectionClass", replacementName: "Collection"),
GetCA1710CSharpResultAt(line: 168, column: 14, symbolName: "DictionaryDoesNotEndInDictionaryClass", replacementName: "Dictionary"),
GetCA1710CSharpResultAt(line: 174, column: 14, symbolName: "MyTest<T>", replacementName: "Collection"),
GetCA1710CSharpResultAt(line: 179, column: 14, symbolName: "DataSetWithWrongSuffix", replacementName: "DataSet"),
GetCA1710CSharpResultAt(line: 186, column: 14, symbolName: "DataTableWithWrongSuffix", replacementName: "DataTable", isSpecial: true));
}
[Fact]
public void CA1710_NoDiagnostics_CSharp()
{
VerifyCSharp(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
[Serializable]
public class MyDictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
{
protected MyDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class MyStringObjectDictionary : System.Collections.Generic.Dictionary<string, object>
{
protected MyStringObjectDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
public class MyCollection<T> : System.Collections.ObjectModel.Collection<T> { }
public class MyStringCollection : System.Collections.ObjectModel.Collection<string> { }
public class MyStack<T> : System.Collections.Generic.Stack<T> { }
public class MyIntegerStack : System.Collections.Generic.Stack<int> { }
public class StackCollection<T> : System.Collections.Generic.Stack<T> { }
public class IntegerStackCollection : System.Collections.Generic.Stack<int> { }
public class MyQueue<T> : System.Collections.Generic.Queue<T> { }
public class MyIntegerQueue : System.Collections.Generic.Queue<int> { }
public class QueueCollection<T> : System.Collections.Generic.Queue<T> { }
public class IntegerQueueCollection : System.Collections.Generic.Queue<int> { }
public delegate void SimpleEventHandler(object sender, EventArgs e);
public class EventHandlerTest
{
public event SimpleEventHandler EventOne;
public event EventHandler<EventArgs> EventTwo;
}
[Serializable]
public class DiskErrorException : Exception
{
public DiskErrorException() { }
public DiskErrorException(string message) : base(message) { }
public DiskErrorException(string message, Exception innerException) : base(message, innerException) { }
protected DiskErrorException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class VerifiableAttribute : Attribute
{
}
public class MyCondition : IMembershipCondition
{
public bool Check(Evidence evidence) { return false; }
public IMembershipCondition Copy() { return (IMembershipCondition)null; }
public void FromXml(SecurityElement e, PolicyLevel level) { }
public SecurityElement ToXml(PolicyLevel level) { return (SecurityElement)null; }
public void FromXml(SecurityElement e) { }
public SecurityElement ToXml() { return (SecurityElement)null; }
}
public class CorrectlyNamedPermission : CodeAccessPermission
{
public override IPermission Copy() { return (IPermission)null; }
public override void FromXml(SecurityElement e) { }
public override IPermission Intersect(IPermission target) { return (IPermission)null; }
public override bool IsSubsetOf(IPermission target) { return false; }
public override SecurityElement ToXml() { return (SecurityElement)null; }
}
public class CorrectlyNamedIPermission : IPermission
{
public IPermission Copy() { return (IPermission)null; }
public void FromXml(SecurityElement e) { }
public IPermission Intersect(IPermission target) { return (IPermission)null; }
public bool IsSubsetOf(IPermission target) { return false; }
public SecurityElement ToXml() { return (SecurityElement)null; }
public IPermission Union(IPermission target) { return (IPermission)null; }
public void Demand() { }
}
public class CorrectlyNamedTypeStream : Stream
{
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { return 0; } }
public override long Position { get { return 0; } set { } }
public override void Close() { base.Close(); }
public override void Flush() { }
public override int Read(byte[] buffer, int offset, int count) { return 0; }
public override long Seek(long offset, SeekOrigin origin) { return 0; }
public override void SetLength(long value) { }
public override void Write(byte[] buffer, int offset, int count) { }
}
public class CollectionEndsInCollection : StringCollection { }
[Serializable]
public class DictionaryEndsInDictionary : Hashtable
{
public DictionaryEndsInDictionary() { }
protected DictionaryEndsInDictionary(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
[Serializable]
public class MySpecialQueue : Queue { }
public class QueueCollection : Queue { }
[Serializable]
public class MyStack : Stack { }
public class StackCollection : Stack { }
[Serializable]
public class MyDataSet : DataSet
{
public MyDataSet() { }
protected MyDataSet(SerializationInfo info, StreamingContext context) : base(info, context) { }
public void DoWork() { Console.WriteLine(this); }
}
[Serializable]
public class MyDataTable : DataTable
{
public MyDataTable() { }
protected MyDataTable(SerializationInfo info, StreamingContext context)
: base(info, context) { }
public void DoWork() { Console.WriteLine(this); }
}
[Serializable]
public class MyCollectionDataTable : DataTable, IEnumerable
{
public MyCollectionDataTable() { }
protected MyCollectionDataTable(SerializationInfo info, StreamingContext context)
: base(info, context) { }
public void DoWork() { Console.WriteLine(this); }
public IEnumerator GetEnumerator()
{
return null;
}
}");
}
[Fact]
public void CA1710_AllScenarioDiagnostics_VisualBasic()
{
this.PrintActualDiagnosticsOnFailure = true;
VerifyBasic(@"
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Imports System.Data
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Security
Imports System.Security.Policy
Public Class AnotherDataStructure
Inherits Queue
End Class
Public Class CollectionDoesNotEndInCollectionClass
Inherits StringCollection
End Class
Public Class ConditionClass
Implements IMembershipCondition, ISecurityEncodable, ISecurityPolicyEncodable
' Methods
Public Function Check(ByVal evidence As Evidence) As Boolean Implements IMembershipCondition.Check
Return False
End Function
Public Function Copy() As IMembershipCondition Implements IMembershipCondition.Copy
Return Nothing
End Function
Public Sub FromXml(ByVal e As SecurityElement) Implements ISecurityEncodable.FromXml
End Sub
Public Sub FromXml(ByVal e As SecurityElement, ByVal level As PolicyLevel) Implements ISecurityPolicyEncodable.FromXml
End Sub
Public Function ToXml() As SecurityElement Implements ISecurityEncodable.ToXml
Return Nothing
End Function
Public Function ToXml(ByVal level As PolicyLevel) As SecurityElement Implements ISecurityPolicyEncodable.ToXml
Return Nothing
End Function
Public Overrides Function ToString() As String Implements IMembershipCondition.ToString
Return MyBase.ToString()
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean Implements IMembershipCondition.Equals
Return MyBase.Equals(obj)
End Function
Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode()
End Function
End Class
<Serializable()>
Public Class DataSetWithWrongSuffix
Inherits DataSet
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
<Serializable()>
Public Class DataTableWithWrongSuffix
Inherits DataTable
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
<Serializable()>
Public Class DictionaryDoesNotEndInDictionaryClass
Inherits Hashtable
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
<Serializable()>
Public Class DiskError
Inherits Exception
' Methods
Public Sub New()
End Sub
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub New(ByVal message As String, ByVal innerException As Exception)
MyBase.New(message, innerException)
End Sub
End Class
Public Delegate Sub EventCallback(ByVal sender As Object, ByVal e As EventArgs)
Public Class EventHandlerTest
' Events
Public Event EventOne As EventCallback
End Class
Public Class EventsItems
Inherits EventArgs
End Class
Public Class FirstInFirstOut(Of T)
Inherits Queue(Of T)
End Class
Public Class LastInFirstOut(Of T)
Inherits Stack(Of T)
End Class
Public Class MyCollectionIsEnumerable
Implements IEnumerable
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
Public Class MyDataStructure
Inherits Stack
End Class
Public Class MyList(Of T)
Inherits Collection(Of T)
End Class
<Serializable()>
Public Class MyStringObjectHashtable
Inherits Dictionary(Of String, Object)
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
<Serializable()>
Public Class MyTable(Of TKey, TValue)
Inherits Dictionary(Of TKey, TValue)
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
Public Class MyTest(Of T)
Inherits List(Of T)
End Class
Public Class QueueOfNumbers
Inherits Queue(Of Integer)
End Class
Public Class StackOfIntegers
Inherits Stack(Of Integer)
End Class
Public Class StringGrouping(Of T)
Inherits Collection(Of T)
End Class
<AttributeUsage(AttributeTargets.Class)>
Public NotInheritable Class Verifiable
Inherits Attribute
End Class
Public Class WronglyNamedIPermissionClass
Implements IPermission, ISecurityEncodable
' Methods
Public Function Copy() As IPermission Implements IPermission.Copy
Return Nothing
End Function
Public Sub Demand() Implements IPermission.Demand
End Sub
Public Sub FromXml(ByVal e As SecurityElement) Implements ISecurityEncodable.FromXml
End Sub
Public Function Intersect(ByVal target As IPermission) As IPermission Implements IPermission.Intersect
Return Nothing
End Function
Public Function IsSubsetOf(ByVal target As IPermission) As Boolean Implements IPermission.IsSubsetOf
Return False
End Function
Public Function ToXml() As SecurityElement Implements ISecurityEncodable.ToXml
Return Nothing
End Function
Public Function Union(ByVal target As IPermission) As IPermission Implements IPermission.Union
Return Nothing
End Function
End Class
Public Class WronglyNamedPermissionClass
Inherits CodeAccessPermission
' Methods
Public Overrides Function Copy() As IPermission
Return Nothing
End Function
Public Overrides Sub FromXml(ByVal e As SecurityElement)
End Sub
Public Overrides Function Intersect(ByVal target As IPermission) As IPermission
Return Nothing
End Function
Public Overrides Function IsSubsetOf(ByVal target As IPermission) As Boolean
Return False
End Function
Public Overrides Function ToXml() As SecurityElement
Return Nothing
End Function
End Class
Public Class WronglyNamedType
Inherits Stream
' Methods
Public Overrides Sub Close()
MyBase.Close()
End Sub
Public Overrides Sub Flush()
End Sub
Public Overrides Function Read(ByVal buffer As Byte(), ByVal offset As Integer, ByVal count As Integer) As Integer
Return 0
End Function
Public Overrides Function Seek(ByVal offset As Long, ByVal origin As SeekOrigin) As Long
Return CType(0, Long)
End Function
Public Overrides Sub SetLength(ByVal value As Long)
End Sub
Public Overrides Sub Write(ByVal buffer As Byte(), ByVal offset As Integer, ByVal count As Integer)
End Sub
' Properties
Public Overrides ReadOnly Property CanRead() As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property CanSeek() As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property CanWrite() As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Length() As Long
Get
Return CType(0, Long)
End Get
End Property
Public Overrides Property Position() As Long
Get
Return CType(0, Long)
End Get
Set(ByVal value As Long)
End Set
End Property
End Class",
GetCA1710BasicResultAt(line: 13, column: 14, symbolName: "AnotherDataStructure", replacementName: "Queue", isSpecial: true),
GetCA1710BasicResultAt(line: 17, column: 14, symbolName: "CollectionDoesNotEndInCollectionClass", replacementName: "Collection"),
GetCA1710BasicResultAt(line: 22, column: 14, symbolName: "ConditionClass", replacementName: "Condition"),
GetCA1710BasicResultAt(line: 64, column: 14, symbolName: "DataSetWithWrongSuffix", replacementName: "DataSet"),
GetCA1710BasicResultAt(line: 75, column: 14, symbolName: "DataTableWithWrongSuffix", replacementName: "DataTable", isSpecial: true),
GetCA1710BasicResultAt(line: 86, column: 14, symbolName: "DictionaryDoesNotEndInDictionaryClass", replacementName: "Dictionary"),
GetCA1710BasicResultAt(line: 97, column: 14, symbolName: "DiskError", replacementName: "Exception"),
GetCA1710BasicResultAt(line: 122, column: 18, symbolName: "EventCallback", replacementName: "EventHandler"),
GetCA1710BasicResultAt(line: 125, column: 14, symbolName: "EventsItems", replacementName: "EventArgs"),
GetCA1710BasicResultAt(line: 130, column: 14, symbolName: "FirstInFirstOut(Of T)", replacementName: "Queue", isSpecial: true),
GetCA1710BasicResultAt(line: 135, column: 14, symbolName: "LastInFirstOut(Of T)", replacementName: "Stack", isSpecial: true),
GetCA1710BasicResultAt(line: 140, column: 14, symbolName: "MyCollectionIsEnumerable", replacementName: "Collection"),
GetCA1710BasicResultAt(line: 148, column: 14, symbolName: "MyDataStructure", replacementName: "Stack", isSpecial: true),
GetCA1710BasicResultAt(line: 153, column: 14, symbolName: "MyList(Of T)", replacementName: "Collection"),
GetCA1710BasicResultAt(line: 159, column: 14, symbolName: "MyStringObjectHashtable", replacementName: "Dictionary"),
GetCA1710BasicResultAt(line: 170, column: 14, symbolName: "MyTable(Of TKey, TValue)", replacementName: "Dictionary"),
GetCA1710BasicResultAt(line: 180, column: 14, symbolName: "MyTest(Of T)", replacementName: "Collection"),
GetCA1710BasicResultAt(line: 185, column: 14, symbolName: "QueueOfNumbers", replacementName: "Queue", isSpecial: true),
GetCA1710BasicResultAt(line: 190, column: 14, symbolName: "StackOfIntegers", replacementName: "Stack", isSpecial: true),
GetCA1710BasicResultAt(line: 195, column: 14, symbolName: "StringGrouping(Of T)", replacementName: "Collection"),
GetCA1710BasicResultAt(line: 201, column: 29, symbolName: "Verifiable", replacementName: "Attribute"),
GetCA1710BasicResultAt(line: 206, column: 14, symbolName: "WronglyNamedIPermissionClass", replacementName: "Permission"),
GetCA1710BasicResultAt(line: 238, column: 14, symbolName: "WronglyNamedPermissionClass", replacementName: "Permission"),
GetCA1710BasicResultAt(line: 263, column: 14, symbolName: "WronglyNamedType", replacementName: "Stream"));
}
[Fact]
public void CA1710_NoDiagnostics_VisualBasic()
{
this.PrintActualDiagnosticsOnFailure = true;
VerifyBasic(@"
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Imports System.Data
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Security
Imports System.Security.Policy
Public Class CollectionEndsInCollection
Inherits StringCollection
End Class
Public Class CorrectlyNamedIPermission
Implements IPermission, ISecurityEncodable
Public Function Copy() As System.Security.IPermission Implements System.Security.IPermission.Copy
Return Me
End Function
Public Sub Demand() Implements System.Security.IPermission.Demand
End Sub
Public Function Intersect(ByVal target As System.Security.IPermission) As System.Security.IPermission Implements System.Security.IPermission.Intersect
Return Nothing
End Function
Public Function IsSubsetOf(ByVal target As System.Security.IPermission) As Boolean Implements System.Security.IPermission.IsSubsetOf
Return False
End Function
Public Function Union(ByVal target As System.Security.IPermission) As System.Security.IPermission Implements System.Security.IPermission.Union
Return Me
End Function
Public Sub FromXml(ByVal e As System.Security.SecurityElement) Implements System.Security.ISecurityEncodable.FromXml
End Sub
Public Function ToXml() As System.Security.SecurityElement Implements System.Security.ISecurityEncodable.ToXml
End Function
End Class
Public Class CorrectlyNamedPermission
Inherits CodeAccessPermission
Public Overrides Function Copy() As System.Security.IPermission
End Function
Public Overrides Sub FromXml(ByVal elem As System.Security.SecurityElement)
End Sub
Public Overrides Function Intersect(ByVal target As System.Security.IPermission) As System.Security.IPermission
End Function
Public Overrides Function IsSubsetOf(ByVal target As System.Security.IPermission) As Boolean
End Function
Public Overrides Function ToXml() As System.Security.SecurityElement
End Function
End Class
Public Class CorrectlyNamedTypeStream
Inherits FileStream
Public Sub New()
MyBase.New("", FileMode.Open)
End Sub
End Class
<Serializable()>
Public Class DictionaryEndsInDictionary
Inherits Hashtable
' Methods
Public Sub New()
End Sub
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
<Serializable()>
Public Class DiskErrorException
Inherits Exception
' Methods
Public Sub New()
End Sub
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub New(ByVal message As String, ByVal innerException As Exception)
MyBase.New(message, innerException)
End Sub
End Class
Public Class EventHandlerTest
' Events
Public Event EventOne As SimpleEventHandler
End Class
Public Class EventsItemsEventArgs
Inherits EventArgs
End Class
Public Class IntegerQueueCollection
Inherits Queue(Of Integer)
End Class
Public Class IntegerStackCollection
Inherits Stack(Of Integer)
End Class
Public Class MyCollection(Of T)
Inherits Collection(Of T)
End Class
Public Class MyCondition
Implements IMembershipCondition, ISecurityEncodable, ISecurityPolicyEncodable
Public Sub FromXml(ByVal e As System.Security.SecurityElement) Implements System.Security.ISecurityEncodable.FromXml
End Sub
Public Function ToXml() As System.Security.SecurityElement Implements System.Security.ISecurityEncodable.ToXml
End Function
Public Sub FromXml1(ByVal e As System.Security.SecurityElement, ByVal level As System.Security.Policy.PolicyLevel) Implements System.Security.ISecurityPolicyEncodable.FromXml
End Sub
Public Function ToXml1(ByVal level As System.Security.Policy.PolicyLevel) As System.Security.SecurityElement Implements System.Security.ISecurityPolicyEncodable.ToXml
End Function
Public Function Check(ByVal evidence As System.Security.Policy.Evidence) As Boolean Implements System.Security.Policy.IMembershipCondition.Check
End Function
Public Function Copy() As System.Security.Policy.IMembershipCondition Implements System.Security.Policy.IMembershipCondition.Copy
End Function
Public Function Equals1(ByVal obj As Object) As Boolean Implements System.Security.Policy.IMembershipCondition.Equals
End Function
Public Function ToString1() As String Implements System.Security.Policy.IMembershipCondition.ToString
End Function
End Class
<Serializable()>
Public Class MyDataSet
Inherits DataSet
' Methods
Public Sub New()
End Sub
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub DoWork()
Console.WriteLine(Me)
End Sub
End Class
<Serializable()>
Public Class MyDataTable
Inherits DataTable
' Methods
Public Sub New()
End Sub
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub DoWork()
Console.WriteLine(Me)
End Sub
End Class
<Serializable()>
Public Class MyDictionary(Of TKey, TValue)
Inherits Dictionary(Of TKey, TValue)
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
Public Class MyIntegerQueue
Inherits Queue(Of Integer)
End Class
Public Class MyIntegerStack
Inherits Stack(Of Integer)
End Class
Public Class MyQueue(Of T)
Inherits Queue(Of T)
End Class
<Serializable()>
Public Class MySpecialQueue
Inherits Queue
End Class
Public Class MyStack(Of T)
Inherits Stack(Of T)
End Class
<Serializable()>
Public Class MyStack
Inherits Stack
End Class
Public Class MyStringCollection
Inherits Collection(Of String)
End Class
<Serializable()>
Public Class MyStringObjectDictionary
Inherits Dictionary(Of String, Object)
' Methods
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
End Class
Public Class QueueCollection(Of T)
Inherits Queue(Of T)
End Class
Public Class QueueCollection
Inherits Queue
End Class
Public Delegate Sub SimpleEventHandler(ByVal sender As Object, ByVal e As EventArgs)
Public Class StackCollection(Of T)
Inherits Stack(Of T)
End Class
Public Class StackCollection
Inherits Stack
End Class
<AttributeUsage(AttributeTargets.Class)>
Public NotInheritable Class VerifiableAttribute
Inherits Attribute
End Class");
}
private static DiagnosticResult GetCA1710BasicResultAt(int line, int column, string symbolName, string replacementName, bool isSpecial = false)
{
return GetBasicResultAt(
line,
column,
IdentifiersShouldHaveCorrectSuffixAnalyzer.RuleId,
string.Format(
isSpecial ?
MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageSpecialCollection :
MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageDefault,
symbolName,
replacementName));
}
private static DiagnosticResult GetCA1710CSharpResultAt(int line, int column, string symbolName, string replacementName, bool isSpecial = false)
{
return GetCSharpResultAt(
line,
column,
IdentifiersShouldHaveCorrectSuffixAnalyzer.RuleId,
string.Format(
isSpecial ?
MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageSpecialCollection :
MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldHaveCorrectSuffixMessageDefault,
symbolName,
replacementName));
}
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class ReliabilityTestSet
{
private int _maximumTestLoops = 0; // default run based on time.
private int _maximumExecutionTime = 60; // 60 minute run by default.
private int _percentPassIsPass = System.Environment.GetEnvironmentVariable("PERCENTPASSISPASS") == null ? -1 : Convert.ToInt32(System.Environment.GetEnvironmentVariable("PERCENTPASSISPASS"));
private int[] _minPercentCPUStaggered_times = null;
private int[] _minPercentCPUStaggered_usage = null;
private int _minimumCPUpercent = 0,_minimumMemoryPercent = 0,_minimumTestsRunning = 0,_maximumTestsRunning = -1; // minimum CPU & memory requirements.
private ReliabilityTest[] _tests;
private string[] _discoveryPaths = null;
private string _friendlyName;
private bool _enablePerfCounters = true,_disableLogging = false,_installDetours = false;
private bool _suppressConsoleOutputFromTests = false;
private bool _debugBreakOnTestHang = true;
private bool _debugBreakOnBadTest = false;
private bool _debugBreakOnOutOfMemory = false;
private bool _debugBreakOnPathTooLong = false;
private bool _debugBreakOnMissingTest = false;
private TestStartModeEnum _testStartMode = TestStartModeEnum.AppDomainLoader;
private string _defaultDebugger,_defaultDebuggerOptions;
private int _ulGeneralUnloadPercent = 0,_ulAppDomainUnloadPercent = 0,_ulAssemblyLoadPercent = 0,_ulWaitTime = 0;
private bool _reportResults = false;
private string _reportResultsTo = "http://clrqa/SmartAPI/result.asmx";
private Guid _bvtCategory = Guid.Empty;
private string _ccFailMail;
private AppDomainLoaderMode _adLoaderMode = AppDomainLoaderMode.Normal;
private int _numAppDomains = 10; //used for roundRobin scheduling, our app domain index
private Random _rand = new Random();
private LoggingLevels _loggingLevel = LoggingLevels.All; // by default log everything
public ReliabilityTest[] Tests
{
get
{
return (_tests);
}
set
{
_tests = value;
}
}
public int MaximumLoops
{
get
{
return (_maximumTestLoops);
}
set
{
_maximumTestLoops = value;
}
}
public LoggingLevels LoggingLevel
{
get
{
return (_loggingLevel);
}
set
{
_loggingLevel = value;
}
}
/// <summary>
/// Maximum execution time, in minutes.
/// </summary>
public int MaximumTime
{
get
{
return (_maximumExecutionTime);
}
set
{
_maximumExecutionTime = value;
}
}
public string FriendlyName
{
get
{
return (_friendlyName);
}
set
{
_friendlyName = value;
}
}
public string[] DiscoveryPaths
{
get
{
return (_discoveryPaths);
}
set
{
_discoveryPaths = value;
}
}
public int MinPercentCPU
{
get
{
return (_minimumCPUpercent);
}
set
{
_minimumCPUpercent = value;
}
}
public int GetCurrentMinPercentCPU(TimeSpan timeRunning)
{
if (_minPercentCPUStaggered_usage == null)
{
return (MinPercentCPU);
}
int curCpu = _minPercentCPUStaggered_usage[0];
int curTime = 0;
for (int i = 1; i < _minPercentCPUStaggered_usage.Length; i++)
{
curTime += _minPercentCPUStaggered_times[i - 1];
if (curTime > timeRunning.TotalMinutes)
{
// we're in this time zone, return our current cpu
return (curCpu);
}
// we're in a later time zone, keep looking...
curCpu = _minPercentCPUStaggered_usage[i];
}
return (curCpu);
}
public string MinPercentCPUStaggered
{
set
{
string[] minPercentCPUStaggered = value.Split(';');
_minPercentCPUStaggered_times = new int[minPercentCPUStaggered.Length];
_minPercentCPUStaggered_usage = new int[minPercentCPUStaggered.Length];
for (int i = 0; i < minPercentCPUStaggered.Length; i++)
{
string[] split = minPercentCPUStaggered[i].Split(':');
string time = split[0];
string usage = split[1];
_minPercentCPUStaggered_times[i] = GetValue(time);
_minPercentCPUStaggered_usage[i] = GetValue(usage);
}
}
}
/// <summary>
/// Gets the integer value or the random value specified in the string.
/// accepted format:
/// 30:50 run for 30 minutes at 50% usage
/// rand(30,60):50 run at 50% usage for somewhere between 30 and 60 minutes.
/// 30:rand(50, 75) run for 30 minutes at somewhere between 50 and 75 % CPU usage
/// rand(30, 60) : rand(50, 75) run for somewhere between 30-60 minutes at 50-75% CPU usage.
/// </summary>
/// <param name="times"></param>
/// <returns></returns>
private int GetValue(string times)
{
times = times.Trim();
if (String.Compare(times, 0, "rand(", 0, 5) == 0)
{
string trimmedTimes = times.Substring(5).Trim();
string[] values = trimmedTimes.Split(new char[] { ',' });
int min = Convert.ToInt32(values[0]);
int max = Convert.ToInt32(values[1].Substring(0, values[1].Length - 1)); // remove the ending )
return (_rand.Next(min, max));
}
else
{
return (Convert.ToInt32(times));
}
}
public int MinPercentMem
{
get
{
return (_minimumMemoryPercent);
}
set
{
_minimumMemoryPercent = value;
}
}
public int MinTestsRunning
{
get
{
return (_minimumTestsRunning);
}
set
{
_minimumTestsRunning = value;
}
}
public int MaxTestsRunning
{
get
{
return (_maximumTestsRunning);
}
set
{
_maximumTestsRunning = value;
}
}
public bool EnablePerfCounters
{
get
{
#if PROJECTK_BUILD
return false;
#else
if (enablePerfCounters)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
enablePerfCounters = false;
}
}
return (enablePerfCounters);
#endif
}
set
{
_enablePerfCounters = value;
}
}
public bool DisableLogging
{
get
{
return (_disableLogging);
}
set
{
_disableLogging = value;
}
}
public bool InstallDetours
{
get
{
return (_installDetours);
}
set
{
_installDetours = value;
}
}
public TestStartModeEnum DefaultTestStartMode
{
get
{
return (_testStartMode);
}
set
{
_testStartMode = value;
}
}
public int PercentPassIsPass
{
get
{
return (_percentPassIsPass);
}
set
{
_percentPassIsPass = value;
}
}
public AppDomainLoaderMode AppDomainLoaderMode
{
get
{
return (_adLoaderMode);
}
set
{
_adLoaderMode = value;
}
}
/// <summary>
/// Used for round-robin scheduling. Number of app domains to schedule tests into.
/// </summary>
public int NumAppDomains
{
get
{
return (_numAppDomains);
}
set
{
_numAppDomains = value;
}
}
public string DefaultDebugger
{
get
{
return (_defaultDebugger);
}
set
{
_defaultDebugger = value;
}
}
public string DefaultDebuggerOptions
{
get
{
return (_defaultDebuggerOptions);
}
set
{
_defaultDebuggerOptions = value;
}
}
public int ULGeneralUnloadPercent
{
get
{
return (_ulGeneralUnloadPercent);
}
set
{
_ulGeneralUnloadPercent = value;
}
}
public int ULAppDomainUnloadPercent
{
get
{
return (_ulAppDomainUnloadPercent);
}
set
{
_ulAppDomainUnloadPercent = value;
}
}
public int ULAssemblyLoadPercent
{
get
{
return (_ulAssemblyLoadPercent);
}
set
{
_ulAssemblyLoadPercent = value;
}
}
public int ULWaitTime
{
get
{
return (_ulWaitTime);
}
set
{
_ulWaitTime = value;
}
}
public bool ReportResults
{
get
{
if (_reportResults && Environment.GetEnvironmentVariable("RF_NOREPORT") == null)
{
_reportResults = false;
}
return (_reportResults);
}
set
{
_reportResults = value;
}
}
public string ReportResultsTo
{
get
{
return (_reportResultsTo);
}
set
{
_reportResultsTo = value;
}
}
public Guid BvtCategory
{
get
{
return (_bvtCategory);
}
set
{
_bvtCategory = value;
}
}
public string CCFailMail
{
get
{
return (_ccFailMail);
}
set
{
_ccFailMail = value;
}
}
public bool SuppressConsoleOutputFromTests
{
get
{
return _suppressConsoleOutputFromTests;
}
set
{
_suppressConsoleOutputFromTests = value;
}
}
public bool DebugBreakOnTestHang
{
get
{
return _debugBreakOnTestHang;
}
set
{
_debugBreakOnTestHang = value;
}
}
public bool DebugBreakOnBadTest
{
get
{
return _debugBreakOnBadTest;
}
set
{
_debugBreakOnBadTest = value;
}
}
public bool DebugBreakOnOutOfMemory
{
get
{
return _debugBreakOnOutOfMemory;
}
set
{
_debugBreakOnOutOfMemory = value;
}
}
public bool DebugBreakOnPathTooLong
{
get
{
return _debugBreakOnPathTooLong;
}
set
{
_debugBreakOnPathTooLong = value;
}
}
public bool DebugBreakOnMissingTest
{
get
{
return _debugBreakOnMissingTest;
}
set
{
_debugBreakOnMissingTest = value;
}
}
}
| |
/*
* 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.Threading;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EntityTransfer;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.XEngine.Tests
{
/// <summary>
/// XEngine tests connected with crossing scripts between regions.
/// </summary>
[TestFixture]
public class XEngineCrossingTests : OpenSimTestCase
{
[TestFixtureSetUp]
public void FixtureInit()
{
// Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread.
Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest;
}
[TestFixtureTearDown]
public void TearDown()
{
// We must set this back afterwards, otherwise later tests will fail since they're expecting multiple
// threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression
// tests really shouldn't).
Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod;
}
/// <summary>
/// Test script state preservation when a script crosses between regions on the same simulator.
/// </summary>
[Test]
public void TestScriptCrossOnSameSimulator()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
UUID userId = TestHelpers.ParseTail(0x1);
int sceneObjectIdTail = 0x2;
EntityTransferModule etmA = new EntityTransferModule();
EntityTransferModule etmB = new EntityTransferModule();
LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule();
XEngine xEngineA = new XEngine();
XEngine xEngineB = new XEngine();
xEngineA.DebugLevel = 1;
xEngineB.DebugLevel = 1;
IConfigSource configSource = new IniConfigSource();
IConfig startupConfig = configSource.AddConfig("Startup");
startupConfig.Set("DefaultScriptEngine", "XEngine");
startupConfig.Set("TrustBinaries", "true");
IConfig xEngineConfig = configSource.AddConfig("XEngine");
xEngineConfig.Set("Enabled", "true");
xEngineConfig.Set("StartDelay", "0");
// These tests will not run with AppDomainLoading = true, at least on mono. For unknown reasons, the call
// to AssemblyResolver.OnAssemblyResolve fails.
xEngineConfig.Set("AppDomainLoading", "false");
IConfig modulesConfig = configSource.AddConfig("Modules");
modulesConfig.Set("EntityTransferModule", etmA.Name);
modulesConfig.Set("SimulationServices", lscm.Name);
SceneHelpers sh = new SceneHelpers();
TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000, configSource);
TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999, configSource);
SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, configSource, lscm);
SceneHelpers.SetupSceneModules(sceneA, configSource, etmA, xEngineA);
SceneHelpers.SetupSceneModules(sceneB, configSource, etmB, xEngineB);
sceneA.StartScripts();
sceneB.StartScripts();
SceneObjectGroup soSceneA = SceneHelpers.AddSceneObject(sceneA, 1, userId, "so1-", sceneObjectIdTail);
soSceneA.AbsolutePosition = new Vector3(128, 10, 20);
string soSceneAName = soSceneA.Name;
string scriptItemSceneAName = "script1";
// CREATE SCRIPT TODO
InventoryItemBase scriptItemSceneA = new InventoryItemBase();
// itemTemplate.ID = itemId;
scriptItemSceneA.Name = scriptItemSceneAName;
scriptItemSceneA.Folder = soSceneA.UUID;
scriptItemSceneA.InvType = (int)InventoryType.LSL;
AutoResetEvent chatEvent = new AutoResetEvent(false);
OSChatMessage messageReceived = null;
sceneA.EventManager.OnChatFromWorld += (s, m) => { messageReceived = m; chatEvent.Set(); };
sceneA.RezNewScript(userId, scriptItemSceneA,
@"integer c = 0;
default
{
state_entry()
{
llSay(0, ""Script running"");
}
changed(integer change)
{
llSay(0, ""Changed"");
}
touch_start(integer n)
{
c = c + 1;
llSay(0, (string)c);
}
}");
chatEvent.WaitOne(60000);
Assert.That(messageReceived, Is.Not.Null, "No chat message received.");
Assert.That(messageReceived.Message, Is.EqualTo("Script running"));
{
// XXX: Should not be doing this so directly. Should call some variant of EventManager.touch() instead.
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = userId;
det[0].Populate(sceneA);
EventParams ep = new EventParams("touch_start", new Object[] { new LSL_Types.LSLInteger(1) }, det);
messageReceived = null;
chatEvent.Reset();
xEngineA.PostObjectEvent(soSceneA.LocalId, ep);
chatEvent.WaitOne(60000);
Assert.That(messageReceived.Message, Is.EqualTo("1"));
}
AutoResetEvent chatEventB = new AutoResetEvent(false);
sceneB.EventManager.OnChatFromWorld += (s, m) => { messageReceived = m; chatEventB.Set(); };
messageReceived = null;
chatEventB.Reset();
// Cross with a negative value
soSceneA.AbsolutePosition = new Vector3(128, -10, 20);
chatEventB.WaitOne(60000);
Assert.That(messageReceived, Is.Not.Null, "No Changed message received.");
Assert.That(messageReceived.Message, Is.Not.Null, "Changed message without content");
Assert.That(messageReceived.Message, Is.EqualTo("Changed"));
// TEST sending event to moved prim and output
{
SceneObjectGroup soSceneB = sceneB.GetSceneObjectGroup(soSceneAName);
TaskInventoryItem scriptItemSceneB = soSceneB.RootPart.Inventory.GetInventoryItem(scriptItemSceneAName);
// XXX: Should not be doing this so directly. Should call some variant of EventManager.touch() instead.
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = userId;
det[0].Populate(sceneB);
EventParams ep = new EventParams("touch_start", new Object[] { new LSL_Types.LSLInteger(1) }, det);
Thread.Sleep(250); // wait for other change messages to pass
messageReceived = null;
chatEventB.Reset();
xEngineB.PostObjectEvent(soSceneB.LocalId, ep);
chatEventB.WaitOne(60000);
Assert.That(messageReceived.Message, Is.EqualTo("2"));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Patterns;
using Xunit;
namespace Microsoft.AspNetCore.Routing.Matching
{
public class RouteEndpointComparerTest
{
[Fact]
public void Compare_PrefersOrder_IfDifferent()
{
// Arrange
var endpoint1 = CreateEndpoint("/", order: 1);
var endpoint2 = CreateEndpoint("/api/foo", order: -1);
var comparer = CreateComparer();
// Act
var result = comparer.Compare(endpoint1, endpoint2);
// Assert
Assert.Equal(1, result);
}
[Fact]
public void Compare_PrefersPrecedence_IfOrderIsSame()
{
// Arrange
var endpoint1 = CreateEndpoint("/api/foo", order: 1);
var endpoint2 = CreateEndpoint("/", order: 1);
var comparer = CreateComparer();
// Act
var result = comparer.Compare(endpoint1, endpoint2);
// Assert
Assert.Equal(1, result);
}
[Fact]
public void Compare_PrefersPolicy_IfPrecedenceIsSame()
{
// Arrange
var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/", order: 1);
var comparer = CreateComparer(new TestMetadata1Policy());
// Act
var result = comparer.Compare(endpoint1, endpoint2);
// Assert
Assert.Equal(-1, result);
}
[Fact]
public void Compare_PrefersSecondPolicy_IfFirstPolicyIsSame()
{
// Arrange
var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/", order: 1, new TestMetadata1(), new TestMetadata2());
var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());
// Act
var result = comparer.Compare(endpoint1, endpoint2);
// Assert
Assert.Equal(1, result);
}
[Fact]
public void Compare_PrefersTemplate_IfOtherCriteriaIsSame()
{
// Arrange
var endpoint1 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/bar", order: 1, new TestMetadata1());
var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());
// Act
var result = comparer.Compare(endpoint1, endpoint2);
// Assert
Assert.True(result > 0);
}
[Fact]
public void Compare_ReturnsZero_WhenIdentical()
{
// Arrange
var endpoint1 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());
// Act
var result = comparer.Compare(endpoint1, endpoint2);
// Assert
Assert.Equal(0, result);
}
[Fact]
public void Equals_NotEqual_IfOrderDifferent()
{
// Arrange
var endpoint1 = CreateEndpoint("/", order: 1);
var endpoint2 = CreateEndpoint("/api/foo", order: -1);
var comparer = CreateComparer();
// Act
var result = comparer.Equals(endpoint1, endpoint2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_NotEqual_IfPrecedenceDifferent()
{
// Arrange
var endpoint1 = CreateEndpoint("/api/foo", order: 1);
var endpoint2 = CreateEndpoint("/", order: 1);
var comparer = CreateComparer();
// Act
var result = comparer.Equals(endpoint1, endpoint2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_NotEqual_IfFirstPolicyDifferent()
{
// Arrange
var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/", order: 1);
var comparer = CreateComparer(new TestMetadata1Policy());
// Act
var result = comparer.Equals(endpoint1, endpoint2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_NotEqual_IfSecondPolicyDifferent()
{
// Arrange
var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/", order: 1, new TestMetadata1(), new TestMetadata2());
var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());
// Act
var result = comparer.Equals(endpoint1, endpoint2);
// Assert
Assert.False(result);
}
[Fact]
public void Equals_Equals_WhenTemplateIsDifferent()
{
// Arrange
var endpoint1 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
var endpoint2 = CreateEndpoint("/bar", order: 1, new TestMetadata1());
var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());
// Act
var result = comparer.Equals(endpoint1, endpoint2);
// Assert
Assert.True(result);
}
[Fact]
public void Sort_MoreSpecific_FirstInList()
{
// Arrange
var endpoint1 = CreateEndpoint("/foo", order: -1);
var endpoint2 = CreateEndpoint("/bar/{baz}", order: -1);
var endpoint3 = CreateEndpoint("/bar", order: 0, new TestMetadata1());
var endpoint4 = CreateEndpoint("/foo", order: 0, new TestMetadata2());
var endpoint5 = CreateEndpoint("/foo", order: 0);
var endpoint6 = CreateEndpoint("/a{baz}", order: 0, new TestMetadata1(), new TestMetadata2());
var endpoint7 = CreateEndpoint("/bar{baz}", order: 0, new TestMetadata1(), new TestMetadata2());
// Endpoints listed in reverse of the desired order.
var list = new List<RouteEndpoint>() { endpoint7, endpoint6, endpoint5, endpoint4, endpoint3, endpoint2, endpoint1, };
var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());
// Act
list.Sort(comparer);
// Assert
Assert.Collection(
list,
e => Assert.Same(endpoint1, e),
e => Assert.Same(endpoint2, e),
e => Assert.Same(endpoint3, e),
e => Assert.Same(endpoint4, e),
e => Assert.Same(endpoint5, e),
e => Assert.Same(endpoint6, e),
e => Assert.Same(endpoint7, e));
}
[Fact]
public void Compare_PatternOrder_OrdinalIgnoreCaseSort()
{
// Arrange
var endpoint1 = CreateEndpoint("/I", order: 0);
var endpoint2 = CreateEndpoint("/i", order: 0);
var endpoint3 = CreateEndpoint("/\u0131", order: 0); // Turkish lowercase i
var list = new List<RouteEndpoint>() { endpoint1, endpoint2, endpoint3 };
var comparer = CreateComparer();
// Act
list.Sort(comparer);
// Assert
Assert.Collection(
list,
e => Assert.Same(endpoint1, e),
e => Assert.Same(endpoint2, e),
e => Assert.Same(endpoint3, e));
}
private static RouteEndpoint CreateEndpoint(string template, int order, params object[] metadata)
{
return new RouteEndpoint(
TestConstants.EmptyRequestDelegate,
RoutePatternFactory.Parse(template),
order,
new EndpointMetadataCollection(metadata),
"test: " + template);
}
private static EndpointComparer CreateComparer(params IEndpointComparerPolicy[] policies)
{
return new EndpointComparer(policies);
}
private class TestMetadata1
{
}
private class TestMetadata1Policy : IEndpointComparerPolicy
{
public IComparer<Endpoint> Comparer => EndpointMetadataComparer<TestMetadata1>.Default;
}
private class TestMetadata2
{
}
private class TestMetadata2Policy : IEndpointComparerPolicy
{
public IComparer<Endpoint> Comparer => EndpointMetadataComparer<TestMetadata2>.Default;
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using System.Linq;
namespace RefactoringEssentials.CSharp.Diagnostics
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
[NotPortedYet]
public class InconsistentNamingAnalyzer : DiagnosticAnalyzer
{
internal const string DiagnosticId = "InconsistentNaming";
const string Description = "Inconsistent Naming";
const string MessageFormat = "";
const string Category = DiagnosticAnalyzerCategories.ConstraintViolations;
static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning, true, "Name doesn't match the defined style for this entity.");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
public override void Initialize(AnalysisContext context)
{
//context.RegisterSyntaxNodeAction(
// (nodeContext) => {
// Diagnostic diagnostic;
// if (TryGetDiagnostic (nodeContext, out diagnostic)) {
// nodeContext.ReportDiagnostic(diagnostic);
// }
// },
// new SyntaxKind[] { SyntaxKind.None }
//);
}
static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
{
diagnostic = default(Diagnostic);
if (nodeContext.IsFromGeneratedCode())
return false;
//var node = nodeContext.Node as ;
//diagnostic = Diagnostic.Create (descriptor, node.GetLocation ());
//return true;
return false;
}
// class GatherVisitor : GatherVisitorBase<InconsistentNamingAnalyzer>
// {
// //readonly NamingConventionService service;
// public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
// : base (semanticModel, addDiagnostic, cancellationToken)
// {
// // service = (NamingConventionService)ctx.GetService (typeof (NamingConventionService));
// }
//// void CheckName(TypeDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// TypeResolveResult resolveResult = ctx.Resolve(node) as TypeResolveResult;
//// if (resolveResult == null)
//// return;
//// var type = resolveResult.Type;
//// if (type.DirectBaseTypes.Any(t => t.FullName == "System.Attribute")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomAttributes, identifier, accessibilty)) {
//// return;
//// }
//// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.EventArgs")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomEventArgs, identifier, accessibilty)) {
//// return;
//// }
//// } else if (type.DirectBaseTypes.Any(t => t.FullName == "System.Exception")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.CustomExceptions, identifier, accessibilty)) {
//// return;
//// }
//// }
////
//// var typeDef = type.GetDefinition();
//// if (typeDef != null && typeDef.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestFixtureAttribute")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestType, identifier, accessibilty)) {
//// return;
//// }
//// }
////
//// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty);
//// }
////
//// void CheckName(MethodDeclaration node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// ResolveResult resolveResult = null;
//// if (node != null && node.Attributes.Any ())
//// resolveResult = ctx.Resolve(node);
////
//// if (resolveResult is MemberResolveResult) {
//// var member = ((MemberResolveResult)resolveResult).Member;
//// if (member.SymbolKind == SymbolKind.Method && member.Attributes.Any(attr => attr.AttributeType.FullName == "NUnit.Framework.TestAttribute")) {
//// if (CheckNamedResolveResult(resolveResult, node, AffectedEntity.TestMethod, identifier, accessibilty)) {
//// return;
//// }
//// }
//// }
////
//// CheckNamedResolveResult(resolveResult, node, entity, identifier, accessibilty);
//// }
////
//// void CheckName(AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// CheckNamedResolveResult(null, node, entity, identifier, accessibilty);
//// }
////
//// bool CheckNamedResolveResult(ResolveResult resolveResult, AstNode node, AffectedEntity entity, Identifier identifier, Modifiers accessibilty)
//// {
//// bool wasHandled = false;
//// foreach (var rule in service.Rules) {
//// if (!rule.AffectedEntity.HasFlag(entity)) {
//// continue;
//// }
//// if (!rule.VisibilityMask.HasFlag(accessibilty)) {
//// continue;
//// }
//// if (!rule.IncludeInstanceMembers || !rule.IncludeStaticEntities) {
//// EntityDeclaration typeSystemEntity;
//// if (node is VariableInitializer) {
//// typeSystemEntity = node.Parent as EntityDeclaration;
//// } else {
//// typeSystemEntity = node as EntityDeclaration;
//// }
//// if (!rule.IncludeInstanceMembers) {
//// if (typeSystemEntity == null || !typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) {
//// continue;
//// }
//// }
//// if (!rule.IncludeStaticEntities) {
//// if (typeSystemEntity == null || typeSystemEntity.HasModifier (Modifiers.Static) || typeSystemEntity.HasModifier (Modifiers.Sealed)) {
//// continue;
//// }
//// }
//// }
////
//// wasHandled = true;
//// if (!rule.IsValid(identifier.Name)) {
//// IList<string> suggestedNames;
//// var msg = rule.GetErrorMessage(ctx, identifier.Name, out suggestedNames);
//// var actions = new List<CodeAction>(suggestedNames.Select(n => new CodeAction(string.Format(ctx.TranslateString("Rename to '{0}'"), n), (Script script) => {
//// if (resolveResult == null)
//// resolveResult = ctx.Resolve (node);
//// if (resolveResult is MemberResolveResult) {
//// script.Rename(((MemberResolveResult)resolveResult).Member, n);
//// } else if (resolveResult is TypeResolveResult) {
//// var def = resolveResult.Type.GetDefinition();
//// if (def != null) {
//// script.Rename(def, n);
//// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) {
//// script.Rename((ITypeParameter)resolveResult.Type, n);
//// }
//// } else if (resolveResult is LocalResolveResult) {
//// script.Rename(((LocalResolveResult)resolveResult).Variable, n);
//// } else if (resolveResult is NamespaceResolveResult) {
//// script.Rename(((NamespaceResolveResult)resolveResult).Namespace, n);
//// } else {
//// script.Replace(identifier, Identifier.Create(n));
//// }
//// }, identifier)));
////
//// if (entity != AffectedEntity.Label) {
//// actions.Add(new CodeAction(string.Format(ctx.TranslateString("Rename '{0}'..."), identifier.Name), (Script script) => {
//// if (resolveResult == null)
//// resolveResult = ctx.Resolve (node);
//// if (resolveResult is MemberResolveResult) {
//// script.Rename(((MemberResolveResult)resolveResult).Member);
//// } else if (resolveResult is TypeResolveResult) {
//// var def = resolveResult.Type.GetDefinition();
//// if (def != null) {
//// script.Rename(def);
//// } else if (resolveResult.Type.Kind == TypeKind.TypeParameter) {
//// script.Rename((ITypeParameter)resolveResult.Type);
//// }
//// } else if (resolveResult is LocalResolveResult) {
//// script.Rename(((LocalResolveResult)resolveResult).Variable);
//// } else if (resolveResult is NamespaceResolveResult) {
//// script.Rename(((NamespaceResolveResult)resolveResult).Namespace);
//// }
//// }, identifier));
//// }
////
//// AddDiagnosticAnalyzer(new CodeIssue(identifier, msg, actions));
//// }
//// }
//// return wasHandled;
//// }
////
//// public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
//// {
//// base.VisitNamespaceDeclaration(namespaceDeclaration);
//// var type = namespaceDeclaration.NamespaceName;
//// while (type is MemberType) {
//// var mt = (MemberType)type;
//// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, mt.MemberNameToken, Modifiers.None);
//// type = mt.Target;
//// }
//// if (type is SimpleType)
//// CheckNamedResolveResult(null, namespaceDeclaration, AffectedEntity.Namespace, ((SimpleType)type).IdentifierToken, Modifiers.None);
//// }
////
//// Modifiers GetAccessibiltiy(EntityDeclaration decl, Modifiers defaultModifier)
//// {
//// var accessibility = (decl.Modifiers & Modifiers.VisibilityMask);
//// if (accessibility == Modifiers.None) {
//// return defaultModifier;
//// }
//// return accessibility;
//// }
////
//// public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
//// {
//// base.VisitTypeDeclaration(typeDeclaration);
//// AffectedEntity entity;
//// switch (typeDeclaration.ClassType) {
//// case ClassType.Class:
//// entity = AffectedEntity.Class;
//// break;
//// case ClassType.Struct:
//// entity = AffectedEntity.Struct;
//// break;
//// case ClassType.Interface:
//// entity = AffectedEntity.Interface;
//// break;
//// case ClassType.Enum:
//// entity = AffectedEntity.Enum;
//// break;
//// default:
//// throw new System.ArgumentOutOfRangeException();
//// }
//// CheckName(typeDeclaration, entity, typeDeclaration.NameToken, GetAccessibiltiy(typeDeclaration, typeDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal));
//// }
////
//// public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
//// {
//// base.VisitDelegateDeclaration(delegateDeclaration);
//// CheckName(delegateDeclaration, AffectedEntity.Delegate, delegateDeclaration.NameToken, GetAccessibiltiy(delegateDeclaration, delegateDeclaration.Parent is TypeDeclaration ? Modifiers.Private : Modifiers.Internal));
//// }
////
//// public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
//// {
//// if (propertyDeclaration.Modifiers.HasFlag (Modifiers.Override))
//// return;
//// base.VisitPropertyDeclaration(propertyDeclaration);
//// CheckName(propertyDeclaration, AffectedEntity.Property, propertyDeclaration.NameToken, GetAccessibiltiy(propertyDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
//// {
//// if (indexerDeclaration.Modifiers.HasFlag(Modifiers.Override)) {
//// var rr = ctx.Resolve (indexerDeclaration) as MemberResolveResult;
//// if (rr == null)
//// return;
//// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface);
//// var method = baseType != null ? baseType.GetProperties (m => m.IsIndexer && m.IsOverridable && m.Parameters.Count == indexerDeclaration.Parameters.Count).FirstOrDefault () : null;
//// if (method == null)
//// return;
//// int i = 0;
//// foreach (var par in indexerDeclaration.Parameters) {
//// if (method.Parameters[i++].Name != par.Name) {
//// par.AcceptVisitor (this);
//// }
//// }
//// return;
//// }
//// base.VisitIndexerDeclaration(indexerDeclaration);
//// }
////
//// public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
//// {
//// if (methodDeclaration.Modifiers.HasFlag(Modifiers.Override)) {
//// var rr = ctx.Resolve (methodDeclaration) as MemberResolveResult;
//// if (rr == null)
//// return;
//// var baseType = rr.Member.DeclaringType.DirectBaseTypes.FirstOrDefault (t => t.Kind != TypeKind.Interface);
//// var method = baseType != null ? baseType.GetMethods (m => m.Name == rr.Member.Name && m.IsOverridable && m.Parameters.Count == methodDeclaration.Parameters.Count).FirstOrDefault () : null;
//// if (method == null)
//// return;
//// int i = 0;
//// foreach (var par in methodDeclaration.Parameters) {
//// if (method.Parameters[i++].Name != par.Name) {
//// par.AcceptVisitor (this);
//// }
//// }
////
//// return;
//// }
//// base.VisitMethodDeclaration(methodDeclaration);
////
//// CheckName(methodDeclaration, methodDeclaration.Modifiers.HasFlag(Modifiers.Async) ? AffectedEntity.AsyncMethod : AffectedEntity.Method, methodDeclaration.NameToken, GetAccessibiltiy(methodDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
//// {
//// base.VisitFieldDeclaration(fieldDeclaration);
//// var entity = AffectedEntity.Field;
//// if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) {
//// entity = AffectedEntity.ConstantField;
//// } else if (fieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) {
//// entity = AffectedEntity.ReadonlyField;
//// }
//// foreach (var init in fieldDeclaration.Variables) {
//// CheckName(init, entity, init.NameToken, GetAccessibiltiy(fieldDeclaration, Modifiers.Private));
//// }
//// }
////
//// public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
//// {
//// base.VisitFixedFieldDeclaration(fixedFieldDeclaration);
//// var entity = AffectedEntity.Field;
//// if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Const)) {
//// entity = AffectedEntity.ConstantField;
//// } else if (fixedFieldDeclaration.Modifiers.HasFlag(Modifiers.Readonly)) {
//// entity = AffectedEntity.ReadonlyField;
//// }
//// CheckName(fixedFieldDeclaration, entity, fixedFieldDeclaration.NameToken, GetAccessibiltiy(fixedFieldDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitEventDeclaration(EventDeclaration eventDeclaration)
//// {
//// base.VisitEventDeclaration(eventDeclaration);
//// foreach (var init in eventDeclaration.Variables) {
//// CheckName(init, AffectedEntity.Event, init.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private));
//// }
//// }
////
//// public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
//// {
//// if (eventDeclaration.Modifiers.HasFlag (Modifiers.Override))
//// return;
//// base.VisitCustomEventDeclaration(eventDeclaration);
//// CheckName(eventDeclaration, AffectedEntity.Event, eventDeclaration.NameToken, GetAccessibiltiy(eventDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
//// {
//// base.VisitEnumMemberDeclaration(enumMemberDeclaration);
//// CheckName(enumMemberDeclaration, AffectedEntity.EnumMember, enumMemberDeclaration.NameToken, GetAccessibiltiy(enumMemberDeclaration, Modifiers.Private));
//// }
////
//// public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
//// {
//// base.VisitParameterDeclaration(parameterDeclaration);
//// CheckNamedResolveResult(null, parameterDeclaration, parameterDeclaration.Parent is LambdaExpression ? AffectedEntity.LambdaParameter : AffectedEntity.Parameter, parameterDeclaration.NameToken, Modifiers.None);
//// }
////
//// public override void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
//// {
//// base.VisitTypeParameterDeclaration(typeParameterDeclaration);
//// CheckNamedResolveResult(null, typeParameterDeclaration, AffectedEntity.TypeParameter, typeParameterDeclaration.NameToken, Modifiers.None);
//// }
////
//// public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
//// {
//// base.VisitVariableDeclarationStatement(variableDeclarationStatement);
//// var entity = variableDeclarationStatement.Modifiers.HasFlag(Modifiers.Const) ? AffectedEntity.LocalConstant : AffectedEntity.LocalVariable;
//// foreach (var init in variableDeclarationStatement.Variables) {
//// CheckNamedResolveResult(null, init, entity, init.NameToken, Modifiers.None);
//// }
//// }
////
//// public override void VisitLabelStatement(LabelStatement labelStatement)
//// {
//// base.VisitLabelStatement(labelStatement);
//// CheckNamedResolveResult(null, labelStatement, AffectedEntity.Label, labelStatement.LabelToken, Modifiers.None);
//// }
// }
}
[ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
public class InconsistentNamingIssueFixProvider : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
return ImmutableArray.Create(InconsistentNamingAnalyzer.DiagnosticId);
}
}
public override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public async override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var span = context.Span;
var diagnostics = context.Diagnostics;
var root = await document.GetSyntaxRootAsync(cancellationToken);
var diagnostic = diagnostics.First();
var node = root.FindNode(context.Span);
//if (!node.IsKind(SyntaxKind.BaseList))
// continue;
var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, diagnostic.GetMessage(), document.WithSyntaxRoot(newRoot)), diagnostic);
}
}
}
| |
using System;
using System.Data;
using PCSComUtils.Common;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
namespace PCSComMaterials.Plan.BO
{
public interface IWorkDayCalendarBO
{
int AddWDCalendar(object pobjMaster, DataSet pdstData);
object GetWDCalendarMaster(int pintYear, int pintCCNID);
DataSet GetDetailByMasterID(int pintMasterID);
void UpdateWDCalendar(object pobjMaster, DataSet pdstData);
}
/// <summary>
/// Summary description for WorkDayCalendarBO.
/// </summary>
public class WorkDayCalendarBO : IWorkDayCalendarBO
{
public WorkDayCalendarBO()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Insert a new record into database
/// </summary>
public void Add(object pObjectDetail)
{
throw new NotImplementedException();
}
/// <summary>
/// Add Master & Detail
/// </summary>
/// <param name="pobjMaster"></param>
/// <param name="pdstData"></param>
public int AddWDCalendar(object pobjMaster, DataSet pdstData)
{
try
{
//add Master
int intMasterID = new MST_WorkingDayMasterDS().AddAndReturnID(pobjMaster);
//add Detail
foreach (DataRow drow in pdstData.Tables[0].Rows)
{
if (drow.RowState == DataRowState.Added)
{
drow[MST_WorkingDayDetailTable.WORKINGDAYMASTERID_FLD] = intMasterID;
}
}
new MST_WorkingDayDetailDS().UpdateDataSet(pdstData);
return intMasterID;
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Update Master & Detail
/// </summary>
/// <param name="pobjMaster"></param>
/// <param name="pdstData"></param>
public void UpdateWDCalendar(object pobjMaster, DataSet pdstData)
{
try
{
//add Master
new MST_WorkingDayMasterDS().Update(pobjMaster);
//add Detail
foreach (DataRow drow in pdstData.Tables[0].Rows)
{
if (drow.RowState == DataRowState.Added)
{
drow[MST_WorkingDayDetailTable.WORKINGDAYMASTERID_FLD] = ((MST_WorkingDayMasterVO) pobjMaster).WorkingDayMasterID;
}
}
new MST_WorkingDayDetailDS().UpdateDataSet(pdstData);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Delete record by condition
/// </summary>
public void Delete(object pObjectVO)
{
try
{
//delete Detail
DataSet dstDataDetail = GetDetailByMasterID(((MST_WorkingDayMasterVO) pObjectVO).WorkingDayMasterID);
foreach (DataRow drow in dstDataDetail.Tables[0].Rows)
{
drow.Delete();
}
new MST_WorkingDayDetailDS().UpdateDataSet(dstDataDetail);
//delete Master
new MST_WorkingDayMasterDS().Delete(((MST_WorkingDayMasterVO) pObjectVO).WorkingDayMasterID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Get WorkingDayDetail by MasterID
/// </summary>
/// <param name="pintMasterID"></param>
/// <returns></returns>
public DataSet GetDetailByMasterID(int pintMasterID)
{
const string DAYOFWEEK = "Day";
try
{
DataSet dstReturn = new MST_WorkingDayDetailDS().GetDetailByMasterID(pintMasterID);
foreach (DataRow drow in dstReturn.Tables[0].Rows)
{
drow[DAYOFWEEK] = DateTime.Parse(drow[MST_WorkingDayDetailTable.OFFDAY_FLD].ToString().Trim()).DayOfWeek;
}
dstReturn.AcceptChanges();
return dstReturn;
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Get the object information by ID of VO class
/// </summary>
public object GetObjectVO(int pintID, string VOclass)
{
throw new NotImplementedException();
}
/// <summary>
/// Get WorkingDayMaster by Year and CCN
/// </summary>
/// <param name="pintYear"></param>
/// <param name="pintCCNID"></param>
/// <returns></returns>
public object GetWDCalendarMaster(int pintYear, int pintCCNID)
{
try
{
return new MST_WorkingDayMasterDS().GetWDCalendarMaster(pintYear, pintCCNID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Return the DataSet (list of record) by inputing the FieldList and Condition
/// </summary>
public void UpdateDataSet(DataSet dstData)
{
throw new NotImplementedException();
}
/// <summary>
/// Update into Database
/// </summary>
public void Update(object pObjectDetail)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using ExamplesFx.ColorCode;
using FileHelpers;
using FileHelpers.Dynamic;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace FileHelpers.WizardApp
{
/// <summary>
/// Load some data and test against the built class
/// </summary>
public partial class frmDataPreview : Form
{
#region Work areas and parameters
private WizardInfo info = new WizardInfo();
#endregion
public frmDataPreview(string data, NetLanguage language)
{
InitializeComponent();
ShowCode(data, language);
//sdClassOut.Text = data;
cboClassLanguage.Items.Clear();
cboClassLanguage.Items.Add(NetLanguage.CSharp);
cboClassLanguage.Items.Add(NetLanguage.VbNet);
cboClassLanguage.SelectedItem = language;
}
private string mLastCode;
private void ShowCode(string code, NetLanguage language)
{
mLastCode = code;
browserCode.DocumentText = "";
var colorizer = new CodeColorizer();
switch (language) {
case NetLanguage.CSharp:
browserCode.DocumentText = GetDefaultCss() + colorizer.Colorize(code, Languages.CSharp);
break;
case NetLanguage.VbNet:
browserCode.DocumentText = GetDefaultCss() + colorizer.Colorize(code, Languages.VbDotNet);
break;
default:
throw new ArgumentOutOfRangeException("language");
}
}
private string GetDefaultCss()
{
return
@"
<style type=""text/css"">
pre {
/*background-color: #EEF3F9;
border: 1px dashed grey;*/
font-family: Consolas,""Courier New"",Courier,Monospace !important;
font-size: 12px !important;
margin-top: 0;
padding: 6px 6px 6px 6px;
/*height: auto;
overflow: auto;
width: 100% !important;*/
}
</style>
";
}
public bool AutoRunTest { get; set; }
public bool HasHeaders { get; set; }
private void cmdReadFile_Click(object sender, EventArgs e) {}
private void cmdReadTest_Click(object sender, EventArgs e)
{
RunTest();
}
private void RunTest()
{
try {
string classStr = mLastCode;
var selected = cboClassLanguage.SelectedItem is NetLanguage
? (NetLanguage) cboClassLanguage.SelectedItem
: NetLanguage.CSharp;
var type = ClassBuilder.ClassFromString(classStr, selected);
FileHelperEngine engine = new FileHelperEngine (type);
engine.ErrorMode = ErrorMode.SaveAndContinue;
DataTable dt = engine.ReadStringAsDT (txtInput.Text);
if (engine.ErrorManager.Errors.Length > 0)
{
dt = new DataTable ();
dt.Columns.Add ("LineNumber");
dt.Columns.Add ("ExceptionInfo");
dt.Columns.Add ("RecordString");
foreach (var e in engine.ErrorManager.Errors)
{
dt.Rows.Add (e.LineNumber, e.ExceptionInfo.Message, e.RecordString);
}
dgPreview.DataSource = dt;
MessageBox.Show ("Error Parsing the Sample Data",
"Layout errors detected",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
dgPreview.DataSource = dt;
lblResults.Text = dt.Rows.Count.ToString () + " Rows - " + dt.Columns.Count.ToString () + " Fields";
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Error Compiling Class", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
ShowCode(Clipboard.GetText(TextDataFormat.Text), NetLanguage.CSharp);
}
private void cboClassLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cboClassLanguage.SelectedIndex) {
case 0:
ShowCode(mLastCode, NetLanguage.CSharp);
break;
case 1:
ShowCode(mLastCode, NetLanguage.VbNet);
break;
default:
break;
}
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
dlgOpenTest.FileName = "";
//try {
// if (RegConfig.HasValue("WizardOpenTest"))
// dlgOpenTest.InitialDirectory = RegConfig.GetStringValue("WizardOpenTest", "");
//}
//catch {}
dlgOpenTest.Title = "Open FileHelpers Class";
dlgOpenTest.Filter = "Dynamic Record File (*.fhw;*.xml)|*.fhw;*.xml|All Files|*.*";
if (dlgOpenTest.ShowDialog() != DialogResult.OK)
return;
RegConfig.SetStringValue("WizardOpenTest", Path.GetDirectoryName(dlgOpenTest.FileName));
ClassBuilder sb = ClassBuilder.LoadFromXml(dlgOpenTest.FileName);
ShowCode(sb.GetClassSourceCode(NetLanguage.CSharp), NetLanguage.CSharp);
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
dlgOpenTest.FileName = "";
//try {
// if (RegConfig.HasValue("WizardOpenTest"))
// dlgOpenTest.InitialDirectory = RegConfig.GetStringValue("WizardOpenTest", "");
//}
//catch {}
dlgOpenTest.Title = "Open Class Source Code";
dlgOpenTest.Filter = "Class source code files (*.cs;*.vb;*.txt)|*.txt;*.cs;*.vb|All Files|*.*";
if (dlgOpenTest.ShowDialog() != DialogResult.OK)
return;
RegConfig.SetStringValue("WizardOpenTest", Path.GetDirectoryName(dlgOpenTest.FileName));
ShowCode(File.ReadAllText(dlgOpenTest.FileName), NetLanguage.CSharp);
}
private void frmDataPreview_Load(object sender, EventArgs e)
{
if (cboClassLanguage.SelectedIndex < 0)
cboClassLanguage.SelectedIndex = 0;
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
dlgOpenTest.FileName = "";
try {
if (RegConfig.HasValue("WizardOpenTestData"))
dlgOpenTest.InitialDirectory = RegConfig.GetStringValue("WizardOpenTestData", "");
}
catch {}
dlgOpenTest.Title = "Open sample data file";
dlgOpenTest.Filter = "Flat Files (*.txt;*.csv;*.prn;*.dat)|*.txt;*.csv;*.prn;*.dat|All Files|*.*";
if (dlgOpenTest.ShowDialog() != DialogResult.OK)
return;
RegConfig.SetStringValue("WizardOpenTestData", Path.GetDirectoryName(dlgOpenTest.FileName));
txtInput.Text = File.ReadAllText(dlgOpenTest.FileName);
}
private void txtClearData_Click(object sender, EventArgs e)
{
txtInput.Text = string.Empty;
}
private void txtPasteData_Click(object sender, EventArgs e)
{
txtInput.Text = Clipboard.GetText(TextDataFormat.Text);
}
private void frmDataPreview_Activated(object sender, EventArgs e)
{
if (AutoRunTest) {
AutoRunTest = false;
Application.DoEvents();
RunTest();
ShowCode (mLastCode, NetLanguage.CSharp);
}
}
}
}
| |
/*************************************************************************
* Project: Dot Map
* Copyright: Shropshire Council (c) 2007
* Purpose: An implementation of the data provider using the SQL and the
* application data block. The public methods are the interesting
* part. The rest is pretty much as is from the example code.
* $Author: $
* $Date: 2009-12-10 11:02:25 +0000 (Thu, 10 Dec 2009) $
* $Revision: 92 $
* $HeadURL: https://sbp.svn.cloudforge.com/naturalshropshire/trunk/SCC.Modules.DotMap/Data/SqlDataProvider.cs $
************************************************************************/
using System;
using System.Data;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Framework.Providers;
using Microsoft.ApplicationBlocks.Data;
namespace SCC.Modules.DotMap.Data
{
public class SqlDataProvider : DataProvider
{
#region Private Members
private const string ProviderType = "data";
private const string ModuleQualifier = "SCC_";
private ProviderConfiguration _providerConfiguration = ProviderConfiguration.GetProviderConfiguration(ProviderType);
private string _connectionString;
private string _providerPath;
private string _objectQualifier;
private string _databaseOwner;
#endregion
#region Constructors
/// <summary>
/// Constructs new SqlDataProvider instance using the appropriate
/// connection information.
/// </summary>
public SqlDataProvider()
{
//Read the configuration specific information for this provider
Provider objProvider = (Provider)_providerConfiguration.Providers[_providerConfiguration.DefaultProvider];
//Read the attributes for this provider
if ((objProvider.Attributes["connectionStringName"] != "") && (System.Configuration.ConfigurationManager.AppSettings[objProvider.Attributes["connectionStringName"]] != ""))
{
_connectionString = System.Configuration.ConfigurationManager.AppSettings[objProvider.Attributes["connectionStringName"]];
}
else
{
_connectionString = objProvider.Attributes["connectionString"];
}
_providerPath = objProvider.Attributes["providerPath"];
_objectQualifier = objProvider.Attributes["objectQualifier"];
if ((_objectQualifier != "") && (_objectQualifier.EndsWith("_") == false))
{
_objectQualifier += "_";
}
_databaseOwner = objProvider.Attributes["databaseOwner"];
if ((_databaseOwner != "") && (_databaseOwner.EndsWith(".") == false))
{
_databaseOwner += ".";
}
}
#endregion
#region Properties
/// <summary>
/// Gets and sets the connection string
/// </summary>
public string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Gets and sets the Provider path
/// </summary>
public string ProviderPath
{
get { return _providerPath; }
}
/// <summary>
/// Gets and sets the Object qualifier
/// </summary>
public string ObjectQualifier
{
get { return _objectQualifier; }
}
/// <summary>
/// Gets and sets the database owner
/// </summary>
public string DatabaseOwner
{
get { return _databaseOwner; }
}
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private string GetFullyQualifiedName(string name)
{
return DatabaseOwner + ObjectQualifier + ModuleQualifier + name;
}
/// <summary>
/// Gets the value for the field or DbNull if field has "null" value
/// </summary>
/// <param name="Field">The field to evaluate</param>
/// <returns></returns>
private Object GetNull(Object Field)
{
return Null.GetNull(Field, DBNull.Value);
}
#endregion
#region Public Methods
/// <summary>
/// Get a list of the species for the module
/// </summary>
/// <param name="moduleId">The id of the current module</param>
/// <returns></returns>
public override IDataReader ListSpecies(int moduleId, string EnglishName, string LatinName)
{
// if (search.Length > 2) search = "%" + search;
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetSpeciesNames"),
moduleId,
EnglishName + "%",
LatinName + "%");
}
/// <summary>
///
/// </summary>
/// <param name="moduleId"></param>
/// <param name="latinName"></param>
/// <returns></returns>
public override IDataReader ListSightings(int moduleId, string latinName)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetSightings"),
moduleId,
latinName);
}
/// <summary>
/// Get all the sightings to be displayed on the map. The sightings list
/// does not contain duplicates for any given tetrad because the view
/// "vwSCC_DotMapTetrads" tetradizes the co-ordinates of the sightings
/// and ignores any identical ones.
/// </summary>
/// <param name="moduleId"></param>
/// <param name="latinName"></param>
public override void DeleteSightings(int moduleId, string latinName)
{
SqlHelper.ExecuteNonQuery(ConnectionString,
GetFullyQualifiedName("DotMapDeleteSightings"),
moduleId,
latinName);
}
/// <summary>
/// Add a species sighting to the database
///
/// The original data is retained. When used or displayed the data is
/// tetradized (the resolution is reduced to the
/// </summary>
/// <param name="portalId">The id of the website portal (starts at 0)</param>
/// <param name="moduleId">The id of the DotNetNuke module</param>
/// <param name="EnglishName">The English or common name of the species</param>
/// <param name="LatinName">The Latin name of the species</param>
/// <param name="YearSeen">The year as four digits (Common Era)</param>
/// <param name="GridX">Ordnance survey Eastings to 6 figures</param>
/// <param name="GridY">Ordnance survey Northings to 6 figures</param>
public override void AddSighting(int portalId, int moduleId, string EnglishName, string LatinName,
int YearSeen, int GridX, int GridY)
{
SqlHelper.ExecuteScalar(ConnectionString,
GetFullyQualifiedName("DotMapAddSighting"),
GetNull(portalId),
GetNull(moduleId),
GetNull(EnglishName),
GetNull(LatinName),
GetNull(YearSeen),
GetNull(GridX),
GetNull(GridY)).ToString();
}
/// <summary>
///
/// </summary>
/// <param name="LatinName"></param>
/// <param name="GridX"></param>
/// <param name="GridY"></param>
/// <returns></returns>
public override IDataReader SpeciesForTetrad(string LatinName, int GridX, int GridY)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetSpeciesForTetrad"),
LatinName,
GridX,
GridY);
}
public override IDataReader ModuleList(int portalId)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetModuleList"),
portalId);
}
/// <summary>
///
/// </summary>
/// <param name="GridX"></param>
/// <param name="GridY"></param>
/// <param name="moduleId"></param>
/// <returns></returns>
public override IDataReader ListSpeciesForTetrad(int GridX, int GridY, int moduleId)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetSpeciesListForTetrad"),
GridX,
GridY,
moduleId);
}
public override IDataReader SpeciesLists(int portalId)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetSpeciesLists"),
portalId);
}
public override IDataReader SpeciesInListForTetrad(int portalId, int SpeciesListId, int GridX, int GridY)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetSpeciesInListForTetrad"),
portalId,
SpeciesListId,
GridX,
GridY);
}
public override IDataReader ListTetrads(int portalId)
{
return (IDataReader)SqlHelper.ExecuteReader(ConnectionString,
GetFullyQualifiedName("DotMapGetTetradList"),
portalId);
}
public override string EnglishName(string LatinName)
{
return (string) SqlHelper.ExecuteScalar(ConnectionString, GetFullyQualifiedName("DotMapGetEnglishName"), LatinName);
}
public override string LatinName(string EnglishName)
{
return (string)SqlHelper.ExecuteScalar(ConnectionString, GetFullyQualifiedName("DotMapGetLatinName"), EnglishName);
}
#endregion
}
}
| |
using Braintree.Exceptions;
using NUnit.Framework;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Text.RegularExpressions;
using System.Linq;
using System.IO;
namespace Braintree.Tests.Integration
{
[TestFixture]
public class DisputeIntegrationTest
{
#if netcore
private static string BT_LOGO_PATH = "../../../../../test/fixtures/bt_logo.png";
#else
private static string BT_LOGO_PATH = "test/fixtures/bt_logo.png";
#endif
private BraintreeGateway gateway;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
}
[Test]
public void Accept_changesDisputeStatusToAccepted()
{
Dispute dispute = createSampleDispute();
var result = gateway.Dispute.Accept(dispute.Id);
Assert.IsTrue(result.IsSuccess());
Dispute finalizedDispute = gateway.Dispute.Find(dispute.Id).Target;
Assert.AreEqual(DisputeStatus.ACCEPTED, finalizedDispute.Status);
Dispute disputeFromTransaction = gateway.Transaction.Find(dispute.Transaction.Id).Disputes[0];
Assert.AreEqual(DisputeStatus.ACCEPTED, disputeFromTransaction.Status);
}
[Test]
#if netcore
public async Task AcceptAsync_changesDisputeStatusToAccepted()
#else
public void AcceptAsync_changesDisputeStatusToAccepted()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
var result = await gateway.Dispute.AcceptAsync(dispute.Id);
Assert.IsTrue(result.IsSuccess());
Result<Dispute> finalizedDisputeResult = await gateway.Dispute.FindAsync(dispute.Id);
Dispute finalizedDispute = finalizedDisputeResult.Target;
Assert.AreEqual(DisputeStatus.ACCEPTED, finalizedDispute.Status);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Accept_whenDisputeNotOpenErrors()
{
var result = gateway.Dispute.Accept("wells_dispute");
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_ACCEPT_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Disputes can only be accepted when they are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
[Test]
#if netcore
public async Task AcceptAsync_whenDisputeNotOpenErrors()
#else
public void AcceptAsync_whenDisputeNotOpenErrors()
{
Task.Run(async () =>
#endif
{
var result = await gateway.Dispute.AcceptAsync("wells_dispute");
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_ACCEPT_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Disputes can only be accepted when they are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Accept_throwsNotFoundExceptionWhenDisputeIsNotFound()
{
NotFoundException exception = Assert.Throws<NotFoundException>(() => gateway.Dispute.Accept("invalid-id"));
Assert.AreEqual(exception.Message, "dispute with id 'invalid-id' not found");
}
[Test]
#if netcore
public async Task AcceptAsync_throwsNotFoundExceptionWhenDisputeIsNotFound()
#else
public void AcceptAsync_throwsNotFoundExceptionWhenDisputeIsNotFound()
{
Task.Run(async () =>
#endif
{
try
{
await gateway.Dispute.AcceptAsync("invalid-id");
Assert.Fail("Expected Exception.");
}
catch (NotFoundException exception)
{
Assert.AreEqual(exception.Message, "dispute with id 'invalid-id' not found");
}
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddFileEvidence_addsEvidence()
{
DocumentUpload document = createSampleDocumentUpload();
Dispute dispute = createSampleDispute();
DisputeEvidence evidence = gateway.Dispute.AddFileEvidence(dispute.Id, document.Id).Target;
Assert.NotNull(evidence);
DisputeEvidence foundEvidence = gateway.Dispute.Find(dispute.Id).Target.Evidence[0];
Assert.Null(evidence.Category);
Assert.NotNull(foundEvidence);
}
[Test]
public void AddFileEvidence_addsEvidenceWithCategory()
{
DocumentUpload document = createSampleDocumentUpload();
Dispute dispute = createSampleDispute();
var fileEvidenceRequest = new FileEvidenceRequest
{
DocumentId = document.Id,
Category = "GENERAL",
};
DisputeEvidence evidence = gateway.Dispute.AddFileEvidence(dispute.Id, fileEvidenceRequest).Target;
Assert.NotNull(evidence);
DisputeEvidence foundEvidence = gateway.Dispute.Find(dispute.Id).Target.Evidence[0];
Assert.NotNull(evidence.Category);
Assert.AreEqual(evidence.Category, "GENERAL");
Assert.NotNull(foundEvidence);
}
[Test]
#if netcore
public async Task AddFileEvidenceAsync_addsEvidence()
#else
public void AddFileEvidenceAsync_addsEvidence()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
DocumentUpload document = await createSampleDocumentUploadAsync();
Result<DisputeEvidence> evidenceResult = await gateway.Dispute.AddFileEvidenceAsync(dispute.Id, document.Id);
Assert.NotNull(evidenceResult.Target);
Result<Dispute> foundResult = await gateway.Dispute.FindAsync(dispute.Id);
DisputeEvidence foundEvidence = foundResult.Target.Evidence[0];
Assert.NotNull(foundEvidence);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddFileEvidence_throwsNotFoundExceptionWhenDisputeOrDocumentIdIsNotFound()
{
NotFoundException exception = Assert.Throws<NotFoundException>(() => gateway.Dispute.AddFileEvidence("invalid-dispute-id", "invalid-document-id"));
Assert.AreEqual(exception.Message, "dispute with id 'invalid-dispute-id' not found");
}
[Test]
#if netcore
public async Task AddFileEvidenceAsync_throwsNotFoundExceptionWhenDisputeOrDocumentIdIsNotFound()
#else
public void AddFileEvidenceAsync_throwsNotFoundExceptionWhenDisputeOrDocumentIdIsNotFound()
{
Task.Run(async () =>
#endif
{
try
{
await gateway.Dispute.AddFileEvidenceAsync("invalid-dispute-id", "invalid-document-id");
Assert.Fail("Expected Exception.");
}
catch (NotFoundException exception)
{
Assert.AreEqual(exception.Message, "dispute with id 'invalid-dispute-id' not found");
}
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddFileEvidence_whenDisputeNotOpenErrors()
{
DocumentUpload document = createSampleDocumentUpload();
Dispute dispute = createSampleDispute();
gateway.Dispute.Accept(dispute.Id);
var result = gateway.Dispute.AddFileEvidence(dispute.Id, document.Id);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Evidence can only be attached to disputes that are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
[Test]
#if netcore
public async Task AddFileEvidenceAsync_whenDisputeNotOpenErrors()
#else
public void AddFileEvidenceAsync_whenDisputeNotOpenErrors()
{
Task.Run(async () =>
#endif
{
DocumentUpload document = await createSampleDocumentUploadAsync();
Dispute dispute = await createSampleDisputeAsync();
await gateway.Dispute.AcceptAsync(dispute.Id);
var result = await gateway.Dispute.AddFileEvidenceAsync(dispute.Id, document.Id);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Evidence can only be attached to disputes that are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddFileEvidence_failsToAddEvidenceWithUnSupportedCategory()
{
DocumentUpload document = createSampleDocumentUpload();
Dispute dispute = createSampleDispute();
FileEvidenceRequest request = new FileEvidenceRequest
{
Category = "NOTAREALCATEGORY",
DocumentId = document.Id,
};
var result = gateway.Dispute.AddFileEvidence(dispute.Id, request);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_CREATE_EVIDENCE_WITH_VALID_CATEGORY, result.Errors.ForObject("Dispute").OnField("Evidence")[0].Code);
}
[Test]
#if netcore
public async Task AddFileEvidenceAsync_failsToAddEvidenceWithUnsupportedCategory()
#else
public void AddFileEvidenceAsync_failsToAddEvidenceWithUnsupportedCategory()
{
Task.Run(async () =>
#endif
{
DocumentUpload document = await createSampleDocumentUploadAsync();
Dispute dispute = await createSampleDisputeAsync();
FileEvidenceRequest request = new FileEvidenceRequest
{
Category = "NOTAREALCATEGORY",
DocumentId = document.Id,
};
var result = await gateway.Dispute.AddFileEvidenceAsync(dispute.Id, request);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_CREATE_EVIDENCE_WITH_VALID_CATEGORY, result.Errors.ForObject("Dispute").OnField("Evidence")[0].Code);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
#if netcore
public async Task AddTextEvidenceAsync_addsTextEvidence()
#else
public void AddTextEvidenceAsync_addsTextEvidence()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
Result<DisputeEvidence> evidenceResult = await gateway.Dispute.AddTextEvidenceAsync(dispute.Id, "my text evidence");
DisputeEvidence evidence = evidenceResult.Target;
Assert.NotNull(evidence.Id);
Assert.NotNull(evidence.CreatedAt);
Assert.AreEqual("my text evidence", evidence.Comment);
Assert.Null(evidence.SentToProcessorAt);
Assert.Null(evidence.Url);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddTextEvidence_addsEvidenceWithCateogry()
{
Dispute dispute = createSampleDispute();
var textEvidenceRequest = new TextEvidenceRequest
{
Content = "my content",
Category = "DEVICE_ID",
};
DisputeEvidence evidence = gateway.Dispute.AddTextEvidence(dispute.Id, textEvidenceRequest).Target;
Assert.NotNull(evidence);
DisputeEvidence foundEvidence = gateway.Dispute.Find(dispute.Id).Target.Evidence[0];
Assert.NotNull(evidence.Category);
Assert.AreEqual(evidence.Category, "DEVICE_ID");
Assert.NotNull(foundEvidence);
}
[Test]
public void AddTextEvidence_failsToAddEvidenceWithUnSupportedCategory()
{
Dispute dispute = createSampleDispute();
TextEvidenceRequest request = new TextEvidenceRequest
{
Category = "NOTAREALCATEGORY",
Content = "evidence",
};
var result = gateway.Dispute.AddTextEvidence(dispute.Id, request);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_CREATE_EVIDENCE_WITH_VALID_CATEGORY, result.Errors.ForObject("Dispute").OnField("Evidence")[0].Code);
}
[Test]
#if netcore
public async Task AddTextEvidenceAsync_failsToAddEvidenceWithUnSupportedCategory()
#else
public void AddTextEvidenceAsync_failsToAddEvidenceWithUnSupportedCategory()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
TextEvidenceRequest request = new TextEvidenceRequest
{
Category = "NOTAREALCATEGORY",
Content = "evidence",
};
var result = await gateway.Dispute.AddTextEvidenceAsync(dispute.Id, request);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_CREATE_EVIDENCE_WITH_VALID_CATEGORY, result.Errors.ForObject("Dispute").OnField("Evidence")[0].Code);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddTextEvidence_throwsNotFoundExceptionWhenDisputeNotFound()
{
NotFoundException exception = Assert.Throws<NotFoundException>(() => gateway.Dispute.AddTextEvidence("invalid-dispute-id", "some comment"));
Assert.AreEqual(exception.Message, "Dispute with ID 'invalid-dispute-id' not found");
}
[Test]
#if netcore
public async Task AddTextEvidenceAsync_throwsNotFoundExceptionWhenDisputeNotFound()
#else
public void AddTextEvidenceAsync_throwsNotFoundExceptionWhenDisputeNotFound()
{
Task.Run(async () =>
#endif
{
try
{
await gateway.Dispute.AddTextEvidenceAsync("invalid-dispute-id", "some comment");
Assert.Fail("Expected Exception.");
}
catch (NotFoundException exception)
{
Assert.AreEqual(exception.Message, "Dispute with ID 'invalid-dispute-id' not found");
}
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddTextEvidence_whenDisputeNotOpenErrors()
{
Dispute dispute = createSampleDispute();
gateway.Dispute.Accept(dispute.Id);
var result = gateway.Dispute.AddTextEvidence(dispute.Id, "my text evidence");
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Evidence can only be attached to disputes that are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
[Test]
#if netcore
public async Task AddTextEvidenceAsync_whenDisputeNotOpenErrors()
#else
public void AddTextEvidenceAsync_whenDisputeNotOpenErrors()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
await gateway.Dispute.AcceptAsync(dispute.Id);
var result = await gateway.Dispute.AddTextEvidenceAsync(dispute.Id, "my text evidence");
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Evidence can only be attached to disputes that are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void AddTextEvidence_showsNewRecordInFind()
{
Dispute dispute = createSampleDispute();
DisputeEvidence evidence = gateway.Dispute.AddTextEvidence(dispute.Id, "my text evidence").Target;
Assert.NotNull(evidence);
DisputeEvidence foundEvidence = gateway.Dispute.Find(dispute.Id).Target.Evidence[0];
Assert.AreEqual(evidence.Id, foundEvidence.Id);
}
[Test]
#if netcore
public async Task AddTextEvidenceAsync_showsNewRecordInFind()
#else
public void AddTextEvidenceAsync_showsNewRecordInFind()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
Result<DisputeEvidence> evidenceResult = await gateway.Dispute.AddTextEvidenceAsync(dispute.Id, "my text evidence");
DisputeEvidence evidence = evidenceResult.Target;
Assert.NotNull(evidence);
Result<Dispute> foundEvidenceResult = await gateway.Dispute.FindAsync(dispute.Id);
DisputeEvidence foundEvidence = foundEvidenceResult.Target.Evidence[0];
Assert.AreEqual(evidence.Id, foundEvidence.Id);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Finalize_changesDisputeStatusToDisputed()
{
Dispute dispute = createSampleDispute();
var result = gateway.Dispute.Finalize(dispute.Id);
Assert.IsTrue(result.IsSuccess());
Dispute finalizedDispute = gateway.Dispute.Find(dispute.Id).Target;
Assert.AreEqual(DisputeStatus.DISPUTED, finalizedDispute.Status);
}
[Test]
public void Finalize_whenThereAreValidationErrorsDoesNotSucceed()
{
Dispute dispute = createSampleDispute();
var textEvidenceRequest = new TextEvidenceRequest
{
Content = "my content",
Category = "DEVICE_ID",
};
DisputeEvidence evidence = gateway.Dispute.AddTextEvidence(dispute.Id, textEvidenceRequest).Target;
var result = gateway.Dispute.Finalize(dispute.Id);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual
(
new HashSet<ValidationErrorCode>
{
ValidationErrorCode.DISPUTE_DIGITAL_GOODS_MISSING_EVIDENCE,
ValidationErrorCode.DISPUTE_DIGITAL_GOODS_MISSING_DOWNLOAD_DATE
},
new HashSet<ValidationErrorCode>(result.Errors.ForObject("Dispute").OnField("Dispute").Select(error => error.Code))
);
Dispute finalizedDispute = gateway.Dispute.Find(dispute.Id).Target;
Assert.AreNotEqual(DisputeStatus.DISPUTED, finalizedDispute.Status);
Assert.AreEqual(DisputeStatus.OPEN, finalizedDispute.Status);
}
[Test]
#if netcore
public async Task FinalizeAsync_changesDisputeStatusToDisputed()
#else
public void FinalizeAsync_changesDisputeStatusToDisputed()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
var result = gateway.Dispute.Finalize(dispute.Id);
Assert.IsTrue(result.IsSuccess());
Result<Dispute> finalizedDisputeResult = await gateway.Dispute.FindAsync(dispute.Id);
Dispute finalizedDispute = finalizedDisputeResult.Target;
Assert.AreEqual(DisputeStatus.DISPUTED, finalizedDispute.Status);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Finalize_whenDisputeNotOpenErrors()
{
var result = gateway.Dispute.Finalize("wells_dispute");
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_FINALIZE_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Disputes can only be finalized when they are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
[Test]
#if netcore
public async Task FinalizeAsync_whenDisputeNotOpenErrors()
#else
public void FinalizeAsync_whenDisputeNotOpenErrors()
{
Task.Run(async () =>
#endif
{
var result = await gateway.Dispute.FinalizeAsync("wells_dispute");
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_FINALIZE_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Disputes can only be finalized when they are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Finalize_whenDisputeNotFoundErrors()
{
NotFoundException exception = Assert.Throws<NotFoundException>(() => gateway.Dispute.Finalize("invalid-id"));
Assert.AreEqual(exception.Message, "dispute with id 'invalid-id' not found");
}
[Test]
#if netcore
public async Task FinalizeAsync_whenDisputeNotFoundErrors()
#else
public void FinalizeAsync_whenDisputeNotFoundErrors()
{
Task.Run(async () =>
#endif
{
try
{
await gateway.Dispute.FinalizeAsync("invalid-id");
Assert.Fail("Expected Exception.");
}
catch (NotFoundException exception)
{
Assert.AreEqual(exception.Message, "dispute with id 'invalid-id' not found");
}
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Find_returnsDisputeWithGivenId()
{
Dispute dispute = gateway.Dispute.Find("open_dispute").Target;
Assert.AreEqual(31m, dispute.AmountDisputed);
Assert.AreEqual(0m, dispute.AmountWon);
Assert.AreEqual("open_dispute", dispute.Id);
Assert.AreEqual(DisputeStatus.OPEN, dispute.Status);
Assert.AreEqual("open_disputed_transaction", dispute.Transaction.Id);
}
[Test]
#if netcore
public async Task FindAsync_returnsDisputeWithGivenId()
#else
public void FindAsync_returnsDisputeWithGivenId()
{
Task.Run(async () =>
#endif
{
Result<Dispute> disputeResult = await gateway.Dispute.FindAsync("open_dispute");
Dispute dispute = disputeResult.Target;
Assert.AreEqual(31m, dispute.AmountDisputed);
Assert.AreEqual(0m, dispute.AmountWon);
Assert.AreEqual("open_dispute", dispute.Id);
Assert.AreEqual(DisputeStatus.OPEN, dispute.Status);
Assert.AreEqual("open_disputed_transaction", dispute.Transaction.Id);
Assert.IsNotNull(dispute.GraphQLId);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Find_throwsNotFoundExceptionWhenDisputeNotFound()
{
NotFoundException exception = Assert.Throws<NotFoundException>(() => gateway.Dispute.Find("invalid-id"));
Assert.AreEqual(exception.Message, "dispute with id 'invalid-id' not found");
}
[Test]
#if netcore
public async Task FindAsync_throwsNotFoundExceptionWhenDisputeNotFound()
#else
public void FindAsync_throwsNotFoundExceptionWhenDisputeNotFound()
{
Task.Run(async () =>
#endif
{
try
{
await gateway.Dispute.FindAsync("invalid-id");
Assert.Fail("Expected Exception.");
}
catch (NotFoundException exception)
{
Assert.AreEqual(exception.Message, "dispute with id 'invalid-id' not found");
}
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void RemoveEvidence_removesEvidenceFromTheDispute()
{
Dispute dispute = createSampleDispute();
DisputeEvidence evidence = gateway.Dispute.AddTextEvidence(dispute.Id, "my text evidence").Target;
Assert.NotNull(evidence);
var result = gateway.Dispute.RemoveEvidence(dispute.Id, evidence.Id);
Assert.IsTrue(result.IsSuccess());
Dispute editedDispute = gateway.Dispute.Find(dispute.Id).Target;
Assert.AreEqual(0, editedDispute.Evidence.Count);
}
[Test]
#if netcore
public async Task RemoveEvidenceAsync_removesEvidenceFromTheDispute()
#else
public void RemoveEvidenceAsync_removesEvidenceFromTheDispute()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
Result<DisputeEvidence> evidenceResult = await gateway.Dispute.AddTextEvidenceAsync(dispute.Id, "my text evidence");
DisputeEvidence evidence = evidenceResult.Target;
Assert.NotNull(evidence);
var result = await gateway.Dispute.RemoveEvidenceAsync(dispute.Id, evidence.Id);
Assert.IsTrue(result.IsSuccess());
Dispute editedDispute = gateway.Dispute.Find(dispute.Id).Target;
Assert.AreEqual(0, editedDispute.Evidence.Count);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void RemoveEvidence_whenDisputeOrEvidenceNotFoundThrowsNotFoundException()
{
NotFoundException exception = Assert.Throws<NotFoundException>(() => gateway.Dispute.RemoveEvidence("invalid-dispute-id", "invalid-evidence-id"));
Assert.AreEqual(exception.Message, "evidence with id 'invalid-evidence-id' for dispute with id 'invalid-dispute-id' not found");
}
[Test]
#if netcore
public async Task RemoveEvidenceAsync_whenDisputeOrEvidenceNotFoundThrowsNotFoundException()
#else
public void RemoveEvidenceAsync_whenDisputeOrEvidenceNotFoundThrowsNotFoundException()
{
Task.Run(async () =>
#endif
{
try
{
await gateway.Dispute.RemoveEvidenceAsync("invalid-dispute-id", "invalid-evidence-id");
Assert.Fail("Expected Exception.");
}
catch (NotFoundException exception)
{
Assert.AreEqual(exception.Message, "evidence with id 'invalid-evidence-id' for dispute with id 'invalid-dispute-id' not found");
}
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void RemoveEvidence_errorsWhenDisputeNotOpen()
{
Dispute dispute = createSampleDispute();
DisputeEvidence evidence = gateway.Dispute.AddTextEvidence(dispute.Id, "my text evidence").Target;
Assert.NotNull(evidence);
gateway.Dispute.Accept(dispute.Id);
var result = gateway.Dispute.RemoveEvidence(dispute.Id, evidence.Id);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_REMOVE_EVIDENCE_FROM_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Evidence can only be removed from disputes that are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
[Test]
#if netcore
public async Task RemoveEvidenceAsync_errorsWhenDisputeNotOpen()
#else
public void RemoveEvidenceAsync_errorsWhenDisputeNotOpen()
{
Task.Run(async () =>
#endif
{
Dispute dispute = await createSampleDisputeAsync();
Result<DisputeEvidence> evidenceResult = await gateway.Dispute.AddTextEvidenceAsync(dispute.Id, "my text evidence");
DisputeEvidence evidence = evidenceResult.Target;
Assert.NotNull(evidence);
await gateway.Dispute.AcceptAsync(dispute.Id);
var result = await gateway.Dispute.RemoveEvidenceAsync(dispute.Id, evidence.Id);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(ValidationErrorCode.DISPUTE_CAN_ONLY_REMOVE_EVIDENCE_FROM_OPEN_DISPUTE, result.Errors.ForObject("Dispute").OnField("Status")[0].Code);
Assert.AreEqual("Evidence can only be removed from disputes that are in an Open state", result.Errors.ForObject("Dispute").OnField("Status")[0].Message);
}
#if net452
).GetAwaiter().GetResult();
}
#endif
[Test]
public void Search_withEmptyResult()
{
DisputeSearchRequest request = new DisputeSearchRequest().
Id.Is("non_existent_dispute");
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.AreEqual(0, disputes.Count);
}
[Test]
public void Search_byIdReturnsSingleDispute()
{
DisputeSearchRequest request = new DisputeSearchRequest().
Id.Is("open_dispute");
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.AreEqual(1, disputes.Count);
}
[Test]
public void Search_withMultipleReasonsReturnsMultipleDisputes()
{
DisputeSearchRequest request = new DisputeSearchRequest().
DisputeReason.IncludedIn(DisputeReason.PRODUCT_UNSATISFACTORY, DisputeReason.RETRIEVAL);
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.IsTrue(disputes.Count >= 2);
}
[Test]
public void Search_withChargebackProtectionLevelReturnsDispute()
{
DisputeSearchRequest request = new DisputeSearchRequest().
DisputeChargebackProtectionLevel.Is(DisputeChargebackProtectionLevel.EFFORTLESS);
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.IsTrue(disputes.Count == 1);
Assert.AreEqual("CASE-CHARGEBACK-PROTECTED", disputes[0].CaseNumber);
Assert.AreEqual(DisputeReason.FRAUD, disputes[0].Reason);
Assert.AreEqual(DisputeChargebackProtectionLevel.EFFORTLESS, disputes[0].ChargebackProtectionLevel);
}
[Test]
public void Search_receivedDateRangeReturnsDispute()
{
DateTime startDate = DateTime.Parse("2014-03-03");
DateTime endDate = DateTime.Parse("2014-03-05");
DisputeSearchRequest request = new DisputeSearchRequest().
ReceivedDate.Between(startDate, endDate);
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.IsTrue(disputes.Count >= 1);
Assert.AreEqual("2014", disputes[0].ReceivedDate.Value.Year.ToString());
Assert.AreEqual("3", disputes[0].ReceivedDate.Value.Month.ToString());
Assert.AreEqual("4", disputes[0].ReceivedDate.Value.Day.ToString());
}
[Test]
public void Search_disbursementDateRangeReturnsDispute()
{
DateTime startDate = DateTime.Parse("2014-03-03");
DateTime endDate = DateTime.Parse("2014-03-05");
DisputeSearchRequest request = new DisputeSearchRequest().
DisbursementDate.Between(startDate, endDate);
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.IsTrue(disputes.Count >= 1);
Assert.AreEqual("2014", disputes[0].StatusHistory[0].DisbursementDate.Value.Year.ToString());
Assert.AreEqual("3", disputes[0].StatusHistory[0].DisbursementDate.Value.Month.ToString());
Assert.AreEqual("5", disputes[0].StatusHistory[0].DisbursementDate.Value.Day.ToString());
}
[Test]
public void Search_effectiveDateRangeReturnsDispute()
{
DateTime startDate = DateTime.Parse("2014-03-03");
DateTime endDate = DateTime.Parse("2014-03-05");
DisputeSearchRequest request = new DisputeSearchRequest().
EffectiveDate.Between(startDate, endDate);
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.IsTrue(disputes.Count >= 1);
Assert.AreEqual("2014", disputes[0].StatusHistory[0].EffectiveDate.Value.Year.ToString());
Assert.AreEqual("3", disputes[0].StatusHistory[0].EffectiveDate.Value.Month.ToString());
Assert.AreEqual("4", disputes[0].StatusHistory[0].EffectiveDate.Value.Day.ToString());
}
[Test]
public void Search_byCustomerIdReturnsDispute()
{
Result<Customer> result = gateway.Customer.Create(new CustomerRequest {});
string customerId = result.Target.Id;
TransactionRequest transactionRequest = new TransactionRequest
{
Amount = 100M,
CreditCard = new TransactionCreditCardRequest
{
Number = SandboxValues.Dispute.CHARGEBACK,
ExpirationDate = "05/2012",
},
CustomerId = customerId
};
Transaction transaction = gateway.Transaction.Sale(transactionRequest).Target;
DisputeSearchRequest request = new DisputeSearchRequest().
CustomerId.Is(customerId);
PaginatedCollection<Dispute> disputeCollection = gateway.Dispute.Search(request);
var disputes = new List<Dispute>();
foreach (var d in disputeCollection)
{
disputes.Add(d);
}
Assert.AreEqual(1, disputes.Count);
}
public Dispute createSampleDispute(){
string creditCardToken = $"cc{new Random().Next(1000000).ToString()}";
TransactionRequest request = new TransactionRequest
{
Amount = 100M,
CreditCard = new TransactionCreditCardRequest
{
Number = SandboxValues.Dispute.CHARGEBACK,
ExpirationDate = "05/2012",
Token = creditCardToken
},
};
Transaction transaction = gateway.Transaction.Sale(request).Target;
return transaction.Disputes[0];
}
public async Task<Dispute> createSampleDisputeAsync(){
string creditCardToken = $"cc{new Random().Next(1000000).ToString()}";
TransactionRequest request = new TransactionRequest
{
Amount = 100M,
CreditCard = new TransactionCreditCardRequest
{
Number = SandboxValues.Dispute.CHARGEBACK,
ExpirationDate = "05/2012",
Token = creditCardToken
},
};
Result<Transaction> transactionResult = await gateway.Transaction.SaleAsync(request);
return transactionResult.Target.Disputes[0];
}
public DocumentUpload createSampleDocumentUpload() {
FileStream file = new FileStream(BT_LOGO_PATH, FileMode.Open, FileAccess.Read);
DocumentUploadRequest request = new DocumentUploadRequest();
request.File = file;
request.DocumentKind = DocumentUploadKind.EVIDENCE_DOCUMENT;
DocumentUpload documentUpload = gateway.DocumentUpload.Create(request).Target;
return documentUpload;
}
public async Task<DocumentUpload> createSampleDocumentUploadAsync() {
FileStream file = new FileStream(BT_LOGO_PATH, FileMode.Open, FileAccess.Read);
DocumentUploadRequest request = new DocumentUploadRequest();
request.File = file;
request.DocumentKind = DocumentUploadKind.EVIDENCE_DOCUMENT;
Result<DocumentUpload> documentUploadResult = await gateway.DocumentUpload.CreateAsync(request);
return documentUploadResult.Target;
}
}
}
| |
using System;
using Xamarin.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Xamvvm
{
public partial class XamvvmFormsFactory : IBaseFactory
{
int _maxPageCacheItems;
readonly Dictionary<Type, Type> _pageModelTypes = new Dictionary<Type, Type>();
readonly Dictionary<Type, Type> _viewModelTypes = new Dictionary<Type, Type>();
readonly Dictionary<Tuple<Type, string>, int> _pageCacheHits = new Dictionary<Tuple<Type, string>, int>();
readonly Dictionary<Tuple<Type, string>, object> _pageCache = new Dictionary<Tuple<Type, string>, object>();
readonly Dictionary<Type, Func<object>> _pageCreation = new Dictionary<Type, Func<object>>();
readonly Dictionary<Type, Func<object>> _pageModelCreation = new Dictionary<Type, Func<object>>();
readonly ConditionalWeakTable<IBasePageModel, object> _weakPageCache = new ConditionalWeakTable<IBasePageModel, object>();
public XamvvmFormsFactory(Application appInstance, int maxPageCacheItems = 6, bool automaticAssembliesDiscovery = true, params Assembly[] additionalPagesAssemblies)
{
_maxPageCacheItems = maxPageCacheItems;
var pagesAssemblies = additionalPagesAssemblies.ToList();
if (automaticAssembliesDiscovery)
pagesAssemblies.Add(appInstance.GetType().GetTypeInfo().Assembly);
foreach (var assembly in pagesAssemblies.Distinct())
{
foreach (var pageTypeInfo in assembly.DefinedTypes.Where(t => t.IsClass && !t.IsAbstract
&& t.ImplementedInterfaces != null && !t.IsGenericTypeDefinition))
{
var found = pageTypeInfo.ImplementedInterfaces.FirstOrDefault(t => t.IsConstructedGenericType &&
t.GetGenericTypeDefinition() == typeof(IBasePage<>));
if (found != default(Type))
{
var pageType = pageTypeInfo.AsType();
var pageModelType = found.GenericTypeArguments.First();
if (!_pageModelTypes.ContainsKey(pageModelType))
{
_pageModelTypes.Add(pageModelType, pageType);
}
else
{
var oldPageType = _pageModelTypes[pageModelType];
if (pageTypeInfo.IsSubclassOf(oldPageType))
{
_pageModelTypes.Remove(pageModelType);
_pageModelTypes.Add(pageModelType, pageType);
}
}
}
var foundView = pageTypeInfo.ImplementedInterfaces.FirstOrDefault(t => t.IsConstructedGenericType &&
t.GetGenericTypeDefinition() == typeof(IBaseView<>));
if (foundView != default(Type))
{
var viewType = pageTypeInfo.AsType();
var viewModelType = foundView.GenericTypeArguments.First();
if (!_viewModelTypes.ContainsKey(viewModelType))
{
_viewModelTypes.Add(viewModelType, viewType);
}
else
{
var oldPageType = _viewModelTypes[viewModelType];
if (pageTypeInfo.IsSubclassOf(oldPageType))
{
_viewModelTypes.Remove(viewModelType);
_viewModelTypes.Add(viewModelType, viewType);
}
}
}
}
}
}
public virtual void RegisterPage<TPageModel>(Func<TPageModel> createPageModel = null, Func<IBasePage<TPageModel>> createPage = null) where TPageModel : class, IBasePageModel
{
if (createPageModel != null)
{
Func<object> found = null;
if (_pageModelCreation.TryGetValue(typeof(TPageModel), out found))
_pageModelCreation[typeof(TPageModel)] = createPageModel;
else
_pageModelCreation.Add(typeof(TPageModel), createPageModel);
}
if (createPage != null)
{
Func<object> found = null;
if (_pageCreation.TryGetValue(typeof(TPageModel), out found))
_pageCreation[typeof(TPageModel)] = createPage;
else
_pageCreation.Add(typeof(TPageModel), createPage);
}
}
public virtual void RegisterNavigationPage<TNavPageModel, TInitalPageModel>(bool initialPageFromCache = true)
where TNavPageModel : class, IBasePageModel
where TInitalPageModel : class, IBasePageModel
{
RegisterNavigationPage<TNavPageModel>(() =>
initialPageFromCache ? GetPageFromCache<TInitalPageModel>() : GetPageAsNewInstance<TInitalPageModel>(), null, null);
}
/// <summary>
/// Used to register the initial navigation page model
/// </summary>
/// <typeparam name="TNavPageModel">Page Model for the navigation page</typeparam>
/// <param name="initialPage">Page Model for the initial page to navigate to</param>
/// <param name="createNavModel">TBD, defaults to null</param>
/// <param name="createNav">TBD, defaults to null</param>
public virtual void RegisterNavigationPage<TNavPageModel>(Func<IBasePage<IBasePageModel>> initialPage = null,
Func<TNavPageModel> createNavModel = null,
Func<IBasePage<IBasePageModel>, IBasePage<TNavPageModel>> createNav = null) where TNavPageModel : class, IBasePageModel
{
// This defaults to null, when is it used?
if (createNavModel != null)
{
Func<object> found = null;
if (_pageModelCreation.TryGetValue(typeof(TNavPageModel), out found))
_pageModelCreation[typeof(TNavPageModel)] = createNavModel;
else
_pageModelCreation.Add(typeof(TNavPageModel), createNavModel);
}
// This defaults to null, when is it used?
if (createNav == null)
{
var pageModelType = typeof(TNavPageModel);
var pageType = GetPageType(pageModelType) ?? typeof(BaseNavigationPage<TNavPageModel>);
_pageModelTypes[pageModelType] = pageType;
if (initialPage == null)
{
createNav = new Func<IBasePage<IBasePageModel>, IBasePage<TNavPageModel>>(
(page) => XamvvmIoC.Resolve(pageType) as IBasePage<TNavPageModel>);
}
else
{
try
{
createNav = new Func<IBasePage<IBasePageModel>, IBasePage<TNavPageModel>>(
(page) => Activator.CreateInstance(pageType, page) as IBasePage<TNavPageModel>);
}
catch (MissingMemberException)
{
throw new MissingMemberException(pageType + " is missing a constructor that accepts a child page as parameter");
}
}
}
// this creates a new lambda function that will be later invoked
var createNavWithPage = new Func<IBasePage<TNavPageModel>>(() =>
{
// Take the initial page and invoke it. The page is passed in as a lambda expression that returns something of type IBasePage<T>
var page = initialPage?.Invoke();
return createNav(page);
});
Func<object> foundPageCreation = null;
if (_pageCreation.TryGetValue(typeof(TNavPageModel), out foundPageCreation))
_pageCreation[typeof(TNavPageModel)] = createNavWithPage;
else
_pageCreation.Add(typeof(TNavPageModel), createNavWithPage);
}
public virtual void RegisterMultiPage<TContainerPageModel, TFormsContainerPageType, TFormsSubPageType>(
Func<IEnumerable<IBasePage<IBasePageModel>>> createSubPages,
Func<TContainerPageModel> createMultModel = null,
Func<IEnumerable<IBasePage<IBasePageModel>>, IBasePage<TContainerPageModel>> createMult = null)
where TContainerPageModel : class, IBasePageModel
where TFormsContainerPageType : MultiPage<TFormsSubPageType>, new()
where TFormsSubPageType: Page
{
if (createMultModel != null)
{
Func<object> found = null;
if (_pageModelCreation.TryGetValue(typeof(TContainerPageModel), out found))
_pageModelCreation[typeof(TContainerPageModel)] = createMultModel;
else
_pageModelCreation.Add(typeof(TContainerPageModel), createMultModel);
}
if (createMult == null)
{
var pageModelType = typeof(TContainerPageModel);
var pageType = GetPageType(pageModelType) ?? typeof(TFormsContainerPageType);
_pageModelTypes[pageModelType] = pageType;
if (createSubPages == null)
{
createMult = new Func<IEnumerable<IBasePage<IBasePageModel>>, IBasePage<TContainerPageModel>>(
(pages) => XamvvmIoC.Resolve(pageType) as IBasePage<TContainerPageModel>);
}
else
{
createMult = new Func<IEnumerable<IBasePage<IBasePageModel>>, IBasePage<TContainerPageModel>>(
(pages) =>
{
var multiPage = XamvvmIoC.Resolve(pageType) as IBasePage<TContainerPageModel>;
var multiPageXam = (TabbedPage)multiPage;
foreach (var page in pages)
{
multiPageXam.Children.Add((Page)page);
}
return multiPage;
});
}
}
var createMultWithPages = new Func<IBasePage<TContainerPageModel>>(() =>
{
var pages = createSubPages?.Invoke();
return createMult(pages);
});
Func<object> foundPageCreation = null;
if (_pageCreation.TryGetValue(typeof(TContainerPageModel), out foundPageCreation))
_pageCreation[typeof(TContainerPageModel)] = createMultWithPages;
else
_pageCreation.Add(typeof(TContainerPageModel), createMultWithPages);
}
public virtual void RegisterTabbedPage<TTabbedPageModel>(IEnumerable<Type> subPageModelTypes, bool subPagesFromCache = true) where TTabbedPageModel : class, IBasePageModel
{
var createSubPages = new Func<IEnumerable<IBasePage<IBasePageModel>>>(
() => subPageModelTypes.Select( t => subPagesFromCache ? GetPageFromCache(t) : GetPageAsNewInstance(t)) );
RegisterMultiPage<TTabbedPageModel, TabbedPage, Page>(createSubPages, null, null);
}
public virtual void RegisterTabbedPage<TTabbedPageModel>(Func<IEnumerable<IBasePage<IBasePageModel>>> createSubPages,
Func<TTabbedPageModel> createTabModel = null,
Func<IEnumerable<IBasePage<IBasePageModel>>, IBasePage<TTabbedPageModel>> createTabPage = null) where TTabbedPageModel : class, IBasePageModel
{
RegisterMultiPage<TTabbedPageModel, TabbedPage, Page>(createSubPages, createTabModel, createTabPage);
}
public virtual void RegisterCarouselPage<TPageModel>(IEnumerable<Type> subPageModelTypes, bool subPagesFromCache = true) where TPageModel : class, IBasePageModel
{
var createSubPages = new Func<IEnumerable<IBasePage<IBasePageModel>>>(
() => subPageModelTypes.Select(t => subPagesFromCache ? GetPageFromCache(t) : GetPageAsNewInstance(t)));
RegisterMultiPage<TPageModel, CarouselPage, ContentPage>(createSubPages, null, null);
}
public virtual void RegisterCarouselPage<TPageModel>(Func<IEnumerable<IBasePage<IBasePageModel>>> createSubPages, Func<TPageModel> createCarModel = null, Func<IEnumerable<IBasePage<IBasePageModel>>, IBasePage<TPageModel>> createCar = null) where TPageModel : class, IBasePageModel
{
RegisterMultiPage<TPageModel, CarouselPage, ContentPage>(createSubPages, createCarModel, createCar);
}
public virtual void RegisterMasterDetail<TPageModel, TMasterPageModel, TDetailPageModel>(bool masterFromCache = true, bool detailFromCache = true)
where TPageModel : class, IBasePageModel where TMasterPageModel : class, IBasePageModel where TDetailPageModel : class, IBasePageModel
{
RegisterMasterDetail<TPageModel>(
() => masterFromCache ? GetPageFromCache<TMasterPageModel>() : GetPageAsNewInstance<TMasterPageModel>(),
() => detailFromCache ? GetPageFromCache<TDetailPageModel>() : GetPageAsNewInstance<TDetailPageModel>());
}
public virtual void RegisterMasterDetail<TPageModel>(Func<IBasePage<IBasePageModel>> createMasterPage, Func<IBasePage<IBasePageModel>> createDetailPage, Func<TPageModel> createMasDetModel = null, Func<IBasePage<IBasePageModel>, IBasePage<IBasePageModel>, IBasePage<TPageModel>> createMasDet = null) where TPageModel : class, IBasePageModel
{
if (createMasDetModel != null)
{
Func<object> found = null;
if (_pageModelCreation.TryGetValue(typeof(TPageModel), out found))
_pageModelCreation[typeof(TPageModel)] = createMasDetModel;
else
_pageModelCreation.Add(typeof(TPageModel), createMasDetModel);
}
if (createMasDet == null)
{
var pageModelType = typeof(TPageModel);
var pageType = GetPageType(pageModelType) ?? typeof(BaseMasterDetailPage<TPageModel>);
_pageModelTypes[pageModelType] = pageType;
createMasDet = new Func<IBasePage<IBasePageModel>, IBasePage<IBasePageModel>, IBasePage<TPageModel>>(
(master, detail) =>
{
var masdetPage = XamvvmIoC.Resolve(pageType) as IBasePage<TPageModel>;
var masdetPageXam = (MasterDetailPage)masdetPage;
masdetPageXam.Master = master as Page;
masdetPageXam.Detail = detail as Page;
return masdetPage;
});
}
var createMasDetWithPages = new Func<IBasePage<TPageModel>>(() =>
{
var masterPage = createMasterPage?.Invoke();
var detailPage = createDetailPage?.Invoke();
return createMasDet(masterPage, detailPage);
});
Func<object> foundPageCreation = null;
if (_pageCreation.TryGetValue(typeof(TPageModel), out foundPageCreation))
_pageCreation[typeof(TPageModel)] = createMasDetWithPages;
else
_pageCreation.Add(typeof(TPageModel), createMasDetWithPages);
}
internal void AddToWeakCacheIfNotExists<TPageModel>(IBasePage<TPageModel> page, TPageModel pageModel) where TPageModel : class, IBasePageModel
{
if (pageModel == null)
return;
object weakExists;
if (!_weakPageCache.TryGetValue(pageModel, out weakExists))
_weakPageCache.Add(pageModel, page);
}
internal Type GetPageType(Type pageModelType)
{
Type pageType = null;
if (_pageModelTypes.TryGetValue(pageModelType, out pageType))
return pageType;
return null;
}
internal Type GetViewType(Type viewModelType)
{
Type viewType = null;
if (_viewModelTypes.TryGetValue(viewModelType, out viewType))
return viewType;
return null;
}
internal Type GetPageModelType(IBasePage<IBasePageModel> page)
{
var found = page.GetType().GetTypeInfo().ImplementedInterfaces.FirstOrDefault(t => t.IsConstructedGenericType && t.GetGenericTypeDefinition() == typeof(IBasePage<>));
var viewModelType = found.GenericTypeArguments.First();
return viewModelType;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
// Groups
// Objects can belong to multiple groups.
public class Group : ScriptableObject, IEnumerable<GameObject>
{
#region static
#region private_static
static Dictionary<string, Group> groups = new Dictionary<string, Group>();
private static Group CreateEmptyGroup(string id)
{
var group = ScriptableObject.CreateInstance<Group>();
group.name = id;
groups.Add(id, group);
return group;
}
private static Group GetOrCreateEmptyGroup(string id)
{
Group group = null;
if(!groups.TryGetValue(id, out group))
group = CreateEmptyGroup(id);
return group;
}
#endregion
public static void DestroyGroup(GroupId id, bool despawnObjects)
{
DestroyGroup(id.name, despawnObjects);
}
public static void DestroyGroup(string id, bool despawnObjects)
{
var group = Get(id);
if(group==null)
return;
if(despawnObjects)
{
group.DespawnObjects();
}
ScriptableObject.Destroy(group);
}
public static Group Get(GroupId id)
{
return Get(id.name);
}
public static Group Get(string id)
{
/* Group result = null;
groups.TryGetValue(id, out result);
return result;
*/
return GetOrCreateEmptyGroup(id);
}
public static GameObject Spawn(string id, GameObject prefab, Vector3 position, Quaternion rotation)
{
var group = GetOrCreateEmptyGroup(id);
return group.Spawn(prefab, position, rotation);
}
public static GameObject Spawn(GroupId id, GameObject prefab, Vector3 position, Quaternion rotation)
{
var group = GetOrCreateEmptyGroup(id.name);
return group.Spawn(prefab, position, rotation);
}
public static GameObject Spawn(string id, GameObject prefab)
{
var group = GetOrCreateEmptyGroup(id);
return group.Spawn(prefab);
}
public static GameObject Spawn(GroupId id, GameObject prefab)
{
return Spawn(id.name, prefab);
}
public static void AddToGroup(GroupId id, GameObject obj)
{
AddToGroup(id.name, obj);
}
public static void AddToGroup(string id, GameObject obj)
{
var group = GetOrCreateEmptyGroup(id);
group.Add(obj);
}
public static void LoadSceneAsGroup(GroupId id, string sceneName)
{
LoadSceneAsGroup(id.name, sceneName);
}
public static void LoadSceneAsGroup(string id, string sceneName)
{
GroupLevelLoader.Create(id, sceneName);
}
public static void LoadTagFromSceneAsGroup(GroupId id, string sceneName, string tagName)
{
LoadTagFromSceneAsGroup(id.name, sceneName, tagName);
}
public static void LoadTagFromSceneAsGroup(string id, string sceneName, string tagName)
{
GroupLevelLoader.Create(id, sceneName, tagName);
}
public static void AddToGroup(GroupId id, IEnumerable<GameObject> objs)
{
AddToGroup(id.name, objs);
}
public static void AddToGroup(string id, IEnumerable<GameObject> objs)
{
var group = GetOrCreateEmptyGroup(id);
group.Add(objs);
}
#endregion
#region instance
public int NumActiveObjects {get {return objects.Count((a) => a && a.activeInHierarchy); } }
public int NumObjects {get {return objects.Count((a) => a); } }
public string Id {get {return name; } }
public GameObject[] Objects
{
get
{
// cleanup dead items
objects.RemoveWhere((obj) => !obj);
return objects.ToArray();
}
}
public GameObject[] ActiveObjects
{
get
{
// cleanup dead items
objects.RemoveWhere((obj) => !obj);
return objects.Where((obj) => obj.activeInHierarchy).ToArray();
}
}
private HashSet<GameObject> objects = new HashSet<GameObject>();
public void Add(GameObject obj)
{
objects.Add(obj);
}
public void Add(IEnumerable<GameObject> range)
{
foreach(GameObject i in range)
objects.Add(i);
}
public void Remove(GameObject obj)
{
objects.Remove(obj);
}
public void Remove(IEnumerable<GameObject> range)
{
foreach(GameObject i in range)
objects.Remove(i);
}
public void DespawnObjects()
{
foreach(var i in objects)
Pool.Despawn(i);
objects.Clear();
}
public void GroupSendMessage(string methodName, SendMessageOptions options)
{
GroupSendMessage(methodName, null, options);
}
public void GroupSendMessage(string methodName, Object parameter, SendMessageOptions options)
{
foreach(var i in objects)
{
i.SendMessage(methodName, parameter, options);
}
}
public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation)
{
var result = Pool.Spawn(prefab, position, rotation);
if(result)
{
Add(result);
}
return result;
}
public GameObject Spawn(GameObject prefab)
{
var result = Pool.Spawn(prefab);
if(result)
{
Add(result);
}
return result;
}
public GameObject Random()
{
return objects.ElementAt(UnityEngine.Random.Range(0, NumObjects));
}
void OnDestroy()
{
groups.Remove(Id);
}
#region IEnumerable[GameObject] implementation
IEnumerator<GameObject> IEnumerable<GameObject>.GetEnumerator ()
{
return objects.GetEnumerator();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return objects.GetEnumerator();
}
#endregion
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;
using System.Threading;
using Hydra.Framework;
namespace Hydra.SharedCache.Common
{
//
// **********************************************************************
/// <summary>
/// Provides generic object cache/pool that based on
/// CLR garbage collector (GC) logic.
/// </summary>
/// <remarks>
/// You can extend Cache behaviour in distributed
/// environment by lifetime services setting
/// of Your classes.
/// </remarks>
// **********************************************************************
//
[Serializable]
public sealed class Cache
{
private long calculatedCacheSize;
//
// **********************************************************************
/// <summary>
/// Gets/sets the CalculatedCacheSize
/// </summary>
// **********************************************************************
//
public long CalculatedCacheSize
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.calculatedCacheSize;
}
}
private CacheCleanup cacheCleanup;
//
// **********************************************************************
/// <summary>
/// Singleton for <see cref="CacheCleanup" />
/// </summary>
// **********************************************************************
//
public CacheCleanup CacheCleanup
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (this.cacheCleanup == null)
this.cacheCleanup = new CacheCleanup();
return this.cacheCleanup;
}
}
//
// **********************************************************************
/// <summary>
/// The Cache Dictionary which contains all data
/// </summary>
// **********************************************************************
//
readonly Dictionary<string, byte[]> dict;
//
// **********************************************************************
/// <summary>
/// Creates an empty Cache.
/// </summary>
// **********************************************************************
//
public Cache()
{
dict = new Dictionary<string, byte[]>();
this.calculatedCacheSize = 0;
}
//
// **********************************************************************
/// <summary>
/// Creates a Cache with the specified initial size.
/// </summary>
/// <param name="initialSize">The approximate number of objects that the Cache can initially contain.</param>
// **********************************************************************
//
public Cache(int initialSize)
: this()
{
dict = new Dictionary<string, byte[]>(initialSize);
}
//
// **********************************************************************
/// <summary>
/// returns the amount this instance contains.
/// </summary>
/// <returns></returns>
// **********************************************************************
//
public long Amount()
{
long result = 0;
lock (dict)
{
result = dict.Count;
}
return result;
}
//
// **********************************************************************
/// <summary>
/// calculates the actual size of this instance.
/// <remarks>
/// This is a very heavy operation, please consider not to use this to often then
/// it locks the cache exclusivly which is very expensive!!!
/// </remarks>
/// </summary>
/// <returns>a <see cref="long"/> object with the actual Dictionary size</returns>
// **********************************************************************
//
public long Size()
{
Dictionary<string, byte[]> di = null;
long size = 0;
//
// consider, this is very expensive!!
//
lock (dict)
{
di = new Dictionary<string, byte[]>(dict);
}
foreach (KeyValuePair<string, byte[]> de in di)
{
size += de.Value.Length;
}
return size;
}
//
// **********************************************************************
/// <summary>
/// Retrive all key's
/// </summary>
/// <returns>returns a list with all key's as a <see cref="string"/> objects.</returns>
// **********************************************************************
//
public List<string> GetAllKeys()
{
Dictionary<string, byte[]> hd = null;
lock (dict)
{
hd = new Dictionary<string, byte[]>(dict);
}
return new List<string>(hd.Keys);
}
//
// **********************************************************************
/// <summary>
/// Adds an object that identified by the provided key to the Cache.
/// if the key is already available it will replace it.
/// </summary>
/// <param name="key">The Object to use as the key of the object to add.</param>
/// <param name="value">The Object to add. </param>
// **********************************************************************
//
public void Add(string key, byte[] value)
{
try
{
lock (dict)
{
dict[key] = value;
this.calculatedCacheSize += value.Length;
}
}
catch (Exception ex)
{
// Log.Error(@"Add Failed - " + ex.Message);
}
}
//
// **********************************************************************
/// <summary>
/// Adds the specified KeyValuePair
/// </summary>
/// <param name="kpv">The KPV. A <see cref="T:System.Collections.Generic.KeyValuePair<System.String,System.Object>"/> Object.</param>
// **********************************************************************
//
public void Add(KeyValuePair<string, byte[]> kpv)
{
this.Add(kpv.Key, kpv.Value);
}
//
// **********************************************************************
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key. A <see cref="T:System.String"/> Object.</param>
/// <param name="value">The value. A <see cref="T:System.Object"/> Object.</param>
// **********************************************************************
//
public void Insert(string key, byte[] value)
{
lock (dict)
{
dict.Add(key, value);
this.calculatedCacheSize += value.Length;
}
}
//
// **********************************************************************
/// <summary>
/// Gets the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>a <see cref="object"/> object.</returns>
// **********************************************************************
//
public byte[] Get(string key)
{
byte[] o = null;
try
{
lock (dict)
{
if (dict.ContainsKey(key))
{
o = dict[key];
}
else
o = null;
}
}
catch (Exception ex)
{
// Log.Error(@"Get Failed!", ex);
}
return o;
}
//
// **********************************************************************
/// <summary>
/// Removes the object that identified by the specified key from the Cache.
/// </summary>
/// <param name="key">The key of the object to remove.</param>
// **********************************************************************
//
public void Remove(string key)
{
try
{
lock (dict)
{
if (dict.ContainsKey(key))
{
this.calculatedCacheSize -= dict[key].Length;
dict.Remove(key);
}
}
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
// Log.Error(@"Remove failed!", ex);
}
}
//
// **********************************************************************
/// <summary>
/// Removes all objects from the Cache.
/// </summary>
// **********************************************************************
//
public void Clear()
{
lock (dict)
{
dict.Clear();
this.calculatedCacheSize = 0;
}
//
// ISSUE: Not sure if this has to be here
//
GC.Collect();
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace ZXing.Datamatrix.Internal
{
/// <summary>
/// The Version object encapsulates attributes about a particular
/// size Data Matrix Code.
///
/// <author>bbrown@google.com (Brian Brown)</author>
/// </summary>
public sealed class Version
{
private static readonly Version[] VERSIONS = buildVersions();
private readonly int versionNumber;
private readonly int symbolSizeRows;
private readonly int symbolSizeColumns;
private readonly int dataRegionSizeRows;
private readonly int dataRegionSizeColumns;
private readonly ECBlocks ecBlocks;
private readonly int totalCodewords;
internal Version(int versionNumber,
int symbolSizeRows,
int symbolSizeColumns,
int dataRegionSizeRows,
int dataRegionSizeColumns,
ECBlocks ecBlocks)
{
this.versionNumber = versionNumber;
this.symbolSizeRows = symbolSizeRows;
this.symbolSizeColumns = symbolSizeColumns;
this.dataRegionSizeRows = dataRegionSizeRows;
this.dataRegionSizeColumns = dataRegionSizeColumns;
this.ecBlocks = ecBlocks;
// Calculate the total number of codewords
int total = 0;
int ecCodewords = ecBlocks.ECCodewords;
ECB[] ecbArray = ecBlocks.ECBlocksValue;
foreach (ECB ecBlock in ecbArray)
{
total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords);
}
this.totalCodewords = total;
}
public int getVersionNumber()
{
return versionNumber;
}
public int getSymbolSizeRows()
{
return symbolSizeRows;
}
public int getSymbolSizeColumns()
{
return symbolSizeColumns;
}
public int getDataRegionSizeRows()
{
return dataRegionSizeRows;
}
public int getDataRegionSizeColumns()
{
return dataRegionSizeColumns;
}
public int getTotalCodewords()
{
return totalCodewords;
}
internal ECBlocks getECBlocks()
{
return ecBlocks;
}
/// <summary>
/// <p>Deduces version information from Data Matrix dimensions.</p>
///
/// <param name="numRows">Number of rows in modules</param>
/// <param name="numColumns">Number of columns in modules</param>
/// <returns>Version for a Data Matrix Code of those dimensions</returns>
/// <exception cref="FormatException">if dimensions do correspond to a valid Data Matrix size</exception>
/// </summary>
public static Version getVersionForDimensions(int numRows, int numColumns)
{
if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0)
{
return null;
}
foreach (var version in VERSIONS)
{
if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns)
{
return version;
}
}
return null;
}
/// <summary>
/// <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
/// use blocks of differing sizes within one version, so, this encapsulates the parameters for
/// each set of blocks. It also holds the number of error-correction codewords per block since it
/// will be the same across all blocks within one version.</p>
/// </summary>
internal sealed class ECBlocks
{
private readonly int ecCodewords;
private readonly ECB[] _ecBlocksValue;
internal ECBlocks(int ecCodewords, ECB ecBlocks)
{
this.ecCodewords = ecCodewords;
this._ecBlocksValue = new ECB[] { ecBlocks };
}
internal ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2)
{
this.ecCodewords = ecCodewords;
this._ecBlocksValue = new ECB[] { ecBlocks1, ecBlocks2 };
}
internal int ECCodewords
{
get { return ecCodewords; }
}
internal ECB[] ECBlocksValue
{
get { return _ecBlocksValue; }
}
}
/// <summary>
/// <p>Encapsualtes the parameters for one error-correction block in one symbol version.
/// This includes the number of data codewords, and the number of times a block with these
/// parameters is used consecutively in the Data Matrix code version's format.</p>
/// </summary>
internal sealed class ECB
{
private readonly int count;
private readonly int dataCodewords;
internal ECB(int count, int dataCodewords)
{
this.count = count;
this.dataCodewords = dataCodewords;
}
internal int Count
{
get { return count; }
}
internal int DataCodewords
{
get { return dataCodewords; }
}
}
override public String ToString()
{
return versionNumber.ToString();
}
/// <summary>
/// See ISO 16022:2006 5.5.1 Table 7
/// </summary>
private static Version[] buildVersions()
{
return new Version[]
{
new Version(1, 10, 10, 8, 8,
new ECBlocks(5, new ECB(1, 3))),
new Version(2, 12, 12, 10, 10,
new ECBlocks(7, new ECB(1, 5))),
new Version(3, 14, 14, 12, 12,
new ECBlocks(10, new ECB(1, 8))),
new Version(4, 16, 16, 14, 14,
new ECBlocks(12, new ECB(1, 12))),
new Version(5, 18, 18, 16, 16,
new ECBlocks(14, new ECB(1, 18))),
new Version(6, 20, 20, 18, 18,
new ECBlocks(18, new ECB(1, 22))),
new Version(7, 22, 22, 20, 20,
new ECBlocks(20, new ECB(1, 30))),
new Version(8, 24, 24, 22, 22,
new ECBlocks(24, new ECB(1, 36))),
new Version(9, 26, 26, 24, 24,
new ECBlocks(28, new ECB(1, 44))),
new Version(10, 32, 32, 14, 14,
new ECBlocks(36, new ECB(1, 62))),
new Version(11, 36, 36, 16, 16,
new ECBlocks(42, new ECB(1, 86))),
new Version(12, 40, 40, 18, 18,
new ECBlocks(48, new ECB(1, 114))),
new Version(13, 44, 44, 20, 20,
new ECBlocks(56, new ECB(1, 144))),
new Version(14, 48, 48, 22, 22,
new ECBlocks(68, new ECB(1, 174))),
new Version(15, 52, 52, 24, 24,
new ECBlocks(42, new ECB(2, 102))),
new Version(16, 64, 64, 14, 14,
new ECBlocks(56, new ECB(2, 140))),
new Version(17, 72, 72, 16, 16,
new ECBlocks(36, new ECB(4, 92))),
new Version(18, 80, 80, 18, 18,
new ECBlocks(48, new ECB(4, 114))),
new Version(19, 88, 88, 20, 20,
new ECBlocks(56, new ECB(4, 144))),
new Version(20, 96, 96, 22, 22,
new ECBlocks(68, new ECB(4, 174))),
new Version(21, 104, 104, 24, 24,
new ECBlocks(56, new ECB(6, 136))),
new Version(22, 120, 120, 18, 18,
new ECBlocks(68, new ECB(6, 175))),
new Version(23, 132, 132, 20, 20,
new ECBlocks(62, new ECB(8, 163))),
new Version(24, 144, 144, 22, 22,
new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))),
new Version(25, 8, 18, 6, 16,
new ECBlocks(7, new ECB(1, 5))),
new Version(26, 8, 32, 6, 14,
new ECBlocks(11, new ECB(1, 10))),
new Version(27, 12, 26, 10, 24,
new ECBlocks(14, new ECB(1, 16))),
new Version(28, 12, 36, 10, 16,
new ECBlocks(18, new ECB(1, 22))),
new Version(29, 16, 36, 14, 16,
new ECBlocks(24, new ECB(1, 32))),
new Version(30, 16, 48, 14, 22,
new ECBlocks(28, new ECB(1, 49)))
};
}
}
}
| |
/*
* DotGNU XmlRpc implementation
*
* Copyright (C) 2003 Free Software Foundation, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* $Revision: 1.1 $ $Date: 2004/05/04 17:00:46 $
*
* --------------------------------------------------------------------------
*/
//using System.Reflection;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Xml;
namespace DotGNU.XmlRpc
{
public abstract class XmlRpcObject : ArrayList
{
private DateTimeFormatInfo dateFormat;
private Stack containerStack;
private object value;
private string text;
protected string methodName;
private string nodeName;
private XmlTextReader reader;
public XmlRpcObject()
{
this.dateFormat = new DateTimeFormatInfo();
}
public void Read( XmlTextReader reader )
{
this.reader = reader;
Read();
}
private void Read() {
containerStack = new Stack();
// Itereate through the tree and construct an n-ary tree with
// XmlRpcNodes so we can detect protocol errors and the current
// scope/context of a value parameter.
while( reader.Read() ) {
switch( reader.NodeType ) {
//
// ELEMENT OPEN
//
case XmlNodeType.Element:
nodeName = reader.Name;
switch( nodeName ) {
case "value":
value = null;
text = null;
break;
case "struct":
PushScope( new XmlRpcStruct() );
break;
case "array":
PushScope( new XmlRpcArray() );
break;
}
break;
//
// ELEMENT TEXT
//
case XmlNodeType.Text:
text = reader.Value;
switch( nodeName ) {
case "methodName":
methodName = text;
break;
default:
AddValue();
break;
}
break;
//
// ELEMENT CLOSE
//
case XmlNodeType.EndElement:
switch( reader.Name ) {
case "struct":
case "array":
object closedScope = containerStack.Pop();
// now determine whether the bugger aint nested...
if( containerStack.Count > 0 ) {
// aaah yes. nested. add him to the current stack object
object stackObject = containerStack.Peek();
if( stackObject is XmlRpcStruct ) {
((XmlRpcStruct)stackObject).value = closedScope;
}
else if( stackObject is XmlRpcArray ) {
((XmlRpcArray)stackObject).Add( closedScope );
}
}
else {
Add( closedScope );
}
break;
case "member":
object stackObject;
if( containerStack.Count > 0 ) {
stackObject = containerStack.Peek();
if( stackObject is XmlRpcStruct ) {
((XmlRpcStruct)stackObject).Commit();
}
}
break;
} //switch
break; // switch XmlNodeType.EndElement
}
} // reader.Read()
}
private void AddValue()
{
object o;
switch( nodeName ) {
case "i4":
case "int":
o = Int32.Parse( text );
break;
case "boolean":
if( text == "0" ) {
text = "false";
}
else {
text = "true";
}
o = Convert.ToBoolean( text );
break;
case "double":
o = Double.Parse( text );
break;
case "dateTime.iso8601":
try {
o = DateTime.ParseExact( text, "s", dateFormat );
}
catch( FormatException e ){
string str =
String.Format
( "Cannot parse DateTime value: {0}, expected format is: {1}",
text, dateFormat.SortableDateTimePattern );
throw new XmlRpcBadFormatException( 200, str );
}
break;
case "base64":
o = Convert.FromBase64String( text );
break;
case "string":
case "name":
o = text;
break;
}
object stackObject;
if( containerStack.Count > 0 ) {
stackObject = containerStack.Peek();
if( stackObject is XmlRpcStruct ) {
switch( nodeName ) {
case "name":
((XmlRpcStruct)stackObject).key = text;
break;
default:
((XmlRpcStruct)stackObject).value = o;
break;
}
}
else if( stackObject is XmlRpcArray ) {
((XmlRpcArray)stackObject).Add( o );
}
}
else {
if( o != null ) Add( o );
}
}
private void PushScope( Object o )
{
containerStack.Push( o );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public interface I
{
void M();
}
public class C : IEquatable<C>, I
{
void I.M()
{
}
public override bool Equals(object o)
{
return o is C && Equals((C)o);
}
public bool Equals(C c)
{
return c != null;
}
public override int GetHashCode()
{
return 0;
}
}
public class D : C, IEquatable<D>
{
public int Val;
public string S;
public D()
{
}
public D(int val)
: this(val, "")
{
}
public D(int val, string s)
{
Val = val;
S = s;
}
public override bool Equals(object o)
{
return o is D && Equals((D)o);
}
public bool Equals(D d)
{
return d != null && d.Val == Val;
}
public override int GetHashCode()
{
return Val;
}
}
public enum E
{
A = 1,
B = 2,
Red = 0,
Green,
Blue
}
public enum El : long
{
A,
B,
C
}
public enum Eu : uint
{
Foo,
Bar,
Baz
}
public struct S : IEquatable<S>
{
public override bool Equals(object o)
{
return (o is S) && Equals((S)o);
}
public bool Equals(S other)
{
return true;
}
public override int GetHashCode()
{
return 0;
}
}
public struct Sp : IEquatable<Sp>
{
public Sp(int i, double d)
{
I = i;
D = d;
}
public int I;
public double D;
public override bool Equals(object o)
{
return (o is Sp) && Equals((Sp)o);
}
public bool Equals(Sp other)
{
return other.I == I && other.D.Equals(D);
}
public override int GetHashCode()
{
return I.GetHashCode() ^ D.GetHashCode();
}
}
public struct Ss : IEquatable<Ss>
{
public Ss(S s)
{
Val = s;
}
public S Val;
public override bool Equals(object o)
{
return (o is Ss) && Equals((Ss)o);
}
public bool Equals(Ss other)
{
return other.Val.Equals(Val);
}
public override int GetHashCode()
{
return Val.GetHashCode();
}
}
public struct Sc : IEquatable<Sc>
{
public Sc(string s)
{
S = s;
}
public string S;
public override bool Equals(object o)
{
return (o is Sc) && Equals((Sc)o);
}
public bool Equals(Sc other)
{
return other.S == S;
}
public override int GetHashCode()
{
return S.GetHashCode();
}
}
public struct Scs : IEquatable<Scs>
{
public Scs(string s, S val)
{
S = s;
Val = val;
}
public string S;
public S Val;
public override bool Equals(object o)
{
return (o is Scs) && Equals((Scs)o);
}
public bool Equals(Scs other)
{
return other.S == S && other.Val.Equals(Val);
}
public override int GetHashCode()
{
return S.GetHashCode() ^ Val.GetHashCode();
}
}
public class BaseClass
{
}
public class FC
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public struct FS
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public class PC
{
public int II { get; set; }
public static int SI { get; set; }
public int this[int i]
{
get { return 1; }
set { }
}
}
public struct PS
{
public int II { get; set; }
public static int SI { get; set; }
}
internal class CompilationTypes : IEnumerable<object[]>
{
private static readonly IEnumerable<object[]> Booleans = new[]
{
#if FEATURE_COMPILE && FEATURE_INTERPRET
new object[] {false},
#endif
new object[] {true},
};
public IEnumerator<object[]> GetEnumerator() => Booleans.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
internal class NoOpVisitor : ExpressionVisitor
{
internal static readonly NoOpVisitor Instance = new NoOpVisitor();
private NoOpVisitor()
{
}
}
public static class Unreadable<T>
{
public static T WriteOnly { set { } }
}
public class GenericClass<T>
{
public void Method() { }
public static T Field;
public static T Property => Field;
}
public class NonGenericClass
{
#pragma warning disable 0067
public event EventHandler Event;
#pragma warning restore 0067
public void GenericMethod<T>() { }
public static void StaticMethod() { }
public static readonly NonGenericClass NonGenericField = new NonGenericClass();
public static NonGenericClass NonGenericProperty => NonGenericField;
}
public class InvalidTypesData : IEnumerable<object[]>
{
private static readonly object[] GenericTypeDefinition = new object[] { typeof(GenericClass<>) };
private static readonly object[] ContainsGenericParameters = new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) };
public IEnumerator<object[]> GetEnumerator()
{
yield return GenericTypeDefinition;
yield return ContainsGenericParameters;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class UnreadableExpressionsData : IEnumerable<object[]>
{
private static readonly object[] Property = new object[] { Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly)) };
private static readonly object[] Indexer = new object[] { Expression.Property(null, typeof(Unreadable<bool>).GetProperty(nameof(Unreadable<bool>.WriteOnly)), new Expression[0]) };
public IEnumerator<object[]> GetEnumerator()
{
yield return Property;
yield return Indexer;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class OpenGenericMethodsData : IEnumerable<object[]>
{
private static readonly object[] GenericClass = new object[] { typeof(GenericClass<>).GetMethod(nameof(GenericClass<string>.Method)) };
private static readonly object[] GenericMethod = new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)) };
public IEnumerator<object[]> GetEnumerator()
{
yield return GenericClass;
yield return GenericMethod;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public enum ByteEnum : byte { A = byte.MaxValue }
public enum SByteEnum : sbyte { A = sbyte.MaxValue }
public enum Int16Enum : short { A = short.MaxValue }
public enum UInt16Enum : ushort { A = ushort.MaxValue }
public enum Int32Enum : int { A = int.MaxValue }
public enum UInt32Enum : uint { A = uint.MaxValue }
public enum Int64Enum : long { A = long.MaxValue }
public enum UInt64Enum : ulong { A = ulong.MaxValue }
#if FEATURE_COMPILE
public static class NonCSharpTypes
{
private static Type _charEnumType;
private static Type _boolEnumType;
private static ModuleBuilder GetModuleBuilder()
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName("Name"), AssemblyBuilderAccess.RunAndCollect);
return assembly.DefineDynamicModule("Name");
}
public static Type CharEnumType
{
get
{
if (_charEnumType == null)
{
EnumBuilder eb = GetModuleBuilder().DefineEnum("CharEnumType", TypeAttributes.Public, typeof(char));
eb.DefineLiteral("A", 'A');
eb.DefineLiteral("B", 'B');
eb.DefineLiteral("C", 'C');
_charEnumType = eb.CreateTypeInfo();
}
return _charEnumType;
}
}
public static Type BoolEnumType
{
get
{
if (_boolEnumType == null)
{
EnumBuilder eb = GetModuleBuilder().DefineEnum("BoolEnumType", TypeAttributes.Public, typeof(bool));
eb.DefineLiteral("False", false);
eb.DefineLiteral("True", true);
_boolEnumType = eb.CreateTypeInfo();
}
return _boolEnumType;
}
}
}
#endif
public class FakeExpression : Expression
{
public FakeExpression(ExpressionType customNodeType, Type customType)
{
CustomNodeType = customNodeType;
CustomType = customType;
}
public ExpressionType CustomNodeType { get; set; }
public Type CustomType { get; set; }
public override ExpressionType NodeType => CustomNodeType;
public override Type Type => CustomType;
}
public struct Number : IEquatable<Number>
{
private readonly int _value;
public Number(int value)
{
_value = value;
}
public static readonly Number MinValue = new Number(int.MinValue);
public static readonly Number MaxValue = new Number(int.MaxValue);
public static Number operator +(Number l, Number r) => new Number(unchecked(l._value + r._value));
public static Number operator -(Number l, Number r) => new Number(l._value - r._value);
public static Number operator *(Number l, Number r) => new Number(unchecked(l._value * r._value));
public static Number operator /(Number l, Number r) => new Number(l._value / r._value);
public static Number operator %(Number l, Number r) => new Number(l._value % r._value);
public static Number operator &(Number l, Number r) => new Number(l._value & r._value);
public static Number operator |(Number l, Number r) => new Number(l._value | r._value);
public static Number operator ^(Number l, Number r) => new Number(l._value ^ r._value);
public static bool operator >(Number l, Number r) => l._value > r._value;
public static bool operator >=(Number l, Number r) => l._value >= r._value;
public static bool operator <(Number l, Number r) => l._value < r._value;
public static bool operator <=(Number l, Number r) => l._value <= r._value;
public static bool operator ==(Number l, Number r) => l._value == r._value;
public static bool operator !=(Number l, Number r) => l._value != r._value;
public override bool Equals(object obj) => obj is Number && Equals((Number)obj);
public bool Equals(Number other) => _value == other._value;
public override int GetHashCode() => _value;
}
public static class ExpressionAssert
{
public static void Verify(this LambdaExpression expression, string il, string instructions)
{
#if FEATURE_COMPILE
expression.VerifyIL(il);
#endif
// FEATURE_COMPILE is not directly required,
// but this functionality relies on private reflection and that would not work with AOT
#if FEATURE_INTERPRET && FEATURE_COMPILE
expression.VerifyInstructions(instructions);
#endif
}
}
public class RunOnceEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerable<T> _source;
private bool _called;
public RunOnceEnumerable(IEnumerable<T> source)
{
_source = source;
}
public IEnumerator<T> GetEnumerator()
{
Assert.False(_called);
_called = true;
return _source.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class Truthiness
{
private bool Value { get; }
public Truthiness(bool value)
{
Value = value;
}
public static implicit operator bool(Truthiness truth) => truth.Value;
public static bool operator true(Truthiness truth) => truth.Value;
public static bool operator false(Truthiness truth) => !truth.Value;
public static Truthiness operator !(Truthiness truth) => new Truthiness(!truth.Value);
}
}
| |
using System;
using System.Diagnostics;
using Avalonia.Data;
using Avalonia.Reactive;
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Base class for styled properties.
/// </summary>
public abstract class StyledPropertyBase<TValue> : AvaloniaProperty<TValue>, IStyledPropertyAccessor
{
private bool _inherits;
/// <summary>
/// Initializes a new instance of the <see cref="StyledPropertyBase{T}"/> class.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="ownerType">The type of the class that registers the property.</param>
/// <param name="metadata">The property metadata.</param>
/// <param name="inherits">Whether the property inherits its value.</param>
/// <param name="validate">A value validation callback.</param>
/// <param name="notifying">A <see cref="AvaloniaProperty.Notifying"/> callback.</param>
protected StyledPropertyBase(
string name,
Type ownerType,
StyledPropertyMetadata<TValue> metadata,
bool inherits = false,
Func<TValue, bool> validate = null,
Action<IAvaloniaObject, bool> notifying = null)
: base(name, ownerType, metadata, notifying)
{
Contract.Requires<ArgumentNullException>(name != null);
Contract.Requires<ArgumentNullException>(ownerType != null);
if (name.Contains("."))
{
throw new ArgumentException("'name' may not contain periods.");
}
_inherits = inherits;
ValidateValue = validate;
HasCoercion |= metadata.CoerceValue != null;
if (validate?.Invoke(metadata.DefaultValue) == false)
{
throw new ArgumentException(
$"'{metadata.DefaultValue}' is not a valid default value for '{name}'.");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StyledPropertyBase{T}"/> class.
/// </summary>
/// <param name="source">The property to add the owner to.</param>
/// <param name="ownerType">The type of the class that registers the property.</param>
protected StyledPropertyBase(StyledPropertyBase<TValue> source, Type ownerType)
: base(source, ownerType, null)
{
_inherits = source.Inherits;
}
/// <summary>
/// Gets a value indicating whether the property inherits its value.
/// </summary>
/// <value>
/// A value indicating whether the property inherits its value.
/// </value>
public override bool Inherits => _inherits;
/// <summary>
/// Gets the value validation callback for the property.
/// </summary>
public Func<TValue, bool> ValidateValue { get; }
/// <summary>
/// Gets a value indicating whether this property has any value coercion callbacks defined
/// in its metadata.
/// </summary>
internal bool HasCoercion { get; private set; }
public TValue CoerceValue(IAvaloniaObject instance, TValue baseValue)
{
var metadata = GetMetadata(instance.GetType());
if (metadata.CoerceValue != null)
{
return metadata.CoerceValue.Invoke(instance, baseValue);
}
return baseValue;
}
/// <summary>
/// Gets the default value for the property on the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The default value.</returns>
public TValue GetDefaultValue(Type type)
{
Contract.Requires<ArgumentNullException>(type != null);
return GetMetadata(type).DefaultValue;
}
/// <summary>
/// Gets the property metadata for the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// The property metadata.
/// </returns>
public new StyledPropertyMetadata<TValue> GetMetadata(Type type)
{
return (StyledPropertyMetadata<TValue>)base.GetMetadata(type);
}
/// <summary>
/// Overrides the default value for the property on the specified type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="defaultValue">The default value.</param>
public void OverrideDefaultValue<T>(TValue defaultValue) where T : IAvaloniaObject
{
OverrideDefaultValue(typeof(T), defaultValue);
}
/// <summary>
/// Overrides the default value for the property on the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="defaultValue">The default value.</param>
public void OverrideDefaultValue(Type type, TValue defaultValue)
{
OverrideMetadata(type, new StyledPropertyMetadata<TValue>(defaultValue));
}
/// <summary>
/// Overrides the metadata for the property on the specified type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <param name="metadata">The metadata.</param>
public void OverrideMetadata<T>(StyledPropertyMetadata<TValue> metadata) where T : IAvaloniaObject
{
base.OverrideMetadata(typeof(T), metadata);
}
/// <summary>
/// Overrides the metadata for the property on the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="metadata">The metadata.</param>
public void OverrideMetadata(Type type, StyledPropertyMetadata<TValue> metadata)
{
if (ValidateValue != null)
{
if (!ValidateValue(metadata.DefaultValue))
{
throw new ArgumentException(
$"'{metadata.DefaultValue}' is not a valid default value for '{Name}'.");
}
}
HasCoercion |= metadata.CoerceValue != null;
base.OverrideMetadata(type, metadata);
}
/// <inheritdoc/>
public override void Accept<TData>(IAvaloniaPropertyVisitor<TData> vistor, ref TData data)
{
vistor.Visit(this, ref data);
}
/// <summary>
/// Gets the string representation of the property.
/// </summary>
/// <returns>The property's string representation.</returns>
public override string ToString()
{
return Name;
}
/// <inheritdoc/>
object IStyledPropertyAccessor.GetDefaultValue(Type type) => GetDefaultBoxedValue(type);
/// <inheritdoc/>
internal override void RouteClearValue(IAvaloniaObject o)
{
o.ClearValue<TValue>(this);
}
/// <inheritdoc/>
internal override object RouteGetValue(IAvaloniaObject o)
{
return o.GetValue<TValue>(this);
}
/// <inheritdoc/>
internal override object RouteGetBaseValue(IAvaloniaObject o, BindingPriority maxPriority)
{
var value = o.GetBaseValue<TValue>(this, maxPriority);
return value.HasValue ? value.Value : AvaloniaProperty.UnsetValue;
}
/// <inheritdoc/>
internal override IDisposable RouteSetValue(
IAvaloniaObject o,
object value,
BindingPriority priority)
{
var v = TryConvert(value);
if (v.HasValue)
{
return o.SetValue<TValue>(this, (TValue)v.Value, priority);
}
else if (v.Type == BindingValueType.UnsetValue)
{
o.ClearValue(this);
}
else if (v.HasError)
{
throw v.Error;
}
return null;
}
/// <inheritdoc/>
internal override IDisposable RouteBind(
IAvaloniaObject o,
IObservable<BindingValue<object>> source,
BindingPriority priority)
{
var adapter = TypedBindingAdapter<TValue>.Create(o, this, source);
return o.Bind<TValue>(this, adapter, priority);
}
/// <inheritdoc/>
internal override void RouteInheritanceParentChanged(
AvaloniaObject o,
IAvaloniaObject oldParent)
{
o.InheritanceParentChanged(this, oldParent);
}
private object GetDefaultBoxedValue(Type type)
{
Contract.Requires<ArgumentNullException>(type != null);
return GetMetadata(type).DefaultValue;
}
[DebuggerHidden]
private Func<IAvaloniaObject, TValue, TValue> Cast<THost>(Func<THost, TValue, TValue> validate)
{
return (o, v) => validate((THost)o, v);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace BinxEd
{
/// <summary>
/// Summary description for FormUnion.
/// </summary>
public class FormUnion : System.Windows.Forms.Form
{
private string typeName_;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxTypeName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox comboBoxDisType;
private System.Windows.Forms.TextBox textBoxBlockSize;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Button buttonCancel;
private EditListView listView1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button buttonDelCase;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FormUnion()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBoxTypeName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.comboBoxDisType = new System.Windows.Forms.ComboBox();
this.textBoxBlockSize = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.listView1 = new BinxEd.EditListView();
this.label4 = new System.Windows.Forms.Label();
this.buttonDelCase = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(88, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Type Name:";
//
// textBoxTypeName
//
this.textBoxTypeName.Location = new System.Drawing.Point(104, 8);
this.textBoxTypeName.Name = "textBoxTypeName";
this.textBoxTypeName.Size = new System.Drawing.Size(176, 20);
this.textBoxTypeName.TabIndex = 1;
this.textBoxTypeName.Text = "typeName";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label2.Location = new System.Drawing.Point(16, 40);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 16);
this.label2.TabIndex = 0;
this.label2.Text = "Discriminant";
//
// comboBoxDisType
//
this.comboBoxDisType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxDisType.Items.AddRange(new object[] {
"byte-8",
"unsignedByte-8",
"short-16",
"unsignedShort-16",
"integer-32",
"unsignedInteger-32",
"long-64",
"unsignedLong-64",
"character-8"});
this.comboBoxDisType.Location = new System.Drawing.Point(104, 40);
this.comboBoxDisType.Name = "comboBoxDisType";
this.comboBoxDisType.Size = new System.Drawing.Size(176, 21);
this.comboBoxDisType.TabIndex = 2;
//
// textBoxBlockSize
//
this.textBoxBlockSize.Location = new System.Drawing.Point(104, 72);
this.textBoxBlockSize.Name = "textBoxBlockSize";
this.textBoxBlockSize.Size = new System.Drawing.Size(176, 20);
this.textBoxBlockSize.TabIndex = 5;
this.textBoxBlockSize.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 72);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 24);
this.label3.TabIndex = 4;
this.label3.Text = "Block Size:";
//
// buttonOK
//
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.Location = new System.Drawing.Point(128, 240);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(72, 24);
this.buttonOK.TabIndex = 6;
this.buttonOK.Text = "OK";
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(208, 240);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(72, 24);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Cancel";
//
// listView1
//
this.listView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.listView1.GridLines = true;
this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listView1.LabelWrap = false;
this.listView1.Location = new System.Drawing.Point(16, 120);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(264, 112);
this.listView1.TabIndex = 7;
this.listView1.View = System.Windows.Forms.View.Details;
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 104);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(112, 16);
this.label4.TabIndex = 8;
this.label4.Text = "Cases:";
//
// buttonDelCase
//
this.buttonDelCase.Location = new System.Drawing.Point(16, 240);
this.buttonDelCase.Name = "buttonDelCase";
this.buttonDelCase.Size = new System.Drawing.Size(24, 24);
this.buttonDelCase.TabIndex = 9;
this.buttonDelCase.Text = "X";
this.buttonDelCase.Click += new System.EventHandler(this.buttonDelCase_Click);
//
// FormUnion
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(296, 277);
this.Controls.Add(this.buttonDelCase);
this.Controls.Add(this.label4);
this.Controls.Add(this.listView1);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.textBoxBlockSize);
this.Controls.Add(this.label3);
this.Controls.Add(this.comboBoxDisType);
this.Controls.Add(this.textBoxTypeName);
this.Controls.Add(this.label1);
this.Controls.Add(this.label2);
this.Controls.Add(this.buttonCancel);
this.Name = "FormUnion";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Define Union Type";
this.Closing += new System.ComponentModel.CancelEventHandler(this.FormUnion_Closing);
this.Load += new System.EventHandler(this.FormUnion_Load);
this.ResumeLayout(false);
}
#endregion
private void FormUnion_Load(object sender, System.EventArgs e)
{
listView1.setColumnHeaders(new string[]{"Value","Type","VarName"}, new int[]{50,150,listView1.Width-204});
if (typeName_ != null)
{
textBoxTypeName.Text = typeName_;
}
comboBoxDisType.SelectedIndex = 0;
}
/// <summary>
/// Delete the selected case.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonDelCase_Click(object sender, System.EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
foreach (ListViewItem itm in listView1.SelectedItems)
{
listView1.Items.Remove(itm);
}
}
}
public string TypeName
{
get { return textBoxTypeName.Text; }
set { typeName_ = value; }
}
public string DiscriminantType
{
get { return comboBoxDisType.Text; }
}
public string BlockSize
{
get { return (textBoxBlockSize.Text.Trim().Equals(""))?"0":textBoxBlockSize.Text; }
}
/// <summary>
/// Change label1 to either "Type Name" or "Var Name".
/// </summary>
/// <param name="text"></param>
public void ChangeLabel(string text)
{
label1.Text = text;
}
/// <summary>
/// Set combobox list of data types
/// </summary>
/// <param name="dataTypes"></param>
public void setDataTypeSource(string[] dataTypes)
{
listView1.addDataTypes(dataTypes);
}
/// <summary>
/// Get list of union cases as a ListViewItemCollection
/// </summary>
/// <returns></returns>
public System.Windows.Forms.ListView.ListViewItemCollection getCases()
{
return this.listView1.Items;
}
/// <summary>
/// Validate before closing the window.
/// </summary>
/// <remarks>
/// The following are validated:
/// <list>
/// If it is used to define a type, a type name must be given
/// there must be at least one case
/// no case should be of empty value
/// there should be no duplicate case values
/// only the last case can be void (of no specific case body type)
/// </list>
/// </remarks>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormUnion_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (this.DialogResult == DialogResult.Cancel)
{
return;
}
if (label1.Text.Equals("Type Name:"))
{
if (textBoxTypeName.Text.Trim().Equals(""))
{
MessageBox.Show(this, "Must give a type name");
e.Cancel = true;
return;
}
}
if (listView1.Items.Count <= 0)
{
MessageBox.Show(this, "At least one case");
e.Cancel = true;
}
else
{
trimListView();
//check each case for empty value, duplicate value, no case body
Hashtable vals = new Hashtable();
foreach (ListViewItem itm in listView1.Items)
{
string sval = itm.Text.Trim();
if (sval.Equals(""))
{
MessageBox.Show("Case value must not be empty");
e.Cancel = true;
break;
}
if (vals.Contains(sval))
{
MessageBox.Show("Cannot have duplicate case values");
e.Cancel = true;
break;
}
else
{
vals.Add(sval, sval);
}
if (itm.SubItems[1].Text.Trim().Equals(""))
{
if (itm.Index < listView1.Items.Count-1)
{
MessageBox.Show("Only last case can be void");
e.Cancel = true;
break;
}
}
}
}
}
/// <summary>
/// Remove blank items at the end of the dimension list.
/// </summary>
private void trimListView()
{
for (int i=listView1.Items.Count-1; i>0; i--)
{
ListViewItem itm = listView1.Items[i];
if (itm.Text.Trim().Equals("") && itm.SubItems[1].Text.Trim().Equals(""))
{
listView1.Items.Remove(itm);
}
}
}
}
}
| |
// 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.IO;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.UnitTests;
using Microsoft.Build.Tasks;
using Microsoft.Build.Shared;
using Xunit;
namespace Microsoft.Build.UnitTests
{
sealed public class Move_Tests
{
/// <summary>
/// Basic case of moving a file
/// </summary>
[Fact]
public void BasicMove()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
FileInfo file = new FileInfo(sourceFile);
file.Attributes = file.Attributes | FileAttributes.ReadOnly; // mark read only
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
File.Delete(destinationFile);
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
Assert.True(t.Execute());
Assert.False(File.Exists(sourceFile)); // "Expected the source file to be gone."
Assert.True(File.Exists(destinationFile)); // "Expected the destination file to exist."
Assert.Single(t.DestinationFiles);
Assert.Equal(destinationFile, t.DestinationFiles[0].ItemSpec);
Assert.Single(t.MovedFiles);
Assert.True(((new FileInfo(destinationFile)).Attributes & FileAttributes.ReadOnly) == 0); // should have cleared r/o bit
}
finally
{
File.Delete(sourceFile);
File.Delete(destinationFile);
}
}
/// <summary>
/// Basic case of moving a file but with OverwriteReadOnlyFiles = true.
/// </summary>
[Fact]
public void BasicMoveOverwriteReadOnlyFilesTrue()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
FileInfo file = new FileInfo(sourceFile);
file.Attributes = file.Attributes | FileAttributes.ReadOnly; // mark read only
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
File.Delete(destinationFile);
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.OverwriteReadOnlyFiles = true;
t.DestinationFiles = destinationFiles;
Assert.True(t.Execute());
Assert.False(File.Exists(sourceFile)); // "Expected the source file to be gone."
Assert.True(File.Exists(destinationFile)); // "Expected the destination file to exist."
Assert.Single(t.DestinationFiles);
Assert.Equal(destinationFile, t.DestinationFiles[0].ItemSpec);
Assert.Single(t.MovedFiles);
Assert.True(((new FileInfo(destinationFile)).Attributes & FileAttributes.ReadOnly) == 0); // should have cleared r/o bit
}
finally
{
if (File.Exists(sourceFile))
{
FileInfo file = new FileInfo(sourceFile);
file.Attributes = file.Attributes & ~FileAttributes.ReadOnly; // mark read only
File.Delete(sourceFile);
}
File.Delete(destinationFile);
}
}
/// <summary>
/// File to move does not exist
/// Should not overwrite destination!
/// </summary>
[Fact]
public void NonexistentSource()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
File.Delete(sourceFile);
using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true))
sw.Write("This is a destination temp file.");
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
Assert.False(t.Execute());
Assert.False(File.Exists(sourceFile)); // "Expected the source file to still not exist."
Assert.True(File.Exists(destinationFile)); // "Expected the destination file to still exist."
Assert.Single(t.DestinationFiles);
Assert.Equal(destinationFile, t.DestinationFiles[0].ItemSpec);
Assert.Empty(t.MovedFiles);
string destinationFileContents;
using (StreamReader sr = FileUtilities.OpenRead(destinationFile))
destinationFileContents = sr.ReadToEnd();
Assert.Equal("This is a destination temp file.", destinationFileContents); // "Expected the destination file to still contain the contents of destination file."
}
finally
{
File.Delete(sourceFile);
File.Delete(destinationFile);
}
}
/// <summary>
/// A file can be moved onto itself successfully (it's a no-op).
/// </summary>
[Fact]
public void MoveOverSelfIsSuccessful()
{
string sourceFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
{
sw.Write("This is a temp file.");
}
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(sourceFile) };
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
// Success
Assert.True(t.Execute());
// File is still there.
Assert.True(File.Exists(sourceFile)); // "Source file should be there"
}
finally
{
File.Delete(sourceFile);
}
}
/// <summary>
/// Move should overwrite any destination file except if it's r/o
/// </summary>
[Fact]
public void MoveOverExistingFileReadOnlyNoOverwrite()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true))
sw.Write("This is a destination temp file.");
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
FileInfo file = new FileInfo(destinationFile);
file.Attributes = file.Attributes | FileAttributes.ReadOnly; // mark destination read only
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
Assert.False(t.Execute());
Assert.True(File.Exists(sourceFile)); // "Source file should be present"
string destinationFileContents;
using (StreamReader sr = FileUtilities.OpenRead(destinationFile))
destinationFileContents = sr.ReadToEnd();
Assert.Equal("This is a destination temp file.", destinationFileContents); // "Expected the destination file to be unchanged."
Assert.True(((new FileInfo(destinationFile)).Attributes & FileAttributes.ReadOnly) != 0); // should still be r/o
}
finally
{
File.Delete(sourceFile);
FileInfo file = new FileInfo(destinationFile);
file.Attributes = file.Attributes ^ FileAttributes.ReadOnly; // mark destination writable only
File.Delete(destinationFile);
}
}
/// <summary>
/// Move should overwrite any writable destination file
/// </summary>
[Fact]
public void MoveOverExistingFileDestinationWriteable()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true))
sw.Write("This is a destination temp file.");
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
t.Execute();
Assert.False(File.Exists(sourceFile)); // "Source file should be gone"
string destinationFileContents;
using (StreamReader sr = FileUtilities.OpenRead(destinationFile))
destinationFileContents = sr.ReadToEnd();
Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file."
}
finally
{
File.Delete(sourceFile);
File.Delete(destinationFile);
}
}
/// <summary>
/// Move should overwrite any destination file even if it's not r/o
/// if OverwriteReadOnlyFiles is set.
///
/// This is a regression test for bug 814744 where a move operation with OverwriteReadonlyFiles = true on a destination file with the readonly
/// flag not set caused the readonly flag to be set before the move which caused the move to fail.
/// </summary>
[Fact]
public void MoveOverExistingFileOverwriteReadOnly()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true))
sw.Write("This is a destination temp file.");
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
FileInfo file = new FileInfo(destinationFile);
file.Attributes = file.Attributes & ~FileAttributes.ReadOnly; // mark not read only
Move t = new Move();
t.OverwriteReadOnlyFiles = true;
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
t.Execute();
Assert.False(File.Exists(sourceFile)); // "Source file should be gone"
string destinationFileContents;
using (StreamReader sr = FileUtilities.OpenRead(destinationFile))
destinationFileContents = sr.ReadToEnd();
Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file."
Assert.True(((new FileInfo(destinationFile)).Attributes & FileAttributes.ReadOnly) == 0); // readonly bit should not be set
}
finally
{
File.Delete(sourceFile);
File.Delete(destinationFile);
}
}
/// <summary>
/// Move should overwrite any destination file even if it's r/o
/// if OverwriteReadOnlyFiles is set.
/// </summary>
[Fact]
public void MoveOverExistingFileOverwriteReadOnlyOverWriteReadOnlyFilesTrue()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = FileUtilities.GetTemporaryFile();
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true))
sw.Write("This is a destination temp file.");
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
FileInfo file = new FileInfo(destinationFile);
file.Attributes = file.Attributes | FileAttributes.ReadOnly; // mark read only
Move t = new Move();
t.OverwriteReadOnlyFiles = true;
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
t.Execute();
Assert.False(File.Exists(sourceFile)); // "Source file should be gone"
string destinationFileContents;
using (StreamReader sr = FileUtilities.OpenRead(destinationFile))
destinationFileContents = sr.ReadToEnd();
Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file."
Assert.True(((new FileInfo(destinationFile)).Attributes & FileAttributes.ReadOnly) == 0); // should have cleared r/o bit
}
finally
{
File.Delete(sourceFile);
File.Delete(destinationFile);
}
}
/// <summary>
/// MovedFiles should only include files that were successfully moved
/// (or skipped), not files for which there was an error.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // "Under Unix all filenames are valid and this test is not useful"
public void OutputsOnlyIncludeSuccessfulMoves()
{
string temp = Path.GetTempPath();
string inFile1 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A392");
string inFile2 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A393");
string invalidFile = "!@#$%^&*()|";
string validOutFile = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A394");
try
{
FileStream fs = null;
FileStream fs2 = null;
try
{
fs = File.Create(inFile1);
fs2 = File.Create(inFile2);
}
finally
{
fs.Dispose();
fs2.Dispose();
}
Move t = new Move();
MockEngine engine = new MockEngine(true /* log to console */);
t.BuildEngine = engine;
ITaskItem i1 = new TaskItem(inFile1);
i1.SetMetadata("Locale", "en-GB");
i1.SetMetadata("Color", "taupe");
t.SourceFiles = new ITaskItem[] { new TaskItem(inFile2), i1 };
ITaskItem o1 = new TaskItem(validOutFile);
o1.SetMetadata("Locale", "fr");
o1.SetMetadata("Flavor", "Pumpkin");
t.DestinationFiles = new ITaskItem[] { new TaskItem(invalidFile), o1 };
bool success = t.Execute();
Assert.False(success);
Assert.Single(t.MovedFiles);
Assert.Equal(validOutFile, t.MovedFiles[0].ItemSpec);
Assert.Equal(2, t.DestinationFiles.Length);
Assert.Equal("fr", t.DestinationFiles[1].GetMetadata("Locale"));
// Output ItemSpec should not be overwritten.
Assert.Equal(invalidFile, t.DestinationFiles[0].ItemSpec);
Assert.Equal(validOutFile, t.DestinationFiles[1].ItemSpec);
Assert.Equal(validOutFile, t.MovedFiles[0].ItemSpec);
// Sources attributes should be left untouched.
Assert.Equal("en-GB", t.SourceFiles[1].GetMetadata("Locale"));
Assert.Equal("taupe", t.SourceFiles[1].GetMetadata("Color"));
// Attributes not on Sources should be left untouched.
Assert.Equal("Pumpkin", t.DestinationFiles[1].GetMetadata("Flavor"));
Assert.Equal("Pumpkin", t.MovedFiles[0].GetMetadata("Flavor"));
// Attribute should have been forwarded
Assert.Equal("taupe", t.DestinationFiles[1].GetMetadata("Color"));
Assert.Equal("taupe", t.MovedFiles[0].GetMetadata("Color"));
// Attribute should not have been updated if it already existed on destination
Assert.Equal("fr", t.DestinationFiles[1].GetMetadata("Locale"));
Assert.Equal("fr", t.MovedFiles[0].GetMetadata("Locale"));
}
finally
{
File.Delete(inFile1);
File.Delete(inFile2);
File.Delete(validOutFile);
}
}
/// <summary>
/// Moving a locked file will fail
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void MoveLockedFile()
{
string file = null;
try
{
file = FileUtilities.GetTemporaryFile();
bool result;
Move move = null;
using (StreamWriter writer = FileUtilities.OpenWrite(file, false)) // lock it for write
{
move = new Move();
move.BuildEngine = new MockEngine(true /* log to console */);
move.SourceFiles = new ITaskItem[] { new TaskItem(file) };
move.DestinationFiles = new ITaskItem[] { new TaskItem(file + "2") };
result = move.Execute();
}
Assert.False(result);
((MockEngine)move.BuildEngine).AssertLogContains("MSB3677");
Assert.False(File.Exists(file + "2"));
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Must have destination
/// </summary>
[Fact]
public void NoDestination()
{
Move move = new Move();
move.BuildEngine = new MockEngine();
move.SourceFiles = new ITaskItem[] { new TaskItem("source") };
Assert.False(move.Execute());
((MockEngine)move.BuildEngine).AssertLogContains("MSB3679");
}
/// <summary>
/// Can't have both destination file and directory
/// </summary>
[Fact]
public void DestinationFileAndDirectory()
{
Move move = new Move();
move.BuildEngine = new MockEngine();
move.SourceFiles = new ITaskItem[] { new TaskItem("source") };
move.DestinationFiles = new ITaskItem[] { new TaskItem("x") };
move.DestinationFolder = new TaskItem(Directory.GetCurrentDirectory());
Assert.False(move.Execute());
((MockEngine)move.BuildEngine).AssertLogContains("MSB3678");
}
/// <summary>
/// Can't specify a directory for the destination file
/// </summary>
[Fact]
public void DestinationFileIsDirectory()
{
Move move = new Move();
move.BuildEngine = new MockEngine();
move.SourceFiles = new ITaskItem[] { new TaskItem("source") };
move.DestinationFiles = new ITaskItem[] { new TaskItem(Directory.GetCurrentDirectory()) };
Assert.False(move.Execute());
((MockEngine)move.BuildEngine).AssertLogContains("MSB3676");
}
/// <summary>
/// Can't move a directory to a file
/// </summary>
[Fact]
public void SourceFileIsDirectory()
{
Move move = new Move();
move.BuildEngine = new MockEngine();
move.DestinationFiles = new ITaskItem[] { new TaskItem("destination") };
move.SourceFiles = new ITaskItem[] { new TaskItem(Directory.GetCurrentDirectory()) };
Assert.False(move.Execute());
((MockEngine)move.BuildEngine).AssertLogContains("MSB3681");
}
/// <summary>
/// Moving a file on top of itself should be a success (no-op).
/// Variation with different casing/relativeness.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // "File names under Unix are case-sensitive and this test is not useful"
public void MoveFileOnItself2()
{
string currdir = Directory.GetCurrentDirectory();
string filename = "2A333ED756AF4dc392E728D0F864A396";
string file = Path.Combine(currdir, filename);
try
{
FileStream fs = null;
try
{
fs = File.Create(file);
}
finally
{
fs.Dispose();
}
Move t = new Move();
MockEngine engine = new MockEngine(true /* log to console */);
t.BuildEngine = engine;
t.SourceFiles = new ITaskItem[] { new TaskItem(file) };
t.DestinationFiles = new ITaskItem[] { new TaskItem(filename.ToLowerInvariant()) };
bool success = t.Execute();
Assert.True(success);
Assert.Single(t.DestinationFiles);
Assert.Equal(filename.ToLowerInvariant(), t.DestinationFiles[0].ItemSpec);
Assert.True(File.Exists(file)); // "Source file should be there"
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Moving a file on top of itself should be a success (no-op).
/// Variation with a second move failure.
/// </summary>
[Fact]
public void MoveFileOnItselfAndFailAMove()
{
string temp = Path.GetTempPath();
string file = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A395");
string invalidFile = "!/@#$%^&*()|";
string dest2 = "whatever";
try
{
FileStream fs = null;
try
{
fs = File.Create(file);
}
finally
{
fs.Dispose();
}
Move t = new Move();
MockEngine engine = new MockEngine(true /* log to console */);
t.BuildEngine = engine;
t.SourceFiles = new ITaskItem[] { new TaskItem(file), new TaskItem(invalidFile) };
t.DestinationFiles = new ITaskItem[] { new TaskItem(file), new TaskItem(dest2) };
bool success = t.Execute();
Assert.False(success);
Assert.Equal(2, t.DestinationFiles.Length);
Assert.Equal(file, t.DestinationFiles[0].ItemSpec);
Assert.Equal(dest2, t.DestinationFiles[1].ItemSpec);
Assert.Single(t.MovedFiles);
Assert.Equal(file, t.MovedFiles[0].ItemSpec);
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// DestinationFolder should work.
/// </summary>
[Fact]
public void MoveToNonexistentDestinationFolder()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string temp = Path.GetTempPath();
string destFolder = Path.Combine(temp, "2A333ED756AF4d1392E728D0F864A398");
string destFile = Path.Combine(destFolder, Path.GetFileName(sourceFile));
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true))
sw.Write("This is a source temp file.");
// Don't create the dest folder, let task do that
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFolder = new TaskItem(destFolder);
bool success = t.Execute();
Assert.True(success); // "success"
Assert.False(File.Exists(sourceFile)); // "source gone"
Assert.True(File.Exists(destFile)); // "destination exists"
string destinationFileContents;
using (StreamReader sr = FileUtilities.OpenRead(destFile))
destinationFileContents = sr.ReadToEnd();
Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file."
Assert.Single(t.DestinationFiles);
Assert.Single(t.MovedFiles);
Assert.Equal(destFile, t.DestinationFiles[0].ItemSpec);
Assert.Equal(destFile, t.MovedFiles[0].ItemSpec);
}
finally
{
File.Delete(sourceFile);
File.Delete(destFile);
FileUtilities.DeleteWithoutTrailingBackslash(destFolder);
}
}
/// <summary>
/// DestinationFiles should only include files that were successfully moved,
/// not files for which there was an error.
/// </summary>
[Fact]
public void DestinationFilesLengthNotEqualSourceFilesLength()
{
string temp = Path.GetTempPath();
string inFile1 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A398");
string inFile2 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A399");
string outFile1 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A400");
try
{
FileStream fs = null;
FileStream fs2 = null;
try
{
fs = File.Create(inFile1);
fs2 = File.Create(inFile2);
}
finally
{
fs.Dispose();
fs2.Dispose();
}
Move t = new Move();
MockEngine engine = new MockEngine(true /* log to console */);
t.BuildEngine = engine;
t.SourceFiles = new ITaskItem[] { new TaskItem(inFile1), new TaskItem(inFile2) };
t.DestinationFiles = new ITaskItem[] { new TaskItem(outFile1) };
bool success = t.Execute();
Assert.False(success);
Assert.Single(t.DestinationFiles);
Assert.Null(t.MovedFiles);
Assert.False(File.Exists(outFile1));
}
finally
{
File.Delete(inFile1);
File.Delete(inFile2);
File.Delete(outFile1);
}
}
/// <summary>
/// If the destination path is too long, the task should not bubble up
/// the System.IO.PathTooLongException
/// </summary>
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)]
public void Regress451057_ExitGracefullyIfPathNameIsTooLong()
{
string sourceFile = FileUtilities.GetTemporaryFile();
string destinationFile = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
try
{
using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) // HIGHCHAR: Test writes in UTF8 without preamble.
sw.Write("This is a source temp file.");
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
bool result = t.Execute();
// Expect for there to have been no copies.
Assert.False(result);
}
finally
{
File.Delete(sourceFile);
}
}
/// <summary>
/// If the source path is too long, the task should not bubble up
/// the System.IO.PathTooLongException
/// </summary>
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)]
public void Regress451057_ExitGracefullyIfPathNameIsTooLong2()
{
string sourceFile = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
string destinationFile = FileUtilities.GetTemporaryFile();
ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) };
ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) };
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = sourceFiles;
t.DestinationFiles = destinationFiles;
bool result = t.Execute();
// Expect for there to have been no copies.
Assert.False(result);
}
/// <summary>
/// If the SourceFiles parameter is given invalid path
/// characters, make sure the task exits gracefully.
/// </summary>
[Fact]
public void ExitGracefullyOnInvalidPathCharacters()
{
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = new ITaskItem[] { new TaskItem("foo | bar") };
t.DestinationFolder = new TaskItem("dest");
bool result = t.Execute();
// Expect for there to have been no copies.
Assert.False(result);
}
/// <summary>
/// If the DestinationFile parameter is given invalid path
/// characters, make sure the task exits gracefully.
/// </summary>
[Fact]
public void ExitGracefullyOnInvalidPathCharactersInDestinationFile()
{
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = new ITaskItem[] { new TaskItem("source") };
t.DestinationFiles = new ITaskItem[] { new TaskItem("foo | bar") };
bool result = t.Execute();
// Expect for there to have been no copies.
Assert.False(result);
}
/// <summary>
/// If the DestinationFile parameter is given invalid path
/// characters, make sure the task exits gracefully.
/// </summary>
[Fact]
public void ExitGracefullyOnInvalidPathCharactersInDestinationFolder()
{
Move t = new Move();
t.BuildEngine = new MockEngine(true /* log to console */);
t.SourceFiles = new ITaskItem[] { new TaskItem("source") };
t.DestinationFolder = new TaskItem("foo | bar");
bool result = t.Execute();
// Expect for there to have been no copies.
Assert.False(result);
}
}
}
| |
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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.
*******************************************************************************/
//package com.handmark.pulltorefresh.library;
//import android.content.Context;
//import android.content.res.TypedArray;
//import android.util.AttributeSet;
//import android.util.Log;
//import android.view.Gravity;
//import android.view.View;
//import android.view.ViewGroup;
//import android.view.ViewParent;
//import android.widget.AbsListView;
//import android.widget.AbsListView.OnScrollListener;
//import android.widget.Adapter;
//import android.widget.AdapterView;
//import android.widget.AdapterView.OnItemClickListener;
//import android.widget.FrameLayout;
//import android.widget.LinearLayout;
//import android.widget.ListAdapter;
//import com.handmark.pulltorefresh.library.internal.EmptyViewMethodAccessor;
//import com.handmark.pulltorefresh.library.internal.IndicatorLayout;
using Android.Content;
using Android.Util;
using Android.Views;
using Android.Widget;
using OnScrollListener=Android.Widget.AbsListView.IOnScrollListener;
using OnItemClickListener=Android.Widget.AdapterView.IOnItemClickListener;
using Mode = Com.Handmark.PullToRefresh.Library.PtrMode;
using Android.Content.Res;
using Com.Handmark.PullToRefresh.Library.Internal;
namespace Com.Handmark.PullToRefresh.Library
{
public abstract class PullToRefreshAdapterViewBase<T> : PullToRefreshBase<T>, OnScrollListener where T : AbsListView
{
private static FrameLayout.LayoutParams convertEmptyViewLayoutParams(ViewGroup.LayoutParams lp)
{
FrameLayout.LayoutParams newLp = null;
if (null != lp)
{
newLp = new FrameLayout.LayoutParams(lp);
//if (lp instanceof LinearLayout.LayoutParams) {
// newLp.gravity = ((LinearLayout.LayoutParams) lp).gravity;
//} else {
// newLp.gravity = Gravity.CENTER;
//}
if (lp is LinearLayout.LayoutParams)
{
newLp.Gravity = ((LinearLayout.LayoutParams)lp).Gravity;
}
else
{
newLp.Gravity = GravityFlags.Center;
}
}
return newLp;
}
private bool mLastItemVisible;
private OnScrollListener mOnScrollListener;
private OnLastItemVisibleListener mOnLastItemVisibleListener;
private View mEmptyView;
private IndicatorLayout mIndicatorIvTop;
private IndicatorLayout mIndicatorIvBottom;
private bool mShowIndicator;
private bool mScrollEmptyView = true;
public PullToRefreshAdapterViewBase(Context context)
: base(context)
{
//super(context);
mRefreshableView.SetOnScrollListener(this);
}
public PullToRefreshAdapterViewBase(Context context, IAttributeSet attrs)
:base(context,attrs)
{
//super(context, attrs);
mRefreshableView.SetOnScrollListener(this);
}
public PullToRefreshAdapterViewBase(Context context, Mode mode)
:base(context,mode)
{
//super(context, mode);
mRefreshableView.SetOnScrollListener(this);
}
public PullToRefreshAdapterViewBase(Context context, Mode mode, AnimationStyle animStyle)
:base(context, mode, animStyle)
{
//super(context, mode, animStyle);
mRefreshableView.SetOnScrollListener(this);
}
/**
* Gets whether an indicator graphic should be displayed when the View is in
* a state where a Pull-to-Refresh can happen. An example of this state is
* when the Adapter View is scrolled to the top and the mode is set to
* {@link Mode#PULL_FROM_START}. The default value is <var>true</var> if
* {@link PullToRefreshBase#isPullToRefreshOverScrollEnabled()
* isPullToRefreshOverScrollEnabled()} returns false.
*
* @return true if the indicators will be shown
*/
public bool getShowIndicator()
{
return mShowIndicator;
}
public void OnScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount)
{
if (DEBUG)
{
Log.Debug(LOG_TAG, "First Visible: " + firstVisibleItem + ". Visible Count: " + visibleItemCount
+ ". Total Items:" + totalItemCount);
}
/**
* Set whether the Last Item is Visible. lastVisibleItemIndex is a
* zero-based index, so we minus one totalItemCount to check
*/
if (null != mOnLastItemVisibleListener)
{
mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
}
// If we're showing the indicator, check positions...
if (getShowIndicatorInternal())
{
updateIndicatorViewsVisibility();
}
// Finally call OnScrollListener if we have one
if (null != mOnScrollListener)
{
mOnScrollListener.OnScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
}
public void OnScrollStateChanged(AbsListView view, ScrollState state)
{
/**
* Check that the scrolling has stopped, and that the last item is
* visible.
*/
if (state == ScrollState.Idle && null != mOnLastItemVisibleListener && mLastItemVisible)
{
mOnLastItemVisibleListener.onLastItemVisible();
}
if (null != mOnScrollListener)
{
mOnScrollListener.OnScrollStateChanged(view, state);
}
}
/**
* Pass-through method for {@link PullToRefreshBase#getRefreshableView()
* getRefreshableView()}.
* {@link AdapterView#setAdapter(android.widget.Adapter)}
* setAdapter(adapter)}. This is just for convenience!
*
* @param adapter - Adapter to set
*/
public void setAdapter(IListAdapter adapter)
{
((AdapterView<IListAdapter>)mRefreshableView).Adapter=adapter;
}
/**
* Sets the Empty View to be used by the Adapter View.
* <p/>
* We need it handle it ourselves so that we can Pull-to-Refresh when the
* Empty View is shown.
* <p/>
* Please note, you do <strong>not</strong> usually need to call this method
* yourself. Calling setEmptyView on the AdapterView will automatically call
* this method and set everything up. This includes when the Android
* Framework automatically sets the Empty View based on it's ID.
*
* @param newEmptyView - Empty View to be used
*/
public void setEmptyView(View newEmptyView) {
FrameLayout refreshableViewWrapper = getRefreshableViewWrapper();
if (null != newEmptyView) {
// New view needs to be clickable so that Android recognizes it as a
// target for Touch Events
//newEmptyView.setClickable(true);
newEmptyView.Clickable=true;
IViewParent newEmptyViewParent = newEmptyView.Parent;
if (null != newEmptyViewParent && newEmptyViewParent is ViewGroup) {
((ViewGroup) newEmptyViewParent).RemoveView(newEmptyView);
}
// We need to convert any LayoutParams so that it works in our
// FrameLayout
FrameLayout.LayoutParams lp = convertEmptyViewLayoutParams(newEmptyView.LayoutParameters);
if (null != lp) {
refreshableViewWrapper.AddView(newEmptyView, lp);
} else {
refreshableViewWrapper.AddView(newEmptyView);
}
}
if (mRefreshableView is IEmptyViewMethodAccessor) {
((IEmptyViewMethodAccessor) mRefreshableView).setEmptyViewInternal(newEmptyView);
} else {
mRefreshableView.EmptyView=newEmptyView;
}
mEmptyView = newEmptyView;
}
/**
* Pass-through method for {@link PullToRefreshBase#getRefreshableView()
* getRefreshableView()}.
* {@link AdapterView#setOnItemClickListener(OnItemClickListener)
* setOnItemClickListener(listener)}. This is just for convenience!
*
* @param listener - OnItemClickListener to use
*/
public void setOnItemClickListener(Android.Widget.AdapterView.IOnItemClickListener listener)
{
mRefreshableView.OnItemClickListener=listener;
}
public void setOnLastItemVisibleListener(OnLastItemVisibleListener listener)
{
mOnLastItemVisibleListener = listener;
}
public void setOnScrollListener(OnScrollListener listener)
{
mOnScrollListener = listener;
}
public void setScrollEmptyView(bool doScroll)
{
mScrollEmptyView = doScroll;
}
/**
* Sets whether an indicator graphic should be displayed when the View is in
* a state where a Pull-to-Refresh can happen. An example of this state is
* when the Adapter View is scrolled to the top and the mode is set to
* {@link Mode#PULL_FROM_START}
*
* @param showIndicator - true if the indicators should be shown.
*/
public void setShowIndicator(bool showIndicator)
{
mShowIndicator = showIndicator;
if (getShowIndicatorInternal())
{
// If we're set to Show Indicator, add/update them
addIndicatorViews();
}
else
{
// If not, then remove then
removeIndicatorViews();
}
}
//;
//@Override
protected override void onPullToRefresh()
{
base.onPullToRefresh();
if (getShowIndicatorInternal())
{
switch (getCurrentMode())
{
case Mode.PULL_FROM_END:
mIndicatorIvBottom.pullToRefresh();
break;
case Mode.PULL_FROM_START:
mIndicatorIvTop.pullToRefresh();
break;
default:
// NO-OP
break;
}
}
}
protected virtual void onRefreshing(bool doScroll)
{
base.onRefreshing(doScroll);
if (getShowIndicatorInternal())
{
updateIndicatorViewsVisibility();
}
}
//@Override
protected override void onReleaseToRefresh()
{
base.onReleaseToRefresh();
if (getShowIndicatorInternal())
{
switch (getCurrentMode())
{
case Mode.PULL_FROM_END:
mIndicatorIvBottom.releaseToRefresh();
break;
case Mode.PULL_FROM_START:
mIndicatorIvTop.releaseToRefresh();
break;
default:
// NO-OP
break;
}
}
}
//@Override
protected override void onReset()
{
base.onReset();
if (getShowIndicatorInternal())
{
updateIndicatorViewsVisibility();
}
}
//@Override
protected override void handleStyledAttributes(TypedArray a)
{
// Set Show Indicator to the XML value, or default value
mShowIndicator = a.GetBoolean(Resource.Styleable.PullToRefresh_ptrShowIndicator, !isPullToRefreshOverScrollEnabled());
}
protected override bool isReadyForPullStart()
{
return isFirstItemVisible();
}
protected override bool isReadyForPullEnd()
{
return isLastItemVisible();
}
//@Override
protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
base.OnScrollChanged(l, t, oldl, oldt);
if (null != mEmptyView && !mScrollEmptyView)
{
mEmptyView.ScrollTo(-l, -t);
}
}
//@Override
protected void updateUIForMode()
{
base.updateUIForMode();
// Check Indicator Views consistent with new Mode
if (getShowIndicatorInternal())
{
addIndicatorViews();
}
else
{
removeIndicatorViews();
}
}
private void addIndicatorViews() {
Mode mode = getMode();
FrameLayout refreshableViewWrapper = getRefreshableViewWrapper();
if (PtrModeHelper.showHeaderLoadingLayout(mode) && null == mIndicatorIvTop) {
// If the mode can pull down, and we don't have one set already
mIndicatorIvTop = new IndicatorLayout(Context, Mode.PULL_FROM_START);
FrameLayout.LayoutParams lparams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent,
ViewGroup.LayoutParams.WrapContent);
lparams.RightMargin = Resources.GetDimensionPixelSize(Resource.Dimension.indicator_right_padding);
lparams.Gravity = GravityFlags.Top | GravityFlags.Right;
refreshableViewWrapper.AddView(mIndicatorIvTop, lparams);
} else if (!PtrModeHelper.showHeaderLoadingLayout(mode) && null != mIndicatorIvTop) {
// If we can't pull down, but have a View then remove it
refreshableViewWrapper.RemoveView(mIndicatorIvTop);
mIndicatorIvTop = null;
}
if (PtrModeHelper.showFooterLoadingLayout(mode) && null == mIndicatorIvBottom) {
// If the mode can pull down, and we don't have one set already
mIndicatorIvBottom = new IndicatorLayout(Context, Mode.PULL_FROM_END);
FrameLayout.LayoutParams lparams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent,
ViewGroup.LayoutParams.WrapContent);
lparams.RightMargin = Resources.GetDimensionPixelSize(Resource.Dimension.indicator_right_padding);
lparams.Gravity = GravityFlags.Bottom | GravityFlags.Right;
refreshableViewWrapper.AddView(mIndicatorIvBottom, lparams);
}
else if (!PtrModeHelper.showFooterLoadingLayout(mode) && null != mIndicatorIvBottom)
{
// If we can't pull down, but have a View then remove it
refreshableViewWrapper.RemoveView(mIndicatorIvBottom);
mIndicatorIvBottom = null;
}
}
private bool getShowIndicatorInternal()
{
return mShowIndicator && isPullToRefreshEnabled();
}
private bool isFirstItemVisible() {
IListAdapter adapter = mRefreshableView.Adapter;
if (null == adapter || adapter.IsEmpty) {
if (DEBUG) {
Log.Debug(LOG_TAG, "isFirstItemVisible. Empty View.");
}
return true;
} else {
/**
* This check should really just be:
* mRefreshableView.getFirstVisiblePosition() == 0, but PtRListView
* internally use a HeaderView which messes the positions up. For
* now we'll just add one to account for it and rely on the inner
* condition which checks getTop().
*/
if (mRefreshableView.FirstVisiblePosition <= 1) {
View firstVisibleChild = mRefreshableView.GetChildAt(0);
if (firstVisibleChild != null) {
return firstVisibleChild.Top >= mRefreshableView.Top;
}
}
}
return false;
}
private bool isLastItemVisible()
{
IListAdapter adapter = mRefreshableView.Adapter;
if (null == adapter || adapter.IsEmpty)
{
if (DEBUG)
{
Log.Debug(LOG_TAG, "isLastItemVisible. Empty View.");
}
return true;
}
else
{
int lastItemPosition = mRefreshableView.Count - 1;
int lastVisiblePosition = mRefreshableView.LastVisiblePosition;
if (DEBUG)
{
Log.Debug(LOG_TAG, "isLastItemVisible. Last Item Position: " + lastItemPosition + " Last Visible Pos: "
+ lastVisiblePosition);
}
/**
* This check should really just be: lastVisiblePosition ==
* lastItemPosition, but PtRListView internally uses a FooterView
* which messes the positions up. For me we'll just subtract one to
* account for it and rely on the inner condition which checks
* getBottom().
*/
if (lastVisiblePosition >= lastItemPosition - 1)
{
int childIndex = lastVisiblePosition - mRefreshableView.FirstVisiblePosition;
View lastVisibleChild = mRefreshableView.GetChildAt(childIndex);
if (lastVisibleChild != null)
{
return lastVisibleChild.Bottom <= mRefreshableView.Bottom;
}
}
}
return false;
}
private void removeIndicatorViews()
{
if (null != mIndicatorIvTop)
{
getRefreshableViewWrapper().RemoveView(mIndicatorIvTop);
mIndicatorIvTop = null;
}
if (null != mIndicatorIvBottom)
{
getRefreshableViewWrapper().RemoveView(mIndicatorIvBottom);
mIndicatorIvBottom = null;
}
}
private void updateIndicatorViewsVisibility()
{
if (null != mIndicatorIvTop)
{
if (!isRefreshing() && isReadyForPullStart())
{
if (!mIndicatorIvTop.isVisible())
{
mIndicatorIvTop.show();
}
}
else
{
if (mIndicatorIvTop.isVisible())
{
mIndicatorIvTop.hide();
}
}
}
if (null != mIndicatorIvBottom)
{
if (!isRefreshing() && isReadyForPullEnd())
{
if (!mIndicatorIvBottom.isVisible())
{
mIndicatorIvBottom.show();
}
}
else
{
if (mIndicatorIvBottom.isVisible())
{
mIndicatorIvBottom.hide();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
/// <summary>
/// UInt64.Parse(System.string,NumberStyle style,IFormatProvider provider)
/// </summary>
public class UInt64Parse3
{
public static int Main()
{
UInt64Parse3 ui64parse3 = new UInt64Parse3();
TestLibrary.TestFramework.BeginTestCase("UInt64Parse3");
if (ui64parse3.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("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
UInt64 uintA;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest1: the string corresponding UInt64 is UInt64 MaxValue 1");
try
{
string strA = UInt64.MaxValue.ToString();
NumberStyles style = NumberStyles.Any;
uintA = UInt64.Parse(strA, style, provider);
if (uintA != UInt64.MaxValue)
{
TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
UInt64 uintA;
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest2: the string corresponding UInt64 is UInt64 MaxValue 2");
try
{
string strA = "FFFFFFFFFFFFFFFF";
NumberStyles style = NumberStyles.HexNumber;
uintA = UInt64.Parse(strA, style, provider);
if (uintA != UInt64.MaxValue)
{
TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
UInt64 uintA;
CultureInfo myculture = new CultureInfo("el-GR");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest3: The string parameter contains a number of the form:[ws][sign]digits[ws]");
try
{
string strA = "\u0009" + "abcde" + "\u000A";
NumberStyles style = NumberStyles.HexNumber;
uintA = UInt64.Parse(strA, style, provider);
UInt64 expUIntA = (UInt64)(10 * Math.Pow(16, 4)) + (UInt64)(11 * Math.Pow(16, 3)) + (UInt64)(12 * Math.Pow(16, 2)) + (UInt64)(13 * Math.Pow(16, 1)) + 14;
if (uintA != expUIntA)
{
TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
UInt64 uintA;
CultureInfo myculture = new CultureInfo("el-GR");
IFormatProvider provider = myculture.NumberFormat;
TestLibrary.TestFramework.BeginScenario("PosTest4: The string parameter contains a number of the form:[ws]hexdigits[ws]");
try
{
string strA = "fffff";
NumberStyles style = NumberStyles.HexNumber;
uintA = UInt64.Parse(strA, style, provider);
UInt64 expUIntA = (UInt64)(15 * Math.Pow(16, 4)) + (UInt64)(15 * Math.Pow(16, 3)) + (UInt64)(15 * Math.Pow(16, 2)) + (UInt64)(15 * Math.Pow(16, 1)) + 15;
if (uintA != expUIntA)
{
TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest1: the parameter string is null");
try
{
string strA = null;
uintA = UInt64.Parse(strA, NumberStyles.Integer, provider);
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest2: the style is not the NumberStyles value");
try
{
string strA = "12345";
NumberStyles numstyle = (NumberStyles)(-1);
uintA = UInt64.Parse(strA, numstyle, provider);
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string is not in a format compliant with style 1");
try
{
string strA = "abcd";
NumberStyles style = NumberStyles.Integer;
uintA = UInt64.Parse(strA, style, provider);
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string is not in a format compliant with style 2");
try
{
string strA = "gabcd";
NumberStyles style = NumberStyles.HexNumber;
uintA = UInt64.Parse(strA, style, provider);
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest5: the parameter string corresponding number is less than UInt64 minValue");
try
{
Int64 Testint = (-1) * Convert.ToInt64(this.GetInt64(1, Int64.MaxValue));
string strA = Testint.ToString();
NumberStyles style = NumberStyles.Integer;
uintA = UInt64.Parse(strA, style, provider);
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest6: the parameter string corresponding number is larger than UInt64 maxValue");
try
{
string strA = "18446744073709551616";
NumberStyles style = NumberStyles.Integer;
uintA = UInt64.Parse(strA, style, provider);
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
UInt64 uintA;
IFormatProvider provider = null;
TestLibrary.TestFramework.BeginScenario("NegTest7: The string parameter contains a number of the form:[ws][sign]hexdigits[ws]");
try
{
string strA = "\u0009" + "+" + "abcde" + "\u0009";
NumberStyles style = NumberStyles.HexNumber;
uintA = UInt64.Parse(strA, style, provider);
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N007", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region ForTestObject
private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Talent.V4
{
/// <summary>Settings for <see cref="EventServiceClient"/> instances.</summary>
public sealed partial class EventServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="EventServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="EventServiceSettings"/>.</returns>
public static EventServiceSettings GetDefault() => new EventServiceSettings();
/// <summary>Constructs a new <see cref="EventServiceSettings"/> object with default settings.</summary>
public EventServiceSettings()
{
}
private EventServiceSettings(EventServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateClientEventSettings = existing.CreateClientEventSettings;
OnCopy(existing);
}
partial void OnCopy(EventServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>EventServiceClient.CreateClientEvent</c> and <c>EventServiceClient.CreateClientEventAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 30 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateClientEventSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(30000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="EventServiceSettings"/> object.</returns>
public EventServiceSettings Clone() => new EventServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="EventServiceClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class EventServiceClientBuilder : gaxgrpc::ClientBuilderBase<EventServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public EventServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public EventServiceClientBuilder()
{
UseJwtAccessWithScopes = EventServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref EventServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<EventServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override EventServiceClient Build()
{
EventServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<EventServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<EventServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private EventServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return EventServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<EventServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return EventServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => EventServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => EventServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => EventServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>EventService client wrapper, for convenient use.</summary>
/// <remarks>
/// A service handles client event report.
/// </remarks>
public abstract partial class EventServiceClient
{
/// <summary>
/// The default endpoint for the EventService service, which is a host of "jobs.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "jobs.googleapis.com:443";
/// <summary>The default EventService scopes.</summary>
/// <remarks>
/// The default EventService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/jobs</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="EventServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EventServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="EventServiceClient"/>.</returns>
public static stt::Task<EventServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new EventServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="EventServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="EventServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="EventServiceClient"/>.</returns>
public static EventServiceClient Create() => new EventServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="EventServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="EventServiceSettings"/>.</param>
/// <returns>The created <see cref="EventServiceClient"/>.</returns>
internal static EventServiceClient Create(grpccore::CallInvoker callInvoker, EventServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
EventService.EventServiceClient grpcClient = new EventService.EventServiceClient(callInvoker);
return new EventServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC EventService client</summary>
public virtual EventService.EventServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(string parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(string parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(string parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ClientEvent CreateClientEvent(TenantName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEvent(new CreateClientEventRequest
{
ParentAsTenantName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(TenantName parent, ClientEvent clientEvent, gaxgrpc::CallSettings callSettings = null) =>
CreateClientEventAsync(new CreateClientEventRequest
{
ParentAsTenantName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
ClientEvent = gax::GaxPreconditions.CheckNotNull(clientEvent, nameof(clientEvent)),
}, callSettings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="parent">
/// Required. Resource name of the tenant under which the event is created.
///
/// The format is "projects/{project_id}/tenants/{tenant_id}", for example,
/// "projects/foo/tenants/bar".
/// </param>
/// <param name="clientEvent">
/// Required. Events issued when end user interacts with customer's application that
/// uses Cloud Talent Solution.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ClientEvent> CreateClientEventAsync(TenantName parent, ClientEvent clientEvent, st::CancellationToken cancellationToken) =>
CreateClientEventAsync(parent, clientEvent, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>EventService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A service handles client event report.
/// </remarks>
public sealed partial class EventServiceClientImpl : EventServiceClient
{
private readonly gaxgrpc::ApiCall<CreateClientEventRequest, ClientEvent> _callCreateClientEvent;
/// <summary>
/// Constructs a client wrapper for the EventService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="EventServiceSettings"/> used within this client.</param>
public EventServiceClientImpl(EventService.EventServiceClient grpcClient, EventServiceSettings settings)
{
GrpcClient = grpcClient;
EventServiceSettings effectiveSettings = settings ?? EventServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateClientEvent = clientHelper.BuildApiCall<CreateClientEventRequest, ClientEvent>(grpcClient.CreateClientEventAsync, grpcClient.CreateClientEvent, effectiveSettings.CreateClientEventSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateClientEvent);
Modify_CreateClientEventApiCall(ref _callCreateClientEvent);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateClientEventApiCall(ref gaxgrpc::ApiCall<CreateClientEventRequest, ClientEvent> call);
partial void OnConstruction(EventService.EventServiceClient grpcClient, EventServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC EventService client</summary>
public override EventService.EventServiceClient GrpcClient { get; }
partial void Modify_CreateClientEventRequest(ref CreateClientEventRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ClientEvent CreateClientEvent(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClientEventRequest(ref request, ref callSettings);
return _callCreateClientEvent.Sync(request, callSettings);
}
/// <summary>
/// Report events issued when end user interacts with customer's application
/// that uses Cloud Talent Solution. You may inspect the created events in
/// [self service
/// tools](https://console.cloud.google.com/talent-solution/overview).
/// [Learn
/// more](https://cloud.google.com/talent-solution/docs/management-tools)
/// about self service tools.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ClientEvent> CreateClientEventAsync(CreateClientEventRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateClientEventRequest(ref request, ref callSettings);
return _callCreateClientEvent.Async(request, callSettings);
}
}
}
| |
// <copyright file="LMemLoopbackClient.cs" company="Maxeler">
// Copyright Maxeler. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using com.maxeler.LMemLoopback;
using Thrift;
using Thrift.Protocol;
using Thrift.Transport;
/// <summary>
/// LMemLoopback BasicStatic example
/// </summary>
internal class LMemLoopbackClient
{
/// <summary> Checks if lMemLoopbackDfe and lMemLoopbackCpu return the same value
/// </summary>
/// <param name = "dataOutDFE" > Data output from DFE </param>
/// <param name = "dataOutCPU" > Data output from CPU </param>
/// <param name = "size" > Size of array </param>
/// <returns> Number of elements that doesn't match </returns>
public static int Check(List<int> dataOutDFE, List<int> dataOutCPU, int size)
{
int status = 0;
for (int i = 0; i < size; i++)
{
if (dataOutDFE[i] != dataOutCPU[i])
{
Console.WriteLine("Output data @ {0} = {1} (expected {2})", i, dataOutDFE[i], dataOutCPU[i]);
status++;
}
}
return status;
}
/// <summary> LMemLoopback on CPU </summary>
/// <param name = "size"> Size of arrays </param>
/// <param name = "inA"> First array </param>
/// <param name = "inB"> Second array </param>
/// <returns> Data output </returns>
public static List<int> LMemLoopbackCPU(int size, List<int> inA, List<int> inB)
{
List<int> dataOut = new List<int>();
for (int i = 0; i < size; i++)
{
dataOut.Add(inA[i] + inB[i]);
}
return dataOut;
}
/// <summary> LMemLoopback on DFE </summary>
/// <param name = "size"> Size of arrays </param>
/// <param name = "inA"> First array </param>
/// <param name = "inB"> Second array </param>
/// <returns> Data output </returns>
public static List<int> LMemLoopbackDFE(int size, List<int> inA, List<int> inB)
{
Stopwatch sw = new Stopwatch();
List<int> outData = new List<int>();
int sizeBytes = size * 4;
try
{
// Make socket
sw.Start();
var transport = new TSocket("localhost", 9090);
// Wrap in a protocol
var protocol = new TBinaryProtocol(transport);
// Create a client to use the protocol encoder
var client = new LMemLoopbackService.Client(protocol);
sw.Stop();
Console.WriteLine("Creating a client:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Connect!
sw.Reset();
sw.Start();
transport.Open();
sw.Stop();
Console.WriteLine("Opening connection:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Initialize maxfile
sw.Reset();
sw.Start();
var maxfile = client.LMemLoopback_init();
sw.Stop();
Console.WriteLine("Initializing maxfile:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Load DFE
sw.Reset();
sw.Start();
var engine = client.max_load(maxfile, "*");
sw.Stop();
Console.WriteLine("Loading DFE:\t\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Allocate and send input streams to server
sw.Reset();
sw.Start();
var address_inA = client.malloc_int32_t(size);
client.send_data_int32_t(address_inA, inA);
var address_inB = client.malloc_int32_t(size);
client.send_data_int32_t(address_inB, inB);
sw.Stop();
Console.WriteLine("Sending input data:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Allocate memory for output stream on server
sw.Reset();
sw.Start();
var address_outData = client.malloc_int32_t(size);
sw.Stop();
Console.WriteLine("Allocating memory for output stream on server:\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Writing to LMem
sw.Reset();
sw.Start();
var actions_lmem_write = new LMemLoopback_writeLMem_actions_t_struct();
actions_lmem_write.Param_address = 0;
actions_lmem_write.Param_nbytes = sizeBytes;
actions_lmem_write.Instream_cpu_to_lmem = address_inA;
var address_actions_lmem_write = client.send_LMemLoopback_writeLMem_actions_t(actions_lmem_write);
client.LMemLoopback_writeLMem_run(engine, address_actions_lmem_write);
actions_lmem_write.Param_address = sizeBytes;
actions_lmem_write.Param_nbytes = sizeBytes;
actions_lmem_write.Instream_cpu_to_lmem = address_inB;
address_actions_lmem_write = client.send_LMemLoopback_writeLMem_actions_t(actions_lmem_write);
client.LMemLoopback_writeLMem_run(engine, address_actions_lmem_write);
client.free(address_actions_lmem_write);
sw.Stop();
Console.WriteLine("Writing to LMem:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Action default
sw.Reset();
sw.Start();
var actions = new LMemLoopback_actions_t_struct();
actions.Param_N = size;
var address_actions = client.send_LMemLoopback_actions_t(actions);
client.LMemLoopback_run(engine, address_actions);
client.free(address_actions);
sw.Stop();
Console.WriteLine("LMemLoopback time:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Reading from LMem
sw.Reset();
sw.Start();
var actions_lmem_read = new LMemLoopback_readLMem_actions_t_struct();
actions_lmem_read.Param_address = 2 * sizeBytes;
actions_lmem_read.Param_nbytes = sizeBytes;
actions_lmem_read.Outstream_lmem_to_cpu = address_outData;
var address_actions_lmem_read = client.send_LMemLoopback_readLMem_actions_t(actions_lmem_read);
client.LMemLoopback_readLMem_run(engine, address_actions_lmem_read);
client.free(address_actions_lmem_read);
sw.Stop();
Console.WriteLine("Reading from LMem:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Unload DFE
sw.Reset();
sw.Start();
client.max_unload(engine);
sw.Stop();
Console.WriteLine("Unloading DFE:\t\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Get output stream from server
sw.Reset();
sw.Start();
outData = client.receive_data_int32_t(address_outData, size);
sw.Stop();
Console.WriteLine("Getting output stream:\t(size = {0} bit)\t{1}s", size * 32, sw.Elapsed.TotalMilliseconds / 1000);
// Free allocated memory for streams on server
sw.Reset();
sw.Start();
client.free(address_inA);
client.free(address_inB);
client.free(address_outData);
sw.Stop();
Console.WriteLine("Freeing allocated memory for streams on server:\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Free allocated maxfile data
sw.Reset();
sw.Start();
client.LMemLoopback_free();
sw.Stop();
Console.WriteLine("Freeing allocated maxfile data:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Close!
sw.Reset();
sw.Start();
transport.Close();
sw.Stop();
Console.WriteLine("Closing connection:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
}
catch (SocketException e)
{
Console.WriteLine("Could not connect to the server: {0}.", e.Message);
Environment.Exit(-1);
}
catch (Exception e)
{
Console.WriteLine("An error occured: {0}", e.Message);
Environment.Exit(-1);
}
return outData;
}
/// <summary> Calculates LMemLoopbackCPU and LMemLoopbackDFE
/// and checks if they return the same value.
/// </summary>
/// <param name = "args"> Command line arguments </param>
public static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
int status;
// Generate input data
sw.Start();
const int SIZE = 384;
List<int> inA = new List<int>();
List<int> inB = new List<int>();
for (int i = 0; i < SIZE; i++)
{
inA.Add(i);
inB.Add(SIZE - i);
}
sw.Stop();
Console.WriteLine("Generating input data:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// DFE Output
sw.Reset();
sw.Start();
List<int> dataOutDFE = LMemLoopbackDFE(SIZE, inA, inB);
sw.Stop();
Console.WriteLine("LMemLoopback DFE total time:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// CPU Output
sw.Reset();
sw.Start();
List<int> dataOutCPU = LMemLoopbackCPU(SIZE, inA, inB);
sw.Stop();
Console.WriteLine("LMemLoopback CPU total time:\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
// Checking results
sw.Reset();
sw.Start();
status = Check(dataOutDFE, dataOutCPU, SIZE);
sw.Stop();
Console.WriteLine("Checking results:\t\t\t\t{0}s", sw.Elapsed.TotalMilliseconds / 1000);
if (status > 0)
{
Console.WriteLine("Test failed {0} times! ", status);
Environment.Exit(-1);
}
else
{
Console.WriteLine("Test passed!");
}
}
}
| |
using System;
using Xunit;
using Medo.Device;
using System.IO;
using System.Text;
using System.Threading;
namespace Tests.Medo.Device {
public class CyberCardTests {
[Fact(DisplayName = "CyberCard: Out of range")]
public void NullPort() {
Assert.Throws<ArgumentNullException>(() => {
var _ = new CyberCard(default(String));
});
Assert.Throws<ArgumentNullException>(() => {
var _ = new CyberCard(default(Stream));
});
}
[Fact(DisplayName = "CyberCard: Model information")]
public void ModelInformation() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// survive without data
Assert.Null(device.GetDeviceModel());
Assert.Null(device.GetDeviceFirmware());
Assert.Null(device.GetDeviceSerial());
Assert.Null(device.GetDeviceManufacturer());
Assert.Equal("P4\rP4\rP4\rP4\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried for each
// now we have data
stream.SetupRead(Encoding.ASCII.GetBytes("#OR700LCDRM1U,BFE7103_8S1,000000000000,CyberPower\r"));
Assert.Equal("OR700LCDRM1U", device.GetDeviceModel());
Assert.Equal("BFE7103_8S1", device.GetDeviceFirmware());
Assert.Equal("", device.GetDeviceSerial()); // ignore all 0's serial
Assert.Equal("CyberPower", device.GetDeviceManufacturer());
Assert.Equal("P4\rP4\rP4\rP4\rP4\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried only once more
// subsequent read goes from cache
Assert.Equal("OR700LCDRM1U", device.GetDeviceModel());
Assert.Equal("BFE7103_8S1", device.GetDeviceFirmware());
Assert.Equal("", device.GetDeviceSerial());
Assert.Equal("CyberPower", device.GetDeviceManufacturer());
Assert.Equal("P4\rP4\rP4\rP4\rP4\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // no new reads
}
[Fact(DisplayName = "CyberCard: Capability information")]
public void CapabilityInformation() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// survive without data
Assert.Null(device.GetDeviceCapacity());
Assert.Null(device.GetDeviceCapacityVA());
Assert.Null(device.GetDeviceVoltage());
Assert.Equal("P2\rP2\rP2\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried for each
// now we have data
stream.SetupRead(Encoding.ASCII.GetBytes("#0700,0400,120,057,063\r"));
Assert.Equal(400, device.GetDeviceCapacity());
Assert.Equal(700, device.GetDeviceCapacityVA());
Assert.Equal(120, device.GetDeviceVoltage());
Assert.Equal("P2\rP2\rP2\rP2\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried only once more
// subsequent read goes from cache
Assert.Equal(400, device.GetDeviceCapacity());
Assert.Equal(700, device.GetDeviceCapacityVA());
Assert.Equal(120, device.GetDeviceVoltage());
Assert.Equal("P2\rP2\rP2\rP2\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // no new reads
}
[Fact(DisplayName = "CyberCard: Current information")]
public void CurrentInformation() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// survive without data
Assert.Null(device.GetInputVoltage());
Assert.Null(device.GetOutputVoltage());
Assert.Null(device.GetFrequency());
Assert.Null(device.GetLoadPercentage());
Assert.Null(device.GetBatteryPercentage());
Assert.Null(device.GetBatteryRuntime());
Assert.Equal("D\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried for each
// now we have data
stream.SetupRead(Encoding.ASCII.GetBytes("#I121.0O121.0L042B088F060.1R073S\x80\x84\x90\x80\x80\r"));
Assert.Equal(121, device.GetInputVoltage());
Assert.Equal(121, device.GetOutputVoltage());
Assert.Equal(60.1, device.GetFrequency());
Assert.Equal(0.42, device.GetLoadPercentage());
Assert.Equal(0.88, device.GetBatteryPercentage());
Assert.Equal(73, device.GetBatteryRuntime());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried only once more
// subsequent read goes from cache
Assert.Equal(121, device.GetInputVoltage());
Assert.Equal(121, device.GetOutputVoltage());
Assert.Equal(60.1, device.GetFrequency());
Assert.Equal(0.42, device.GetLoadPercentage());
Assert.Equal(0.88, device.GetBatteryPercentage());
Assert.Equal(73, device.GetBatteryRuntime());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // no new reads
}
[Fact(DisplayName = "CyberCard: Current information (flags)")]
public void CurrentInformation_Flags() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// survive without data
Assert.Null(device.IsPendingPowerOn());
Assert.Null(device.IsPendingPowerOff());
Assert.Null(device.IsTestInProgress());
Assert.Null(device.IsAlarmActive());
Assert.Null(device.IsUsingBattery());
Assert.Null(device.IsBatteryLow());
Assert.Null(device.IsBatteryCharging());
Assert.Null(device.IsBatteryFull());
Assert.Null(device.IsPoweredOff());
Assert.Null(device.IsPoweredOn());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried for each
// now we have data
stream.SetupRead(Encoding.Latin1.GetBytes("#I121.0O121.0L042B088F060.1R073S\x80\x84\x90\x80\x80\r"));
Assert.False(device.IsPendingPowerOn());
Assert.False(device.IsPendingPowerOff());
Assert.False(device.IsTestInProgress());
Assert.False(device.IsAlarmActive());
Assert.False(device.IsUsingBattery());
Assert.False(device.IsBatteryLow());
Assert.True (device.IsBatteryCharging());
Assert.False(device.IsBatteryFull());
Assert.False(device.IsPoweredOff());
Assert.True(device.IsPoweredOn());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried only once more
// subsequent read goes from cache
Assert.False(device.IsPendingPowerOn());
Assert.False(device.IsPendingPowerOff());
Assert.False(device.IsTestInProgress());
Assert.False(device.IsAlarmActive());
Assert.False(device.IsUsingBattery());
Assert.False(device.IsBatteryLow());
Assert.True(device.IsBatteryCharging());
Assert.False(device.IsBatteryFull());
Assert.False(device.IsPoweredOff());
Assert.True(device.IsPoweredOn());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // no new reads
// wait for cache to expire
Thread.Sleep(1000);
stream.SetupRead(Encoding.Latin1.GetBytes("#I000.0O120.0L000B100F060.1R084S\xc0\x81\x88\x80\x80\r"));
Assert.False(device.IsPendingPowerOn());
Assert.False(device.IsPendingPowerOff());
Assert.False(device.IsTestInProgress());
Assert.False(device.IsAlarmActive());
Assert.True(device.IsUsingBattery());
Assert.False(device.IsBatteryLow());
Assert.False(device.IsBatteryCharging());
Assert.False(device.IsBatteryFull());
Assert.False(device.IsPoweredOff());
Assert.True(device.IsPoweredOn());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried only once more
}
[Fact(DisplayName = "CyberCard: Current information (short caching)")]
public void CurrentInformation_Cache() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// we have data
stream.SetupRead(Encoding.ASCII.GetBytes("#I121.0O121.0L042B088F060.1R073S\x80\x84\x90\x80\x80\r"));
Assert.Equal(121, device.GetInputVoltage());
Assert.Equal(121, device.GetOutputVoltage());
Assert.Equal(60.1, device.GetFrequency());
Assert.Equal(0.42, device.GetLoadPercentage());
Assert.Equal(0.88, device.GetBatteryPercentage());
Assert.Equal(73, device.GetBatteryRuntime());
Assert.Equal("D\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // check we tried only once
// subsequent read goes from cache
Assert.Equal(121, device.GetInputVoltage());
Assert.Equal(121, device.GetOutputVoltage());
Assert.Equal(60.1, device.GetFrequency());
Assert.Equal(0.42, device.GetLoadPercentage());
Assert.Equal(0.88, device.GetBatteryPercentage());
Assert.Equal(73, device.GetBatteryRuntime());
Assert.Equal("D\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // no new reads
// expire cache
Thread.Sleep(1000);
Assert.Null(device.GetInputVoltage());
Assert.Null(device.GetOutputVoltage());
Assert.Null(device.GetFrequency());
Assert.Null(device.GetLoadPercentage());
Assert.Null(device.GetBatteryPercentage());
Assert.Null(device.GetBatteryRuntime());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // cache failure causes a new read every time
// new data
stream.SetupRead(Encoding.ASCII.GetBytes("#I121.4O122L41B087F060.4R033S\x80\x84\x90\x80\x80\r"));
Assert.Equal(121.4, device.GetInputVoltage());
Assert.Equal(122, device.GetOutputVoltage());
Assert.Equal(60.4, device.GetFrequency());
Assert.Equal(0.41, device.GetLoadPercentage());
Assert.Equal(0.87, device.GetBatteryPercentage());
Assert.Equal(33, device.GetBatteryRuntime());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // only one new read once we have data
// subsequent read goes from cache
Assert.Equal(121.4, device.GetInputVoltage());
Assert.Equal(122, device.GetOutputVoltage());
Assert.Equal(60.4, device.GetFrequency());
Assert.Equal(0.41, device.GetLoadPercentage());
Assert.Equal(0.87, device.GetBatteryPercentage());
Assert.Equal(33, device.GetBatteryRuntime());
Assert.Equal("D\rD\rD\rD\rD\rD\rD\rD\r", Encoding.ASCII.GetString(stream.ToWrittenArray())); // no new reads
}
[Fact(DisplayName = "CyberCard: Power on")]
public void PowerOn() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// immediate power off
device.PowerOff();
Assert.Equal("S\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
// power off after 60 minutes
device.PowerOff(new TimeSpan(1, 0, 0));
Assert.Equal("S\rS60\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
// power reset
device.PowerReset();
Assert.Equal("S\rS60\rS00R0000\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
// power off after 1 minute and power on after 900 minutes
device.PowerReset(new TimeSpan(0, 1, 0), new TimeSpan(0, 900, 0));
Assert.Equal("S\rS60\rS00R0000\rS01R0900\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
// power on immediatelly
device.PowerOn();
Assert.Equal("S\rS60\rS00R0000\rS01R0900\rW\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
// cancel power off
device.CancelPowerOff();
Assert.Equal("S\rS60\rS00R0000\rS01R0900\rW\rC\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
}
[Fact(DisplayName = "CyberCard: Alarm")]
public void Alarm() {
var stream = new TestStream();
using var device = new CyberCard(stream);
// enable
device.AlarmDisable();
Assert.Equal("C7:0\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
// enable
device.AlarmEnable();
Assert.Equal("C7:0\rC7:1\r", Encoding.ASCII.GetString(stream.ToWrittenArray()));
}
}
}
| |
using ExtendedXmlSerializer.Configuration;
using ExtendedXmlSerializer.ExtensionModel.Content.Members;
using ExtendedXmlSerializer.ExtensionModel.Encryption;
using ExtendedXmlSerializer.ExtensionModel.References;
using ExtendedXmlSerializer.ExtensionModel.Types;
using ExtendedXmlSerializer.ExtensionModel.Xml;
using ExtendedXmlSerializer.Tests.Support;
using ExtendedXmlSerializer.Tests.TestObject;
using JetBrains.Annotations;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Xunit;
using MemberInfo = System.Reflection.MemberInfo;
namespace ExtendedXmlSerializer.Tests.Configuration
{
using Core.Sources;
[SuppressMessage("ReSharper", "TestFileNameWarning")]
public class ConfigurationContainerTests
{
const string Testclass = "UpdatedTestClassName", MemberName = "UpdatedMemberName";
static IConfigurationContainer Configure(Action<IConfigurationContainer> configure)
{
var result = new ConfigurationContainer();
configure(result);
return result;
}
[Fact]
public void ConfigureType()
{
var config = Configure(cfg => cfg.Type<TestClassPrimitiveTypes>());
var configType = config.GetTypeConfiguration(typeof(TestClassPrimitiveTypes));
Assert.NotNull(configType);
Assert.Same(configType, config.GetTypeConfiguration(typeof(TestClassPrimitiveTypes)));
Assert.NotNull(config.GetTypeConfiguration(typeof(TestClassPrimitiveTypesNullable)));
}
[Fact]
public void ConfigureNameForType()
{
var configuration = new ConfigurationContainer();
configuration.Type<SimpleTestSubject>()
.Name(Testclass);
var names = configuration.Root.Find<TypeNamesExtension>()
.Names;
Assert.Equal(names[typeof(SimpleTestSubject).GetTypeInfo()], Testclass);
Assert.False(names.ContainsKey(typeof(TestClassPrimitiveTypesNullable).GetTypeInfo()));
var support = new SerializationSupport(configuration);
var expected = new SimpleTestSubject {BasicProperty = "Hello World!"};
var actual = support.Assert(expected,
@"<?xml version=""1.0"" encoding=""utf-8""?><UpdatedTestClassName xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.Configuration;assembly=ExtendedXmlSerializer.Tests""><BasicProperty>Hello World!</BasicProperty></UpdatedTestClassName>");
Assert.Equal(expected.BasicProperty, actual.BasicProperty);
}
[Fact]
public void ConfigureEntityType()
{
var configuration = new ConfigurationContainer();
Assert.Null(configuration.Root.Find<ReferencesExtension>());
configuration.EnableReferences();
var configType = configuration.GetTypeConfiguration(typeof(TestClassPrimitiveTypes));
var extension = configuration.Root.Find<ReferencesExtension>();
Assert.NotNull(extension);
Assert.Null(extension.Get(configType.Get()));
}
[Fact]
public void ConfigureMigrationForType()
{
var configuration = Configure(cfg => cfg.Type<TestClassPrimitiveTypes>()
.AddMigration(xml => {}));
var type = configuration.GetTypeConfiguration(typeof(TestClassPrimitiveTypes));
Assert.Single(configuration.Root.With<MigrationsExtension>()
.Get(type.Get()));
}
[Fact]
public void ConfigureCustomSerializerForType()
{
var config = Configure(cfg =>
{
var t = cfg.Type<TestClassPrimitiveTypes>();
Assert.Null(cfg.Root.With<CustomSerializationExtension>()
.XmlSerializers.Get(t.Get()));
t.CustomSerializer((writer, types) => {}, element => null);
});
var type = config.GetTypeConfiguration(typeof(TestClassPrimitiveTypes));
Assert.NotNull(config.Root.With<CustomSerializationExtension>()
.XmlSerializers.Get(type.Get()));
}
[Fact]
public void ConfigureProperty()
{
var config = Configure(cfg => cfg.Type<TestClassPrimitiveTypes>()
.Member(p => p.PropChar));
var configType = config.GetTypeConfiguration(typeof(TestClassPrimitiveTypes));
Assert.NotNull(configType.Member("PropChar"));
Assert.Null(configType.Member("TheNewPropertyThatDoesNotExist"));
}
[Fact]
public void ConfigurePropertyAsId()
{
var configuration =
Configure(cfg => cfg.Type<TestClassPrimitiveTypes>()
.EnableReferences(p => p.PropChar));
var configType = configuration.GetTypeConfiguration(typeof(TestClassPrimitiveTypes));
var property = configType.Member("PropChar");
Assert.NotNull(property);
var extension = configuration.Root.Find<ReferencesExtension>();
Assert.NotNull(extension);
Assert.Same(((ISource<MemberInfo>)property).Get(), extension.Get(configType.Get()));
}
[Fact]
public void ConfigureNameForProperty()
{
var configuration =
Configure(cfg => cfg.Type<SimpleTestSubject>()
.Member(p => p.BasicProperty)
.Name(MemberName));
var member =
configuration.GetTypeConfiguration(typeof(SimpleTestSubject))
.Member(nameof(SimpleTestSubject.BasicProperty));
Assert.Equal(configuration.Root.Find<MemberPropertiesExtension>()
.Names[((ISource<MemberInfo>)member).Get()], MemberName);
var support = new SerializationSupport(configuration);
var instance = new SimpleTestSubject {BasicProperty = "Hello World! Testing Member."};
support.Assert(instance,
@"<?xml version=""1.0"" encoding=""utf-8""?><ConfigurationContainerTests-SimpleTestSubject xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.Configuration;assembly=ExtendedXmlSerializer.Tests""><UpdatedMemberName>Hello World! Testing Member.</UpdatedMemberName></ConfigurationContainerTests-SimpleTestSubject>");
}
[Fact]
public void ConfigureOrderForProperty()
{
var order = 0;
var configuration = Configure(cfg => cfg.Type<SimpleOrderedTestSubject>()
.Member(p => p.Property2)
.Order(order));
var member =
configuration.GetTypeConfiguration(typeof(SimpleOrderedTestSubject))
.Member(nameof(SimpleOrderedTestSubject.Property2));
Assert.Equal(configuration.Root.Find<MemberPropertiesExtension>()
.Order[((ISource<MemberInfo>)member).Get()], order);
var instance = new SimpleOrderedTestSubject {Property2 = "World!", Property1 = "Hello"};
new SerializationSupport().Assert(instance,
@"<?xml version=""1.0"" encoding=""utf-8""?><ConfigurationContainerTests-SimpleOrderedTestSubject xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.Configuration;assembly=ExtendedXmlSerializer.Tests""><Property1>Hello</Property1><Property2>World!</Property2></ConfigurationContainerTests-SimpleOrderedTestSubject>");
new SerializationSupport(configuration).Assert(instance,
@"<?xml version=""1.0"" encoding=""utf-8""?><ConfigurationContainerTests-SimpleOrderedTestSubject xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.Configuration;assembly=ExtendedXmlSerializer.Tests""><Property2>World!</Property2><Property1>Hello</Property1></ConfigurationContainerTests-SimpleOrderedTestSubject>");
}
[Fact]
public void ConfigurePropertyAsAttribute()
{
var configuration =
Configure(cfg =>
{
cfg.Type<SimpleTestSubject>()
.Member(p => p.BasicProperty)
.Attribute();
});
var member = configuration.GetTypeConfiguration(typeof(SimpleTestSubject))
.Member(nameof(SimpleTestSubject.BasicProperty));
Assert.True(configuration.Root.With<MemberFormatExtension>()
.Registered.Contains(((ISource<MemberInfo>)member).Get()));
var instance = new SimpleTestSubject {BasicProperty = "Hello World as Attribute!"};
new SerializationSupport(configuration).Assert(instance,
@"<?xml version=""1.0"" encoding=""utf-8""?><ConfigurationContainerTests-SimpleTestSubject BasicProperty=""Hello World as Attribute!"" xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.Configuration;assembly=ExtendedXmlSerializer.Tests"" />");
}
[Fact]
public void ConfigureEncrypt()
{
var configuration = new ConfigurationContainer();
Assert.Null(configuration.Root.Find<EncryptionExtension>());
configuration.UseEncryptionAlgorithm()
.Type<TestClassWithEncryptedData>()
.Member(p => p.Password, x => x.Encrypt())
.Member(p => p.Salary)
.Encrypt();
var extension = configuration.Root.Find<EncryptionExtension>();
Assert.NotNull(extension);
var type = configuration.GetTypeConfiguration(typeof(TestClassWithEncryptedData));
Assert.NotNull(type);
var member = type.Member(nameof(TestClassWithEncryptedData.Salary));
var property = ((ISource<MemberInfo>)member).Get();
Assert.NotNull(property);
Assert.Contains(property, extension.Registered);
const int salary = 6776;
var instance = new TestClassWithEncryptedData {Salary = salary};
var support = new SerializationSupport(configuration);
var actual =
support.Assert(instance,
@"<?xml version=""1.0"" encoding=""utf-8""?><TestClassWithEncryptedData xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.TestObject;assembly=ExtendedXmlSerializer.Tests""><Salary>Njc3Ng==</Salary></TestClassWithEncryptedData>");
Assert.Equal(salary, actual.Salary);
}
[Fact]
public void ConfigureEncryptDifferenetOrder()
{
var container = new ConfigurationContainer();
container.UseAutoFormatting();
Assert.Null(container.Root.Find<EncryptionExtension>());
container.Type<TestClassWithEncryptedData>()
.Member(p => p.Password, x => x.Encrypt())
.Member(p => p.Salary)
.Encrypt();
container.UseEncryptionAlgorithm();
var extension = container.Root.Find<EncryptionExtension>();
Assert.NotNull(extension);
var type = container.GetTypeConfiguration(typeof(TestClassWithEncryptedData));
Assert.NotNull(type);
var member = type.Member(nameof(TestClassWithEncryptedData.Salary));
var property = ((ISource<MemberInfo>)member).Get();
Assert.NotNull(property);
Assert.Contains(property, extension.Registered);
const int salary = 6776;
var instance = new TestClassWithEncryptedData {Salary = salary};
var actual =
new SerializationSupport(container).Assert(instance,
@"<?xml version=""1.0"" encoding=""utf-8""?><TestClassWithEncryptedData Salary=""Njc3Ng=="" xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.TestObject;assembly=ExtendedXmlSerializer.Tests"" />");
Assert.Equal(salary, actual.Salary);
}
class SimpleTestSubject
{
public string BasicProperty { get; set; }
}
class SimpleOrderedTestSubject
{
public string Property1 { [UsedImplicitly] get; set; }
public string Property2 { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace WYZTracker
{
public class Song : NotifierBase
{
public Song()
{
this.Channels = DEFAULT_CHANNELS_COUNT;
initializeSong(false);
}
public Song(byte numChannels)
{
this.Channels = numChannels;
initializeSong(true);
}
public bool[] MutedChannels
{
get { return mutedChannels; }
set
{
mutedChannels = value;
}
}
private void initializeSong(bool defaultValues)
{
Pattern defaultPattern;
Instrument defaultInstrument;
this.Looped = true;
if (defaultValues)
{
defaultPattern = new Pattern(this.channels);
defaultPattern.Name = WYZTracker.Core.Properties.Resources.New;
this.patterns.Add(defaultPattern);
defaultInstrument = new Instrument();
defaultInstrument.ID = "0";
defaultInstrument.Name = WYZTracker.Core.Properties.Resources.Piano;
defaultInstrument.SetVolumeLength(4);
defaultInstrument.Looped = true;
defaultInstrument.LoopStart = 3;
defaultInstrument.Volumes[0] = 8;
defaultInstrument.Volumes[1] = 7;
defaultInstrument.Volumes[2] = 6;
defaultInstrument.Volumes[3] = 5;
this.Instruments.Add(defaultInstrument);
defaultInstrument = new Instrument();
defaultInstrument.ID = "R";
defaultInstrument.Name = "Sawtooth";
defaultInstrument.Looped = false;
defaultInstrument.LoopStart = 0;
this.Instruments.Add(defaultInstrument);
this.mutedChannels = new bool[this.channels + 1];
this.ChipFrequency = (int) LibAYEmu.ChipSpeedsByMachine.MSX;
this.defaultMsxFreqs = true;
this.parameterValue = this.chipFrequency;
}
}
public const int DEFAULT_CHANNELS_COUNT = 3;
private string name;
private byte tempo;
private byte channels;
private List<Pattern> patterns = new List<Pattern>();
private List<int> playOrder = new List<int>();
private Instruments instruments = new Instruments();
private Effects effects = new Effects();
private bool[] mutedChannels = { };
private Int16[] frequencies = { };
private int chipFrequency;
private bool looped;
private bool defaultMsxFreqs;
private bool defaultCpcFreqs;
private bool customFreqs;
private int parameterValue;
private bool parameterizedFreqs;
private int fxChannel;
private int loopToPattern;
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
OnPropertyChanged("Name");
}
}
}
public List<Pattern> Patterns
{
get { return patterns; }
set
{
if (value != patterns)
{
patterns = value;
OnPropertyChanged("Patterns");
}
}
}
public List<int> PlayOrder
{
get { return playOrder; }
set
{
if (value != playOrder)
{
playOrder = value;
OnPropertyChanged("PlayOrder");
}
}
}
public byte Tempo
{
get { return tempo; }
set
{
if (value != tempo)
{
tempo = value;
OnPropertyChanged("Tempo");
}
}
}
public byte Channels
{
get
{
return channels;
}
set
{
if (value != channels)
{
channels = value;
setChannels();
OnPropertyChanged("Channels");
}
}
}
public Instruments Instruments
{
get { return instruments; }
set
{
if (value != instruments)
{
instruments = value;
OnPropertyChanged("Instruments");
}
}
}
public Effects Effects
{
get { return effects; }
set
{
if (value != effects)
{
effects = value;
OnPropertyChanged("Effects");
}
}
}
public Int16[] Frequencies
{
get
{
return frequencies;
}
set
{
if (value != frequencies)
{
frequencies = value;
OnPropertyChanged("Frequencies");
}
}
}
public int ChipFrequency
{
get
{
return chipFrequency;
}
set
{
if (value != chipFrequency)
{
chipFrequency = value;
OnPropertyChanged("ChipFrequency");
}
}
}
public bool Looped
{
get
{
return looped;
}
set
{
if (value != looped)
{
looped = value;
OnPropertyChanged("Looped");
}
}
}
public bool DefaultMsxFreqs
{
get
{
return defaultMsxFreqs;
}
set
{
if (value != defaultMsxFreqs)
{
defaultMsxFreqs = value;
OnPropertyChanged("DefaultMsxFreqs");
}
}
}
public bool DefaultCpcFreqs
{
get
{
return defaultCpcFreqs;
}
set
{
if (value != defaultCpcFreqs)
{
defaultCpcFreqs = value;
OnPropertyChanged("DefaultCpcFreqs");
}
}
}
public bool CustomFreqs
{
get
{
return customFreqs;
}
set
{
if (value != customFreqs)
{
customFreqs = value;
OnPropertyChanged("CustomFreqs");
}
}
}
public bool ParameterizedFreqs
{
get
{
return parameterizedFreqs;
}
set
{
if (value != parameterizedFreqs)
{
parameterizedFreqs = value;
OnPropertyChanged("ParameterizedFreqs");
}
}
}
public int ParameterValue
{
get
{
return parameterValue;
}
set
{
if (value != parameterValue)
{
parameterValue = value;
OnPropertyChanged("ParameterValue");
}
}
}
public int FxChannel
{
get
{
return fxChannel;
}
set
{
if (value != fxChannel)
{
fxChannel = value;
OnPropertyChanged("FxChannel");
}
}
}
public int LoopToPattern
{
get
{
return loopToPattern;
}
set
{
if (value != loopToPattern)
{
loopToPattern = value;
OnPropertyChanged("LoopToPattern");
}
}
}
private void setChannels()
{
foreach (Pattern p in this.patterns)
{
p.Channels = this.channels;
}
Array.Resize(ref this.mutedChannels, this.channels + 1);
}
public Instrument GetInstrument(string id)
{
Instrument instr = null;
foreach (Instrument i in this.Instruments)
{
if (i.ID == id)
{
instr = i;
break;
}
}
return instr;
}
public Effect GetEffect(int id)
{
Effect eff = null;
foreach (Effect e in this.Effects)
{
if (e.ID == id)
{
eff = e;
break;
}
}
return eff;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.Storage.FileProperties;
using Windows.UI.Core;
using WinRTFileAttributes = Windows.Storage.FileAttributes;
namespace System.IO
{
internal sealed partial class WinRTFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.mincore.MAX_PATH; } }
public override int MaxDirectoryPath { get { return Interop.mincore.MAX_DIRECTORY_PATH; } }
private static System.IO.FileAttributes ConvertFileAttributes(WinRTFileAttributes fileAttributes)
{
//namespace Windows.Storage
//{
// [Flags]
// public enum FileAttributes
// {
// Normal = 0,
// ReadOnly = 1,
// Directory = 16,
// Archive = 32,
// Temporary = 256,
// LocallyIncomplete = 512,
// }
//}
//namespace System.IO
//{
// [Flags]
// public enum FileAttributes
// {
// ReadOnly = 1,
// Hidden = 2,
// System = 4,
// Directory = 16,
// Archive = 32,
// Device = 64,
// Normal = 128,
// Temporary = 256,
// SparseFile = 512,
// ReparsePoint = 1024,
// Compressed = 2048,
// Offline = 4096,
// NotContentIndexed = 8192,
// Encrypted = 16384,
// }
//}
// Normal is a special case and happens to have different values in WinRT and Win32.
// It's meant to indicate the absence of other flags. On WinRT this logically is 0,
// however on Win32 it is represented with a discrete value of 128.
return (fileAttributes == WinRTFileAttributes.Normal) ?
FileAttributes.Normal :
(FileAttributes)fileAttributes;
}
private static WinRTFileAttributes ConvertFileAttributes(FileAttributes fileAttributes)
{
// see comment above
// Here we make sure to remove the "normal" value since it is redundant
// We do not mask unsupported values
return (fileAttributes == FileAttributes.Normal) ?
WinRTFileAttributes.Normal :
(WinRTFileAttributes)(fileAttributes & ~FileAttributes.Normal);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
EnsureBackgroundThread();
SynchronousResultOf(CopyFileAsync(sourceFullPath, destFullPath, overwrite));
}
private async Task CopyFileAsync(string sourceFullPath, string destFullPath, bool overwrite)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(sourceFullPath).TranslateWinRTTask(sourceFullPath);
string destDirectory, destFileName;
PathHelpers.SplitDirectoryFile(destFullPath, out destDirectory, out destFileName);
StorageFolder destFolder = await StorageFolder.GetFolderFromPathAsync(destDirectory).TranslateWinRTTask(destDirectory, isDirectory: true);
await file.CopyAsync(destFolder, destFileName, overwrite ? NameCollisionOption.ReplaceExisting : NameCollisionOption.FailIfExists).TranslateWinRTTask(sourceFullPath);
}
public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors)
{
EnsureBackgroundThread();
SynchronousResultOf(ReplaceFileAsync(sourceFullPath, destFullPath, destBackupFullPath, ignoreMetadataErrors));
}
private async Task ReplaceFileAsync(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors)
{
// Copy the destination file to a backup.
if (destBackupFullPath != null)
{
await CopyFileAsync(destFullPath, destBackupFullPath, overwrite: true).ConfigureAwait(false);
}
// Then copy the contents of the source file to the destination file.
await CopyFileAsync(sourceFullPath, destFullPath, overwrite: true).ConfigureAwait(false);
// Finally, delete the source file.
await DeleteFileAsync(sourceFullPath).ConfigureAwait(false);
}
public override void CreateDirectory(string fullPath)
{
EnsureBackgroundThread();
SynchronousResultOf(CreateDirectoryAsync(fullPath, failIfExists: false));
}
private async Task<StorageFolder> CreateDirectoryAsync(string fullPath, bool failIfExists)
{
if (fullPath.Length >= Interop.mincore.MAX_DIRECTORY_PATH)
throw new PathTooLongException(SR.IO_PathTooLong);
Stack<string> stackDir = new Stack<string>();
StorageFolder workingFolder = null;
string workingPath = fullPath;
// walk up the path until we can get a directory
while (workingFolder == null)
{
try
{
workingFolder = await StorageFolder.GetFolderFromPathAsync(workingPath).TranslateWinRTTask(workingPath, isDirectory: true);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
if (workingFolder == null)
{
// we couldn't get the directory, we'll need to create it
string folderName = null;
PathHelpers.SplitDirectoryFile(workingPath, out workingPath, out folderName);
if (String.IsNullOrEmpty(folderName))
{
// we reached the root and it did not exist. we can't create roots.
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, workingPath);
}
stackDir.Push(folderName);
Debug.Assert(!String.IsNullOrEmpty(workingPath));
}
}
Debug.Assert(workingFolder != null);
if (failIfExists && (stackDir.Count == 0))
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_ALREADY_EXISTS, fullPath);
// we have work to do. if stackDir is empty it means we were passed a path to an existing directory.
while (stackDir.Count > 0)
{
// use CreationCollisionOption.OpenIfExists to address a race conditions when creating directories
workingFolder = await workingFolder.CreateFolderAsync(stackDir.Pop(), CreationCollisionOption.OpenIfExists).TranslateWinRTTask(fullPath, isDirectory: true);
}
return workingFolder;
}
public override void DeleteFile(string fullPath)
{
EnsureBackgroundThread();
SynchronousResultOf(DeleteFileAsync(fullPath));
}
private async Task DeleteFileAsync(string fullPath)
{
try
{
// Note the absence of TranslateWinRTTask, we translate below in the catch block.
StorageFile file = await StorageFile.GetFileFromPathAsync(fullPath).AsTask().ConfigureAwait(false);
await file.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().ConfigureAwait(false);
}
catch (Exception exception)
{
// For consistency with Win32 we ignore missing files
if (exception.HResult != HResults.ERROR_FILE_NOT_FOUND)
throw exception.TranslateWinRTException(fullPath);
}
}
public override bool DirectoryExists(string fullPath)
{
EnsureBackgroundThread();
return SynchronousResultOf(DirectoryExistsAsync(fullPath));
}
private async Task<bool> DirectoryExistsAsync(string fullPath)
{
string directoryPath = null, fileName = null;
PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName);
// Rather than call await StorageFolder.GetFolderFromPathAsync(fullPath); and catch FileNotFoundException
// we try to avoid the exception by calling TryGetItemAsync.
// We can still hit an exception if the parent directory doesn't exist but it does provide better performance
// for the existing parent/non-existing directory case and avoids a first chance exception which is a developer
// pain point.
StorageFolder parent = null;
try
{
parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
if (String.IsNullOrEmpty(fileName))
{
// we were given a root
return parent != null;
}
if (parent != null)
{
StorageFolder folder = await parent.TryGetItemAsync(fileName).TranslateWinRTTask(fullPath, isDirectory: true) as StorageFolder;
return folder != null;
}
else
{
// it's possible we don't have access to the parent but do have access to this folder
try
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true);
return folder != null;
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return false;
}
public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
IReadOnlyList<IStorageItem> storageFiles = SynchronousResultOf(EnumerateFileQuery(fullPath, searchPattern, searchOption, searchTarget));
return IteratePathsFromStorageItems(storageFiles);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
IReadOnlyList<IStorageItem> storageFiles = SynchronousResultOf(EnumerateFileQuery(fullPath, searchPattern, searchOption, searchTarget));
return IterateFileSystemInfosFromStorageItems(storageFiles);
}
/// <summary>
/// Translates IStorageItems into FileSystemInfos and yields the results.
/// </summary>
private static IEnumerable<FileSystemInfo> IterateFileSystemInfosFromStorageItems(IReadOnlyList<IStorageItem> storageFiles)
{
int count = storageFiles.Count;
for (int i = 0; i < count; i++)
{
if (storageFiles[i].IsOfType(StorageItemTypes.Folder))
{
yield return new DirectoryInfo(storageFiles[i].Path);
}
else // If it is neither a File nor folder then we treat it as a File.
{
yield return new FileInfo(storageFiles[i].Path);
}
}
}
/// <summary>
/// Translates IStorageItems into string paths and yields the results.
/// </summary>
private static IEnumerable<string> IteratePathsFromStorageItems(IReadOnlyList<IStorageItem> storageFiles)
{
int count = storageFiles.Count;
for (int i = 0; i < count; i++)
{
yield return storageFiles[i].Path;
}
}
private async static Task<IReadOnlyList<IStorageItem>> EnumerateFileQuery(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
// Get a StorageFolder for "path"
string fullPath = Path.GetFullPath(path);
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true);
// Construct a query for the search.
QueryOptions query = new QueryOptions();
// Translate SearchOption into FolderDepth
query.FolderDepth = searchOption == SearchOption.AllDirectories ? FolderDepth.Deep : FolderDepth.Shallow;
// Construct an AQS filter
string normalizedSearchPattern = PathHelpers.NormalizeSearchPattern(searchPattern);
if (normalizedSearchPattern.Length == 0)
{
// An empty searchPattern will return no results and requires no AQS parsing.
return new IStorageItem[0];
}
else
{
// Parse the query as an ItemPathDisplay filter.
string searchPath = PathHelpers.GetFullSearchString(fullPath, normalizedSearchPattern);
string aqs = "System.ItemPathDisplay:~\"" + searchPath + "\"";
query.ApplicationSearchFilter = aqs;
// If the filtered path is deeper than the given user path, we need to get a new folder for it.
// This occurs when someone does something like Enumerate("C:\first\second\", "C:\first\second\third\*").
// When AllDirectories is set this isn't an issue, but for TopDirectoryOnly we have to do some special work
// to make sure something is actually returned when the searchPattern is a subdirectory of the path.
// To do this, we attempt to get a new StorageFolder for the subdirectory and return an empty enumerable
// if we can't.
string searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern);
string userPath = string.IsNullOrEmpty(searchPatternDirName) ? fullPath : Path.Combine(fullPath, searchPatternDirName);
if (userPath != folder.Path)
{
folder = await StorageFolder.GetFolderFromPathAsync(userPath).TranslateWinRTTask(userPath, isDirectory: true);
}
}
// Execute our built query
if (searchTarget == SearchTarget.Files)
{
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(query);
return await queryResult.GetFilesAsync().TranslateWinRTTask(folder.Path, isDirectory: true);
}
else if (searchTarget == SearchTarget.Directories)
{
StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(query);
return await queryResult.GetFoldersAsync().TranslateWinRTTask(folder.Path, isDirectory: true);
}
else
{
StorageItemQueryResult queryResult = folder.CreateItemQueryWithOptions(query);
return await queryResult.GetItemsAsync().TranslateWinRTTask(folder.Path, isDirectory: true);
}
}
public override bool FileExists(string fullPath)
{
EnsureBackgroundThread();
return SynchronousResultOf(FileExistsAsync(fullPath));
}
private async Task<bool> FileExistsAsync(string fullPath)
{
string directoryPath = null, fileName = null;
PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName);
if (String.IsNullOrEmpty(fileName))
{
// No filename was provided
return false;
}
// Rather than call await StorageFile.GetFileFromPathAsync(fullPath); and catch FileNotFoundException
// we try to avoid the exception by calling TryGetItemAsync.
// We can still hit an exception if the directory doesn't exist but it does provide better performance
// for the existing folder/non-existing file case and avoids a first chance exception which is a developer
// pain point.
StorageFolder parent = null;
try
{
parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
StorageFile file = null;
if (parent != null)
{
// The expectation is that this API will never throw, thus it is missing TranslateWinRTTask
file = await parent.TryGetItemAsync(fileName).TranslateWinRTTask(fullPath) as StorageFile;
}
else
{
// it's possible we don't have access to the parent but do have access to this file
try
{
file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
return (file != null) ? file.IsAvailable : false;
}
public override FileAttributes GetAttributes(string fullPath)
{
EnsureBackgroundThread();
return SynchronousResultOf(GetAttributesAsync(fullPath));
}
private async Task<FileAttributes> GetAttributesAsync(string fullPath)
{
IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false);
return ConvertFileAttributes(item.Attributes);
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
EnsureBackgroundThread();
return SynchronousResultOf(GetCreationTimeAsync(fullPath));
}
private async Task<DateTimeOffset> GetCreationTimeAsync(string fullPath)
{
IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false);
return item.DateCreated;
}
public override string GetCurrentDirectory()
{
throw new PlatformNotSupportedException();
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return new WinRTFileSystemObject(fullPath, asDirectory);
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
EnsureBackgroundThread();
return SynchronousResultOf(GetLastAccessTimeAsync(fullPath));
}
private async Task<DateTimeOffset> GetLastAccessTimeAsync(string fullPath)
{
IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false);
return await GetLastAccessTimeAsync(item).ConfigureAwait(false);
}
// declare a static to avoid unnecessary heap allocations
private static readonly string[] s_dateAccessedKey = { "System.DateAccessed" };
private static async Task<DateTimeOffset> GetLastAccessTimeAsync(IStorageItem item)
{
BasicProperties properties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path);
var propertyMap = await properties.RetrievePropertiesAsync(s_dateAccessedKey).TranslateWinRTTask(item.Path);
// shell doesn't expose this metadata on all item types
if (propertyMap.ContainsKey(s_dateAccessedKey[0]))
{
return (DateTimeOffset)propertyMap[s_dateAccessedKey[0]];
}
// fallback to modified date
return properties.DateModified;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
EnsureBackgroundThread();
return SynchronousResultOf(GetLastWriteTimeAsync(fullPath));
}
private async Task<DateTimeOffset> GetLastWriteTimeAsync(string fullPath)
{
IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false);
return await GetLastWriteTimeAsync(item).ConfigureAwait(false);
}
private static async Task<DateTimeOffset> GetLastWriteTimeAsync(IStorageItem item)
{
BasicProperties properties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path);
return properties.DateModified;
}
private static async Task<IStorageItem> GetStorageItemAsync(string fullPath)
{
string directoryPath, itemName;
PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out itemName);
StorageFolder parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);
if (String.IsNullOrEmpty(itemName))
return parent;
return await parent.GetItemAsync(itemName).TranslateWinRTTask(fullPath);
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
EnsureBackgroundThread();
SynchronousResultOf(MoveDirectoryAsync(sourceFullPath, destFullPath));
}
private async Task MoveDirectoryAsync(string sourceFullPath, string destFullPath)
{
StorageFolder sourceFolder = await StorageFolder.GetFolderFromPathAsync(sourceFullPath).TranslateWinRTTask(sourceFullPath, isDirectory: true);
// WinRT doesn't support move, only rename
// If parents are the same, just rename.
string sourceParent, sourceFolderName, destParent, destFolderName;
PathHelpers.SplitDirectoryFile(sourceFullPath, out sourceParent, out sourceFolderName);
PathHelpers.SplitDirectoryFile(destFullPath, out destParent, out destFolderName);
// same parent folder
if (String.Equals(sourceParent, destParent, StringComparison.OrdinalIgnoreCase))
{
// not the same subfolder
if (!String.Equals(sourceFolderName, destFolderName, StringComparison.OrdinalIgnoreCase))
{
await sourceFolder.RenameAsync(destFolderName).TranslateWinRTTask(destFullPath, isDirectory: true);
}
// else : nothing to do
}
else
{
// Otherwise, create the destination and move each item recursively.
// We could do a copy, which would be safer in case of a failure
// We do a move because it has the perf characteristics that match the win32 move
StorageFolder destFolder = await CreateDirectoryAsync(destFullPath, failIfExists: true).ConfigureAwait(false);
await MoveDirectoryAsync(sourceFolder, destFolder).ConfigureAwait(false);
}
}
private async Task MoveDirectoryAsync(StorageFolder sourceFolder, StorageFolder destFolder)
{
foreach (var sourceFile in await sourceFolder.GetFilesAsync().TranslateWinRTTask(sourceFolder.Path, isDirectory: true))
{
await sourceFile.MoveAsync(destFolder).TranslateWinRTTask(sourceFile.Path);
}
foreach (var sourceSubFolder in await sourceFolder.GetFoldersAsync().TranslateWinRTTask(sourceFolder.Path, isDirectory: true))
{
StorageFolder destSubFolder = await destFolder.CreateFolderAsync(sourceSubFolder.Name).TranslateWinRTTask(destFolder.Path, isDirectory: true);
// Recursively move sub-directory
await MoveDirectoryAsync(sourceSubFolder, destSubFolder).ConfigureAwait(false);
}
// sourceFolder should now be empty
await sourceFolder.DeleteAsync(StorageDeleteOption.PermanentDelete).TranslateWinRTTask(sourceFolder.Path, isDirectory: true);
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
EnsureBackgroundThread();
SynchronousResultOf(MoveFileAsync(sourceFullPath, destFullPath));
}
private async Task MoveFileAsync(string sourceFullPath, string destFullPath)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(sourceFullPath).TranslateWinRTTask(sourceFullPath);
string destDirectory, destFileName;
PathHelpers.SplitDirectoryFile(destFullPath, out destDirectory, out destFileName);
// Win32 MoveFileEx will return success if source and destination are the same.
// Comparison is safe here as the caller has normalized both paths.
if (!sourceFullPath.Equals(destFullPath, StringComparison.OrdinalIgnoreCase))
{
StorageFolder destFolder = await StorageFolder.GetFolderFromPathAsync(destDirectory).TranslateWinRTTask(destDirectory, isDirectory: true);
await file.MoveAsync(destFolder, destFileName, NameCollisionOption.FailIfExists).TranslateWinRTTask(sourceFullPath);
}
}
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
EnsureBackgroundThread();
return SynchronousResultOf(OpenAsync(fullPath, mode, access, share, bufferSize, options, parent));
}
private async Task<FileStreamBase> OpenAsync(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
// When trying to open the root directory, we need to throw an Access Denied
if (PathInternal.GetRootLength(fullPath) == fullPath.Length)
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_ACCESS_DENIED, fullPath);
// Win32 CreateFile returns ERROR_PATH_NOT_FOUND when given a path that ends with '\'
if (PathHelpers.EndsInDirectorySeparator(fullPath))
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, fullPath);
StorageFile file = null;
// FileMode
if (mode == FileMode.Open || mode == FileMode.Truncate)
{
file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath);
}
else
{
CreationCollisionOption collisionOptions;
switch (mode)
{
case FileMode.Create:
collisionOptions = CreationCollisionOption.ReplaceExisting;
break;
case FileMode.CreateNew:
collisionOptions = CreationCollisionOption.FailIfExists;
break;
case FileMode.Append:
case FileMode.OpenOrCreate:
default:
collisionOptions = CreationCollisionOption.OpenIfExists;
break;
}
string directoryPath, fileName;
PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName);
StorageFolder directory = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);
file = await directory.CreateFileAsync(fileName, collisionOptions).TranslateWinRTTask(fullPath);
}
// FileAccess: WinRT doesn't support FileAccessMode.Write so we upgrade to ReadWrite
FileAccessMode accessMode = ((access & FileAccess.Write) != 0) ? FileAccessMode.ReadWrite : FileAccessMode.Read;
// FileShare: cannot translate StorageFile uses a different sharing model (oplocks) that is controlled via FileAccessMode
// FileOptions: ignore most values of FileOptions as they are hints and are not supported by WinRT.
// FileOptions.Encrypted is not a hint, and not supported by WinRT, but there is precedent for ignoring this (FAT).
// FileOptions.DeleteOnClose should result in an UnauthorizedAccessException when
// opening a file that can only be read, but we cannot safely reproduce that behavior
// in WinRT without actually deleting the file.
// Instead the failure will occur in the finalizer for WinRTFileStream and be ignored.
// open our stream
Stream stream = (await file.OpenAsync(accessMode).TranslateWinRTTask(fullPath)).AsStream(bufferSize);
if (mode == FileMode.Append)
{
// seek to end.
stream.Seek(0, SeekOrigin.End);
}
else if (mode == FileMode.Truncate)
{
// truncate stream to 0
stream.SetLength(0);
}
return new WinRTFileStream(stream, file, access, options, parent);
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
EnsureBackgroundThread();
SynchronousResultOf(RemoveDirectoryAsync(fullPath, recursive));
}
private async Task RemoveDirectoryAsync(string fullPath, bool recursive)
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true);
// StorageFolder.DeleteAsync will always be recursive. Detect a non-empty folder up front and throw.
if (!recursive && (await folder.GetItemsAsync()).Count != 0)
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_DIR_NOT_EMPTY, fullPath);
// StorageFolder.Delete ignores readonly attribute. Detect and throw.
if ((folder.Attributes & WinRTFileAttributes.ReadOnly) == WinRTFileAttributes.ReadOnly)
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath));
StorageFolder parentFolder = await folder.GetParentAsync().TranslateWinRTTask(fullPath, isDirectory: true);
// StorageFolder.Delete throws on hidden directories but we cannot prevent it.
await folder.DeleteAsync(StorageDeleteOption.PermanentDelete).TranslateWinRTTask(fullPath, isDirectory: true);
// WinRT will ignore failures to delete in cases where files are in use.
// Throw if the folder still remains after successful DeleteAsync
if (null != await (parentFolder.TryGetItemAsync(folder.Name)))
throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_DIR_NOT_EMPTY, fullPath);
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
EnsureBackgroundThread();
SynchronousResultOf(SetAttributesAsync(fullPath, attributes));
}
private async Task SetAttributesAsync(string fullPath, FileAttributes attributes)
{
IStorageItem item = await GetStorageItemAsync(fullPath).ConfigureAwait(false);
await SetAttributesAsync(item, attributes).ConfigureAwait(false);
}
private static async Task SetAttributesAsync(IStorageItem item, FileAttributes attributes)
{
BasicProperties basicProperties = await item.GetBasicPropertiesAsync().TranslateWinRTTask(item.Path);
// This works for only a subset of attributes, unsupported attributes are ignored.
// We don't mask the attributes since WinRT just ignores the unsupported ones and flowing
// them enables possible lightup in the future.
var property = new KeyValuePair<string, object>("System.FileAttributes", (UInt32)ConvertFileAttributes(attributes));
try
{
await basicProperties.SavePropertiesAsync(new[] { property }).AsTask().ConfigureAwait(false);
}
catch (Exception exception)
{
if (exception.HResult != HResults.ERROR_INVALID_PARAMETER)
throw new ArgumentException(SR.Arg_InvalidFileAttrs);
throw exception.TranslateWinRTException(item.Path);
}
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
// intentionally noop : not supported
// "System.DateCreated" property is readonly
}
public override void SetCurrentDirectory(string fullPath)
{
throw new PlatformNotSupportedException();
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
// intentionally noop
// "System.DateAccessed" property is readonly
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
// intentionally noop : not supported
// "System.DateModified" property is readonly
}
public override string[] GetLogicalDrives()
{
return DriveInfoInternal.GetLogicalDrives();
}
#region Task Utility
private static void EnsureBackgroundThread()
{
// WinRT async operations on brokered files require posting a message back to the UI thread.
// If we were to run a sync method on the UI thread we'd deadlock. Throw instead.
if (IsUIThread())
throw new InvalidOperationException(SR.IO_SyncOpOnUIThread);
}
private static bool IsUIThread()
{
CoreWindow window = CoreWindow.GetForCurrentThread();
return window != null && window.Dispatcher != null && window.Dispatcher.HasThreadAccess;
}
private static void SynchronousResultOf(Task task)
{
WaitForTask(task);
}
private static TResult SynchronousResultOf<TResult>(Task<TResult> task)
{
WaitForTask(task);
return task.Result;
}
// this needs to be separate from SynchronousResultOf so that SynchronousResultOf<T> can call it.
private static void WaitForTask(Task task)
{
// This should never be called from the UI thread since it can deadlock
// Throwing here, however, is too late since work has already been started
// Instead we assert here so that our tests can catch cases where we forgot to
// call EnsureBackgroundThread before starting the task.
Debug.Assert(!IsUIThread());
task.GetAwaiter().GetResult();
}
#endregion Task Utility
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
#pragma warning disable SA1649
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Irony.Ast;
namespace Irony.Parsing
{
[Flags]
public enum StringOptions : short
{
None = 0,
IsChar = 0x01,
AllowsDoubledQuote = 0x02, //Convert doubled start/end symbol to a single symbol; for ex. in SQL, '' -> '
AllowsLineBreak = 0x04,
IsTemplate = 0x08, //Can include embedded expressions that should be evaluated on the fly; ex in Ruby: "hello #{name}"
NoEscapes = 0x10,
AllowsUEscapes = 0x20,
AllowsXEscapes = 0x40,
AllowsOctalEscapes = 0x80,
AllowsAllEscapes = AllowsUEscapes | AllowsXEscapes | AllowsOctalEscapes,
}
//Container for settings of tempate string parser, to interpet strings having embedded values or expressions
// like in Ruby:
// "Hello, #{name}"
// Default values match settings for Ruby strings
public class StringTemplateSettings
{
public string StartTag = "#{";
public string EndTag = "}";
public NonTerminal ExpressionRoot;
}
public class StringLiteral : CompoundTerminalBase
{
public enum StringFlagsInternal : short
{
HasEscapes = 0x100,
}
#region StringSubType
private class StringSubType
{
internal readonly string Start, End;
internal readonly StringOptions Flags;
internal readonly byte Index;
internal StringSubType(string start, string end, StringOptions flags, byte index)
{
this.Start = start;
this.End = end;
this.Flags = flags;
this.Index = index;
}
internal static int LongerStartFirst(StringSubType x, StringSubType y)
{
try
{//in case any of them is null
if (x.Start.Length > y.Start.Length)
{
return -1;
}
}
catch { }
return 0;
}
}
private class StringSubTypeList : List<StringSubType>
{
internal void Add(string start, string end, StringOptions flags)
{
base.Add(new StringSubType(start, end, flags, (byte)this.Count));
}
}
#endregion
#region constructors and initialization
public StringLiteral(string name)
: base(name)
{
base.SetFlag(TermFlags.IsLiteral);
}
public StringLiteral(string name, string startEndSymbol, StringOptions options)
: this(name)
{
this._subtypes.Add(startEndSymbol, startEndSymbol, options);
}
public StringLiteral(string name, string startEndSymbol)
: this(name, startEndSymbol, StringOptions.None) { }
public StringLiteral(string name, string startEndSymbol, StringOptions options, Type astNodeType)
: this(name, startEndSymbol, options)
{
base.AstConfig.NodeType = astNodeType;
}
public StringLiteral(string name, string startEndSymbol, StringOptions options, AstNodeCreator astNodeCreator)
: this(name, startEndSymbol, options)
{
base.AstConfig.NodeCreator = astNodeCreator;
}
public void AddStartEnd(string startEndSymbol, StringOptions stringOptions)
{
this.AddStartEnd(startEndSymbol, startEndSymbol, stringOptions);
}
public void AddStartEnd(string startSymbol, string endSymbol, StringOptions stringOptions)
{
this._subtypes.Add(startSymbol, endSymbol, stringOptions);
}
public void AddPrefix(string prefix, StringOptions flags)
{
base.AddPrefixFlag(prefix, (short)flags);
}
#endregion
#region Properties/Fields
private readonly StringSubTypeList _subtypes = new StringSubTypeList();
private string _startSymbolsFirsts; //first chars of start-end symbols
#endregion
#region overrides: Init, GetFirsts, ReadBody, etc...
public override void Init(GrammarData grammarData)
{
base.Init(grammarData);
this._startSymbolsFirsts = string.Empty;
if (this._subtypes.Count == 0)
{
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrInvStrDef, this.Name); //"Error in string literal [{0}]: No start/end symbols specified."
return;
}
//collect all start-end symbols in lists and create strings of first chars
var allStartSymbols = new StringSet(); //to detect duplicate start symbols
this._subtypes.Sort(StringSubType.LongerStartFirst);
bool isTemplate = false;
foreach (StringSubType subType in this._subtypes)
{
if (allStartSymbols.Contains(subType.Start))
{
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null,
Resources.ErrDupStartSymbolStr, subType.Start, this.Name); //"Duplicate start symbol {0} in string literal [{1}]."
}
allStartSymbols.Add(subType.Start);
this._startSymbolsFirsts += subType.Start[0].ToString();
if ((subType.Flags & StringOptions.IsTemplate) != 0)
{
isTemplate = true;
}
}
if (!this.CaseSensitivePrefixesSuffixes)
{
this._startSymbolsFirsts = this._startSymbolsFirsts.ToLower() + this._startSymbolsFirsts.ToUpper();
}
//Set multiline flag
foreach (StringSubType info in this._subtypes)
{
if ((info.Flags & StringOptions.AllowsLineBreak) != 0)
{
this.SetFlag(TermFlags.IsMultiline);
break;
}
}
//For templates only
if (isTemplate)
{
//Check that template settings object is provided
var templateSettings = this.AstConfig.Data as StringTemplateSettings;
if (templateSettings == null)
{
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplNoSettings, this.Name); //"Error in string literal [{0}]: IsTemplate flag is set, but TemplateSettings is not provided."
}
else if (templateSettings.ExpressionRoot == null)
{
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplMissingExprRoot, this.Name); //""
}
else if (!this.Grammar.SnippetRoots.Contains(templateSettings.ExpressionRoot))
{
grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplExprNotRoot, this.Name); //""
}
}//if
//Create editor info
if (this.EditorInfo == null)
{
this.EditorInfo = new TokenEditorInfo(TokenType.String, TokenColor.String, TokenTriggers.None);
}
}//method
public override IList<string> GetFirsts()
{
StringList result = new StringList();
result.AddRange(this.Prefixes);
//we assume that prefix is always optional, so string can start with start-end symbol
foreach (char ch in this._startSymbolsFirsts)
{
result.Add(ch.ToString());
}
return result;
}
protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details)
{
if (!details.PartialContinues)
{
if (!this.ReadStartSymbol(source, details))
{
return false;
}
}
return this.CompleteReadBody(source, details);
}
private bool CompleteReadBody(ISourceStream source, CompoundTokenDetails details)
{
bool escapeEnabled = !details.IsSet((short)StringOptions.NoEscapes);
int start = source.PreviewPosition;
string endQuoteSymbol = details.EndSymbol;
string endQuoteDoubled = endQuoteSymbol + endQuoteSymbol; //doubled quote symbol
bool lineBreakAllowed = details.IsSet((short)StringOptions.AllowsLineBreak);
//1. Find the string end
// first get the position of the next line break; we are interested in it to detect malformed string,
// therefore do it only if linebreak is NOT allowed; if linebreak is allowed, set it to -1 (we don't care).
int nlPos = lineBreakAllowed ? -1 : source.Text.IndexOf('\n', source.PreviewPosition);
//fix by ashmind for EOF right after opening symbol
while (true)
{
int endPos = source.Text.IndexOf(endQuoteSymbol, source.PreviewPosition);
//Check for partial token in line-scanning mode
if (endPos < 0 && details.PartialOk && lineBreakAllowed)
{
this.ProcessPartialBody(source, details);
return true;
}
//Check for malformed string: either EndSymbol not found, or LineBreak is found before EndSymbol
bool malformed = endPos < 0 || nlPos >= 0 && nlPos < endPos;
if (malformed)
{
//Set source position for recovery: move to the next line if linebreak is not allowed.
if (nlPos > 0)
{
endPos = nlPos;
}
if (endPos > 0)
{
source.PreviewPosition = endPos + 1;
}
details.Error = Resources.ErrBadStrLiteral;// "Mal-formed string literal - cannot find termination symbol.";
return true; //we did find start symbol, so it is definitely string, only malformed
}//if malformed
if (source.EOF())
{
return true;
}
//We found EndSymbol - check if it is escaped; if yes, skip it and continue search
if (escapeEnabled && this.IsEndQuoteEscaped(source.Text, endPos))
{
source.PreviewPosition = endPos + endQuoteSymbol.Length;
continue; //searching for end symbol
}
//Check if it is doubled end symbol
source.PreviewPosition = endPos;
if (details.IsSet((short)StringOptions.AllowsDoubledQuote) && source.MatchSymbol(endQuoteDoubled))
{
source.PreviewPosition = endPos + endQuoteDoubled.Length;
continue;
}//checking for doubled end symbol
//Ok, this is normal endSymbol that terminates the string.
// Advance source position and get out from the loop
details.Body = source.Text.Substring(start, endPos - start);
source.PreviewPosition = endPos + endQuoteSymbol.Length;
return true; //if we come here it means we're done - we found string end.
} //end of loop to find string end;
}
private void ProcessPartialBody(ISourceStream source, CompoundTokenDetails details)
{
int from = source.PreviewPosition;
source.PreviewPosition = source.Text.Length;
details.Body = source.Text.Substring(from, source.PreviewPosition - from);
details.IsPartial = true;
}
protected override void InitDetails(ParsingContext context, CompoundTerminalBase.CompoundTokenDetails details)
{
base.InitDetails(context, details);
if (context.VsLineScanState.Value != 0)
{
//we are continuing partial string on the next line
details.Flags = context.VsLineScanState.TerminalFlags;
details.SubTypeIndex = context.VsLineScanState.TokenSubType;
var stringInfo = this._subtypes[context.VsLineScanState.TokenSubType];
details.StartSymbol = stringInfo.Start;
details.EndSymbol = stringInfo.End;
}
}
protected override void ReadSuffix(ISourceStream source, CompoundTerminalBase.CompoundTokenDetails details)
{
base.ReadSuffix(source, details);
//"char" type can be identified by suffix (like VB where c suffix identifies char)
// in this case we have details.TypeCodes[0] == char and we need to set the IsChar flag
if (details.TypeCodes != null && details.TypeCodes[0] == TypeCode.Char)
{
details.Flags |= (int)StringOptions.IsChar;
}
else
//we may have IsChar flag set (from startEndSymbol, like in c# single quote identifies char)
// in this case set type code
if (details.IsSet((short)StringOptions.IsChar))
{
details.TypeCodes = new TypeCode[] { TypeCode.Char };
}
}
private bool IsEndQuoteEscaped(string text, int quotePosition)
{
bool escaped = false;
int p = quotePosition - 1;
while (p > 0 && text[p] == this.EscapeChar)
{
escaped = !escaped;
p--;
}
return escaped;
}
private bool ReadStartSymbol(ISourceStream source, CompoundTokenDetails details)
{
if (this._startSymbolsFirsts.IndexOf(source.PreviewChar) < 0)
{
return false;
}
foreach (StringSubType subType in this._subtypes)
{
if (!source.MatchSymbol(subType.Start))
{
continue;
}
//We found start symbol
details.StartSymbol = subType.Start;
details.EndSymbol = subType.End;
details.Flags |= (short)subType.Flags;
details.SubTypeIndex = subType.Index;
source.PreviewPosition += subType.Start.Length;
return true;
}//foreach
return false;
}//method
//Extract the string content from lexeme, adjusts the escaped and double-end symbols
protected override bool ConvertValue(CompoundTokenDetails details)
{
string value = details.Body;
bool escapeEnabled = !details.IsSet((short)StringOptions.NoEscapes);
//Fix all escapes
if (escapeEnabled && value.IndexOf(this.EscapeChar) >= 0)
{
details.Flags |= (int)StringFlagsInternal.HasEscapes;
string[] arr = value.Split(this.EscapeChar);
bool ignoreNext = false;
//we skip the 0 element as it is not preceeded by "\"
for (int i = 1; i < arr.Length; i++)
{
if (ignoreNext)
{
ignoreNext = false;
continue;
}
string s = arr[i];
if (string.IsNullOrEmpty(s))
{
//it is "\\" - escaped escape symbol.
arr[i] = @"\";
ignoreNext = true;
continue;
}
//The char is being escaped is the first one; replace it with char in Escapes table
char first = s[0];
char newFirst;
if (this.Escapes.TryGetValue(first, out newFirst))
arr[i] = newFirst + s.Substring(1);
else
{
arr[i] = this.HandleSpecialEscape(arr[i], details);
}//else
}//for i
value = string.Join(string.Empty, arr);
}// if EscapeEnabled
//Check for doubled end symbol
string endSymbol = details.EndSymbol;
if (details.IsSet((short)StringOptions.AllowsDoubledQuote) && value.IndexOf(endSymbol) >= 0)
{
value = value.Replace(endSymbol + endSymbol, endSymbol);
}
if (details.IsSet((short)StringOptions.IsChar))
{
if (value.Length != 1)
{
details.Error = Resources.ErrBadChar; //"Invalid length of char literal - should be a single character.";
return false;
}
details.Value = value[0];
}
else
{
details.TypeCodes = new TypeCode[] { TypeCode.String };
details.Value = value;
}
return true;
}
//Should support: \Udddddddd, \udddd, \xdddd, \N{name}, \0, \ddd (octal),
protected virtual string HandleSpecialEscape(string segment, CompoundTokenDetails details)
{
if (string.IsNullOrEmpty(segment))
{
return string.Empty;
}
int len, p; string digits; char ch; string result;
char first = segment[0];
switch (first)
{
case 'u':
case 'U':
if (details.IsSet((short)StringOptions.AllowsUEscapes))
{
len = (first == 'u' ? 4 : 8);
if (segment.Length < len + 1)
{
details.Error = string.Format(Resources.ErrBadUnEscape, segment.Substring(len + 1), len);// "Invalid unicode escape ({0}), expected {1} hex digits."
return segment;
}
digits = segment.Substring(1, len);
ch = (char)Convert.ToUInt32(digits, 16);
result = ch + segment.Substring(len + 1);
return result;
}//if
break;
case 'x':
if (details.IsSet((short)StringOptions.AllowsXEscapes))
{
//x-escape allows variable number of digits, from one to 4; let's count them
p = 1; //current position
while (p < 5 && p < segment.Length)
{
if (Strings.HexDigits.IndexOf(segment[p]) < 0)
{
break;
}
p++;
}
//p now point to char right after the last digit
if (p <= 1)
{
details.Error = Resources.ErrBadXEscape; // @"Invalid \x escape, at least one digit expected.";
return segment;
}
digits = segment.Substring(1, p - 1);
ch = (char)Convert.ToUInt32(digits, 16);
result = ch + segment.Substring(p);
return result;
}//if
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
if (details.IsSet((short)StringOptions.AllowsOctalEscapes))
{
//octal escape allows variable number of digits, from one to 3; let's count them
p = 0; //current position
while (p < 3 && p < segment.Length)
{
if (Strings.OctalDigits.IndexOf(segment[p]) < 0)
{
break;
}
p++;
}
//p now point to char right after the last digit
digits = segment.Substring(0, p);
ch = (char)Convert.ToUInt32(digits, 8);
result = ch + segment.Substring(p);
return result;
}//if
break;
}//switch
details.Error = string.Format(Resources.ErrInvEscape, segment); //"Invalid escape sequence: \{0}"
return segment;
}//method
#endregion
}//class
}//namespace
| |
namespace Banshee
{
partial class WindowPlayer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WindowPlayer));
this.mainMenu = new System.Windows.Forms.MenuStrip();
this.musicToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importMusicToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.quitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.selectNoneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pluginsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.styleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.blueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.silverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.blackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.playbackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.playToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.previousToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.nextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.seekForwardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.seekBackwardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.restartSongToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.repeatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.allToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.singleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.noneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.shuffleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showCoverartToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showFullScreenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showEqualiserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.columnsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.showLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.jumpToPlayingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.byAlbumToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.byArtistToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.byGenreToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.versionInfoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SourceSplitter = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.event_panel = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.cover_art_view = new Banshee.Base.Winforms.Widgets.CoverArtView();
this.LibraryContainer = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.playlistContainer = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.playlistView = new Banshee.PlayListView();
this.playlist_header_event_box = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.dapDiskUsageBar = new System.Windows.Forms.ProgressBar();
this.ViewNameLabel = new System.Windows.Forms.Label();
this.searchEntry1 = new Banshee.Base.Winforms.Controls.SearchEntry();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.header_container = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.trackInfoHeader = new Banshee.Widgets.TrackInfoHeader();
this.additional_action_buttons_box = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.sync_dap_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.volumeButton = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.seekpanel = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.next_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.previous_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.playpause_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.status_panel = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.LabelStatusBar = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.song_properties_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.repeat_toggle_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.shuffle_toggle_button = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.Manager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.posTimer = new System.Windows.Forms.Timer(this.components);
this.mainMenu.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.SourceSplitter)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.SourceSplitter.Panel1)).BeginInit();
this.SourceSplitter.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.SourceSplitter.Panel2)).BeginInit();
this.SourceSplitter.Panel2.SuspendLayout();
this.SourceSplitter.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.event_panel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cover_art_view)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LibraryContainer)).BeginInit();
this.LibraryContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.playlistContainer)).BeginInit();
this.playlistContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.playlist_header_event_box)).BeginInit();
this.playlist_header_event_box.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.header_container)).BeginInit();
this.header_container.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.additional_action_buttons_box)).BeginInit();
this.additional_action_buttons_box.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.sync_dap_button)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.volumeButton)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.seekpanel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel2)).BeginInit();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.next_button)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.previous_button)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.playpause_button)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.status_panel)).BeginInit();
this.status_panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.LabelStatusBar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.song_properties_button)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.repeat_toggle_button)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.shuffle_toggle_button)).BeginInit();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.Font = new System.Drawing.Font("Segoe UI", 9F);
this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.musicToolStripMenuItem,
this.editToolStripMenuItem,
this.playbackToolStripMenuItem,
this.viewToolStripMenuItem,
this.helpToolStripMenuItem});
this.mainMenu.Location = new System.Drawing.Point(0, 0);
this.mainMenu.Name = "mainMenu";
this.mainMenu.Size = new System.Drawing.Size(655, 24);
this.mainMenu.TabIndex = 0;
this.mainMenu.Text = "menuStrip1";
//
// musicToolStripMenuItem
//
this.musicToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.importFolderToolStripMenuItem,
this.importFilesToolStripMenuItem,
this.importMusicToolStripMenuItem,
this.propertiesToolStripMenuItem,
this.quitToolStripMenuItem});
this.musicToolStripMenuItem.Name = "musicToolStripMenuItem";
this.musicToolStripMenuItem.Size = new System.Drawing.Size(51, 20);
this.musicToolStripMenuItem.Text = "&Music";
//
// importFolderToolStripMenuItem
//
this.importFolderToolStripMenuItem.Name = "importFolderToolStripMenuItem";
this.importFolderToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.importFolderToolStripMenuItem.Text = "Import Folder";
this.importFolderToolStripMenuItem.Click += new System.EventHandler(this.importFolderToolStripMenuItem_Click);
//
// importFilesToolStripMenuItem
//
this.importFilesToolStripMenuItem.Name = "importFilesToolStripMenuItem";
this.importFilesToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.importFilesToolStripMenuItem.Text = "Import Files";
this.importFilesToolStripMenuItem.Click += new System.EventHandler(this.importFilesToolStripMenuItem_Click);
//
// importMusicToolStripMenuItem
//
this.importMusicToolStripMenuItem.Name = "importMusicToolStripMenuItem";
this.importMusicToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.importMusicToolStripMenuItem.Text = "Import Music";
this.importMusicToolStripMenuItem.Click += new System.EventHandler(this.importMusicToolStripMenuItem_Click);
//
// propertiesToolStripMenuItem
//
this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
this.propertiesToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.propertiesToolStripMenuItem.Text = "Properties";
this.propertiesToolStripMenuItem.Visible = false;
this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.propertiesToolStripMenuItem_Click);
//
// quitToolStripMenuItem
//
this.quitToolStripMenuItem.Name = "quitToolStripMenuItem";
this.quitToolStripMenuItem.Size = new System.Drawing.Size(146, 22);
this.quitToolStripMenuItem.Text = "&Quit";
this.quitToolStripMenuItem.Click += new System.EventHandler(this.quitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.selectAllToolStripMenuItem,
this.selectNoneToolStripMenuItem,
this.pluginsToolStripMenuItem,
this.preferencesToolStripMenuItem,
this.styleToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.selectAllToolStripMenuItem.Text = "Select All";
this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click);
//
// selectNoneToolStripMenuItem
//
this.selectNoneToolStripMenuItem.Name = "selectNoneToolStripMenuItem";
this.selectNoneToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.selectNoneToolStripMenuItem.Text = "Select None";
this.selectNoneToolStripMenuItem.Click += new System.EventHandler(this.selectNoneToolStripMenuItem_Click);
//
// pluginsToolStripMenuItem
//
this.pluginsToolStripMenuItem.Name = "pluginsToolStripMenuItem";
this.pluginsToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.pluginsToolStripMenuItem.Text = "Plugins";
this.pluginsToolStripMenuItem.Visible = false;
this.pluginsToolStripMenuItem.Click += new System.EventHandler(this.pluginsToolStripMenuItem_Click);
//
// preferencesToolStripMenuItem
//
this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem";
this.preferencesToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.preferencesToolStripMenuItem.Text = "Preferences";
this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click);
//
// styleToolStripMenuItem
//
this.styleToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.blueToolStripMenuItem,
this.silverToolStripMenuItem,
this.blackToolStripMenuItem});
this.styleToolStripMenuItem.Name = "styleToolStripMenuItem";
this.styleToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.styleToolStripMenuItem.Text = "Style";
//
// blueToolStripMenuItem
//
this.blueToolStripMenuItem.Name = "blueToolStripMenuItem";
this.blueToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
this.blueToolStripMenuItem.Text = "Blue";
this.blueToolStripMenuItem.Click += new System.EventHandler(this.blueToolStripMenuItem_Click);
//
// silverToolStripMenuItem
//
this.silverToolStripMenuItem.Name = "silverToolStripMenuItem";
this.silverToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
this.silverToolStripMenuItem.Text = "Silver";
this.silverToolStripMenuItem.Click += new System.EventHandler(this.blueToolStripMenuItem_Click);
//
// blackToolStripMenuItem
//
this.blackToolStripMenuItem.Name = "blackToolStripMenuItem";
this.blackToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
this.blackToolStripMenuItem.Text = "Black";
this.blackToolStripMenuItem.Click += new System.EventHandler(this.blueToolStripMenuItem_Click);
//
// playbackToolStripMenuItem
//
this.playbackToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.playToolStripMenuItem,
this.previousToolStripMenuItem,
this.nextToolStripMenuItem,
this.toolStripSeparator1,
this.seekForwardToolStripMenuItem,
this.seekBackwardToolStripMenuItem,
this.restartSongToolStripMenuItem,
this.repeatToolStripMenuItem,
this.shuffleToolStripMenuItem});
this.playbackToolStripMenuItem.Name = "playbackToolStripMenuItem";
this.playbackToolStripMenuItem.Size = new System.Drawing.Size(66, 20);
this.playbackToolStripMenuItem.Text = "&Playback";
//
// playToolStripMenuItem
//
this.playToolStripMenuItem.Name = "playToolStripMenuItem";
this.playToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.playToolStripMenuItem.Text = "Play/Pause";
this.playToolStripMenuItem.Click += new System.EventHandler(this.playToolStripMenuItem_Click);
//
// previousToolStripMenuItem
//
this.previousToolStripMenuItem.Name = "previousToolStripMenuItem";
this.previousToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.previousToolStripMenuItem.Text = "Previous";
this.previousToolStripMenuItem.Click += new System.EventHandler(this.previousToolStripMenuItem_Click);
//
// nextToolStripMenuItem
//
this.nextToolStripMenuItem.Name = "nextToolStripMenuItem";
this.nextToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.nextToolStripMenuItem.Text = "Next";
this.nextToolStripMenuItem.Click += new System.EventHandler(this.nextToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(149, 6);
//
// seekForwardToolStripMenuItem
//
this.seekForwardToolStripMenuItem.Name = "seekForwardToolStripMenuItem";
this.seekForwardToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.seekForwardToolStripMenuItem.Text = "Seek Forward";
this.seekForwardToolStripMenuItem.Visible = false;
this.seekForwardToolStripMenuItem.Click += new System.EventHandler(this.seekForwardToolStripMenuItem_Click);
//
// seekBackwardToolStripMenuItem
//
this.seekBackwardToolStripMenuItem.Name = "seekBackwardToolStripMenuItem";
this.seekBackwardToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.seekBackwardToolStripMenuItem.Text = "Seek Backward";
this.seekBackwardToolStripMenuItem.Visible = false;
this.seekBackwardToolStripMenuItem.Click += new System.EventHandler(this.seekBackwardToolStripMenuItem_Click);
//
// restartSongToolStripMenuItem
//
this.restartSongToolStripMenuItem.Name = "restartSongToolStripMenuItem";
this.restartSongToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.restartSongToolStripMenuItem.Text = "Restart Song";
this.restartSongToolStripMenuItem.Visible = false;
//
// repeatToolStripMenuItem
//
this.repeatToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.allToolStripMenuItem,
this.singleToolStripMenuItem,
this.noneToolStripMenuItem});
this.repeatToolStripMenuItem.Name = "repeatToolStripMenuItem";
this.repeatToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.repeatToolStripMenuItem.Text = "Repeat";
//
// allToolStripMenuItem
//
this.allToolStripMenuItem.Name = "allToolStripMenuItem";
this.allToolStripMenuItem.Size = new System.Drawing.Size(106, 22);
this.allToolStripMenuItem.Text = "All";
this.allToolStripMenuItem.Click += new System.EventHandler(this.allToolStripMenuItem_Click);
//
// singleToolStripMenuItem
//
this.singleToolStripMenuItem.Name = "singleToolStripMenuItem";
this.singleToolStripMenuItem.Size = new System.Drawing.Size(106, 22);
this.singleToolStripMenuItem.Text = "Single";
this.singleToolStripMenuItem.Click += new System.EventHandler(this.singleToolStripMenuItem_Click);
//
// noneToolStripMenuItem
//
this.noneToolStripMenuItem.Name = "noneToolStripMenuItem";
this.noneToolStripMenuItem.Size = new System.Drawing.Size(106, 22);
this.noneToolStripMenuItem.Text = "None";
this.noneToolStripMenuItem.Click += new System.EventHandler(this.noneToolStripMenuItem_Click);
//
// shuffleToolStripMenuItem
//
this.shuffleToolStripMenuItem.Name = "shuffleToolStripMenuItem";
this.shuffleToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.shuffleToolStripMenuItem.Text = "Shuffle";
this.shuffleToolStripMenuItem.Click += new System.EventHandler(this.shuffleToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.showCoverartToolStripMenuItem,
this.showFullScreenToolStripMenuItem,
this.showEqualiserToolStripMenuItem,
this.columnsToolStripMenuItem,
this.showLogToolStripMenuItem,
this.jumpToPlayingToolStripMenuItem,
this.searchToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.viewToolStripMenuItem.Text = "&View";
//
// showCoverartToolStripMenuItem
//
this.showCoverartToolStripMenuItem.Name = "showCoverartToolStripMenuItem";
this.showCoverartToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.showCoverartToolStripMenuItem.Text = "Show Coverart";
this.showCoverartToolStripMenuItem.Click += new System.EventHandler(this.showCoverartToolStripMenuItem_Click);
//
// showFullScreenToolStripMenuItem
//
this.showFullScreenToolStripMenuItem.Name = "showFullScreenToolStripMenuItem";
this.showFullScreenToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.showFullScreenToolStripMenuItem.Text = "Show FullScreen";
this.showFullScreenToolStripMenuItem.Visible = false;
this.showFullScreenToolStripMenuItem.Click += new System.EventHandler(this.showFullScreenToolStripMenuItem_Click);
//
// showEqualiserToolStripMenuItem
//
this.showEqualiserToolStripMenuItem.Name = "showEqualiserToolStripMenuItem";
this.showEqualiserToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.showEqualiserToolStripMenuItem.Text = "Show Equaliser";
this.showEqualiserToolStripMenuItem.Visible = false;
this.showEqualiserToolStripMenuItem.Click += new System.EventHandler(this.showEqualiserToolStripMenuItem_Click);
//
// columnsToolStripMenuItem
//
this.columnsToolStripMenuItem.Name = "columnsToolStripMenuItem";
this.columnsToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.columnsToolStripMenuItem.Text = "Columns";
this.columnsToolStripMenuItem.Click += new System.EventHandler(this.columnsToolStripMenuItem_Click);
//
// showLogToolStripMenuItem
//
this.showLogToolStripMenuItem.Name = "showLogToolStripMenuItem";
this.showLogToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.showLogToolStripMenuItem.Text = "Show Log";
this.showLogToolStripMenuItem.Visible = false;
this.showLogToolStripMenuItem.Click += new System.EventHandler(this.showLogToolStripMenuItem_Click);
//
// jumpToPlayingToolStripMenuItem
//
this.jumpToPlayingToolStripMenuItem.Name = "jumpToPlayingToolStripMenuItem";
this.jumpToPlayingToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.jumpToPlayingToolStripMenuItem.Text = "Jump To Playing";
this.jumpToPlayingToolStripMenuItem.Visible = false;
this.jumpToPlayingToolStripMenuItem.Click += new System.EventHandler(this.jumpToPlayingToolStripMenuItem_Click);
//
// searchToolStripMenuItem
//
this.searchToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.byAlbumToolStripMenuItem,
this.byArtistToolStripMenuItem,
this.byGenreToolStripMenuItem});
this.searchToolStripMenuItem.Name = "searchToolStripMenuItem";
this.searchToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.searchToolStripMenuItem.Text = "Search";
this.searchToolStripMenuItem.Visible = false;
//
// byAlbumToolStripMenuItem
//
this.byAlbumToolStripMenuItem.Name = "byAlbumToolStripMenuItem";
this.byAlbumToolStripMenuItem.Size = new System.Drawing.Size(126, 22);
this.byAlbumToolStripMenuItem.Text = "By Album";
this.byAlbumToolStripMenuItem.Click += new System.EventHandler(this.byAlbumToolStripMenuItem_Click);
//
// byArtistToolStripMenuItem
//
this.byArtistToolStripMenuItem.Name = "byArtistToolStripMenuItem";
this.byArtistToolStripMenuItem.Size = new System.Drawing.Size(126, 22);
this.byArtistToolStripMenuItem.Text = "By Artist";
this.byArtistToolStripMenuItem.Click += new System.EventHandler(this.byArtistToolStripMenuItem_Click);
//
// byGenreToolStripMenuItem
//
this.byGenreToolStripMenuItem.Name = "byGenreToolStripMenuItem";
this.byGenreToolStripMenuItem.Size = new System.Drawing.Size(126, 22);
this.byGenreToolStripMenuItem.Text = "By Genre";
this.byGenreToolStripMenuItem.Click += new System.EventHandler(this.byGenreToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.versionInfoToolStripMenuItem,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
this.helpToolStripMenuItem.Visible = false;
//
// versionInfoToolStripMenuItem
//
this.versionInfoToolStripMenuItem.Name = "versionInfoToolStripMenuItem";
this.versionInfoToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.versionInfoToolStripMenuItem.Text = "Version Info";
this.versionInfoToolStripMenuItem.Visible = false;
this.versionInfoToolStripMenuItem.Click += new System.EventHandler(this.versionInfoToolStripMenuItem_Click);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.aboutToolStripMenuItem.Text = "About";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// SourceSplitter
//
this.SourceSplitter.BackColor = System.Drawing.SystemColors.Control;
this.SourceSplitter.Cursor = System.Windows.Forms.Cursors.Default;
this.SourceSplitter.DirtyPaletteCounter = 37;
this.SourceSplitter.Dock = System.Windows.Forms.DockStyle.Fill;
this.SourceSplitter.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.SourceSplitter.Location = new System.Drawing.Point(0, 66);
this.SourceSplitter.Name = "SourceSplitter";
//
// SourceSplitter.Panel1
//
this.SourceSplitter.Panel1.AutoScroll = true;
this.SourceSplitter.Panel1.Controls.Add(this.event_panel);
this.SourceSplitter.Panel1.Controls.Add(this.cover_art_view);
this.SourceSplitter.Panel1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.SourceSplitter.Panel1.Resize += new System.EventHandler(this.SourceSplitter_Panel1_Resize);
//
// SourceSplitter.Panel2
//
this.SourceSplitter.Panel2.Controls.Add(this.LibraryContainer);
this.SourceSplitter.Panel2.Controls.Add(this.playlist_header_event_box);
this.SourceSplitter.Size = new System.Drawing.Size(655, 353);
this.SourceSplitter.SplitterDistance = 193;
this.SourceSplitter.TabIndex = 2;
//
// event_panel
//
this.event_panel.BackColor = System.Drawing.Color.Transparent;
this.event_panel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.event_panel.Location = new System.Drawing.Point(0, 105);
this.event_panel.Name = "event_panel";
this.event_panel.Size = new System.Drawing.Size(193, 55);
this.event_panel.TabIndex = 2;
this.event_panel.VisibleChanged += new System.EventHandler(this.event_panel_VisibleChanged);
//
// cover_art_view
//
this.cover_art_view.Dock = System.Windows.Forms.DockStyle.Bottom;
this.cover_art_view.Enabled = false;
this.cover_art_view.Location = new System.Drawing.Point(0, 160);
this.cover_art_view.Name = "cover_art_view";
this.cover_art_view.Padding = new System.Windows.Forms.Padding(2);
this.cover_art_view.Size = new System.Drawing.Size(193, 193);
this.cover_art_view.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.cover_art_view.TabIndex = 3;
this.cover_art_view.TabStop = false;
//
// LibraryContainer
//
this.LibraryContainer.Controls.Add(this.playlistContainer);
this.LibraryContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.LibraryContainer.Location = new System.Drawing.Point(0, 33);
this.LibraryContainer.Name = "LibraryContainer";
this.LibraryContainer.Size = new System.Drawing.Size(457, 320);
this.LibraryContainer.TabIndex = 6;
//
// playlistContainer
//
this.playlistContainer.Controls.Add(this.playlistView);
this.playlistContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.playlistContainer.Location = new System.Drawing.Point(0, 0);
this.playlistContainer.Name = "playlistContainer";
this.playlistContainer.Size = new System.Drawing.Size(457, 320);
this.playlistContainer.TabIndex = 5;
//
// playlistView
//
this.playlistView.Dock = System.Windows.Forms.DockStyle.Fill;
this.playlistView.Location = new System.Drawing.Point(0, 0);
this.playlistView.Model = null;
this.playlistView.Name = "playlistView";
this.playlistView.SelectedTrackInfo = null;
this.playlistView.Size = new System.Drawing.Size(457, 320);
this.playlistView.SourceView = null;
this.playlistView.TabIndex = 0;
this.playlistView.Viewlabel = null;
//
// playlist_header_event_box
//
this.playlist_header_event_box.BackColor = System.Drawing.Color.Transparent;
this.playlist_header_event_box.Controls.Add(this.dapDiskUsageBar);
this.playlist_header_event_box.Controls.Add(this.ViewNameLabel);
this.playlist_header_event_box.Controls.Add(this.searchEntry1);
this.playlist_header_event_box.Dock = System.Windows.Forms.DockStyle.Top;
this.playlist_header_event_box.Location = new System.Drawing.Point(0, 0);
this.playlist_header_event_box.Name = "playlist_header_event_box";
this.playlist_header_event_box.Size = new System.Drawing.Size(457, 33);
this.playlist_header_event_box.TabIndex = 3;
//
// dapDiskUsageBar
//
this.dapDiskUsageBar.Dock = System.Windows.Forms.DockStyle.Right;
this.dapDiskUsageBar.Location = new System.Drawing.Point(157, 0);
this.dapDiskUsageBar.Name = "dapDiskUsageBar";
this.dapDiskUsageBar.Size = new System.Drawing.Size(100, 33);
this.dapDiskUsageBar.TabIndex = 4;
//
// ViewNameLabel
//
this.ViewNameLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ViewNameLabel.BackColor = System.Drawing.Color.Transparent;
this.ViewNameLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ViewNameLabel.ForeColor = System.Drawing.Color.WhiteSmoke;
this.ViewNameLabel.Location = new System.Drawing.Point(3, 0);
this.ViewNameLabel.Name = "ViewNameLabel";
this.ViewNameLabel.Size = new System.Drawing.Size(163, 34);
this.ViewNameLabel.TabIndex = 2;
this.ViewNameLabel.Text = "Loading ....";
this.ViewNameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// searchEntry1
//
this.searchEntry1.Dock = System.Windows.Forms.DockStyle.Right;
this.searchEntry1.Field = "";
this.searchEntry1.Location = new System.Drawing.Point(257, 0);
this.searchEntry1.Name = "searchEntry1";
this.searchEntry1.Query = "";
this.searchEntry1.Ready = false;
this.searchEntry1.SearchFields = ((System.Collections.ArrayList)(resources.GetObject("searchEntry1.SearchFields")));
this.searchEntry1.Size = new System.Drawing.Size(200, 33);
this.searchEntry1.TabIndex = 3;
//
// backgroundWorker1
//
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
//
// header_container
//
this.header_container.BackColor = System.Drawing.Color.Transparent;
this.header_container.Controls.Add(this.trackInfoHeader);
this.header_container.Controls.Add(this.additional_action_buttons_box);
this.header_container.Controls.Add(this.seekpanel);
this.header_container.Controls.Add(this.panel2);
this.header_container.Dock = System.Windows.Forms.DockStyle.Top;
this.header_container.Location = new System.Drawing.Point(0, 24);
this.header_container.Name = "header_container";
this.header_container.Size = new System.Drawing.Size(655, 42);
this.header_container.TabIndex = 1;
//
// trackInfoHeader
//
this.trackInfoHeader.BackColor = System.Drawing.Color.Transparent;
this.trackInfoHeader.Dock = System.Windows.Forms.DockStyle.Fill;
this.trackInfoHeader.FileName = null;
this.trackInfoHeader.ForeColor = System.Drawing.Color.WhiteSmoke;
this.trackInfoHeader.Label = null;
this.trackInfoHeader.Location = new System.Drawing.Point(242, 0);
this.trackInfoHeader.Name = "trackInfoHeader";
this.trackInfoHeader.Size = new System.Drawing.Size(276, 42);
this.trackInfoHeader.TabIndex = 6;
//
// additional_action_buttons_box
//
this.additional_action_buttons_box.BackColor = System.Drawing.Color.Transparent;
this.additional_action_buttons_box.Controls.Add(this.sync_dap_button);
this.additional_action_buttons_box.Controls.Add(this.volumeButton);
this.additional_action_buttons_box.Dock = System.Windows.Forms.DockStyle.Right;
this.additional_action_buttons_box.Location = new System.Drawing.Point(518, 0);
this.additional_action_buttons_box.Name = "additional_action_buttons_box";
this.additional_action_buttons_box.Size = new System.Drawing.Size(137, 42);
this.additional_action_buttons_box.TabIndex = 11;
//
// sync_dap_button
//
this.sync_dap_button.DirtyPaletteCounter = 49;
this.sync_dap_button.Dock = System.Windows.Forms.DockStyle.Fill;
this.sync_dap_button.ForeColor = System.Drawing.Color.Black;
this.sync_dap_button.Location = new System.Drawing.Point(0, 0);
this.sync_dap_button.Name = "sync_dap_button";
this.sync_dap_button.Padding = new System.Windows.Forms.Padding(5);
this.sync_dap_button.Size = new System.Drawing.Size(97, 42);
this.sync_dap_button.TabIndex = 9;
this.sync_dap_button.Text = "Syncronize";
this.sync_dap_button.Values.ExtraText = "";
this.sync_dap_button.Values.Image = null;
this.sync_dap_button.Values.ImageStates.ImageCheckedNormal = null;
this.sync_dap_button.Values.ImageStates.ImageCheckedPressed = null;
this.sync_dap_button.Values.ImageStates.ImageCheckedTracking = null;
this.sync_dap_button.Values.Text = "Syncronize";
this.sync_dap_button.Visible = false;
this.sync_dap_button.Click += new System.EventHandler(this.sync_dap_button_Click);
//
// volumeButton
//
this.volumeButton.DirtyPaletteCounter = 48;
this.volumeButton.Dock = System.Windows.Forms.DockStyle.Right;
this.volumeButton.Location = new System.Drawing.Point(97, 0);
this.volumeButton.Name = "volumeButton";
this.volumeButton.Padding = new System.Windows.Forms.Padding(5);
this.volumeButton.Size = new System.Drawing.Size(40, 42);
this.volumeButton.TabIndex = 8;
this.volumeButton.Values.ExtraText = "";
this.volumeButton.Values.Image = global::Banshee.Properties.Resources.audio_volume_low;
this.volumeButton.Values.ImageStates.ImageCheckedNormal = null;
this.volumeButton.Values.ImageStates.ImageCheckedPressed = null;
this.volumeButton.Values.ImageStates.ImageCheckedTracking = null;
this.volumeButton.Values.Text = "";
//
// seekpanel
//
this.seekpanel.BackColor = System.Drawing.Color.Transparent;
this.seekpanel.Dock = System.Windows.Forms.DockStyle.Left;
this.seekpanel.Location = new System.Drawing.Point(137, 0);
this.seekpanel.Name = "seekpanel";
this.seekpanel.Size = new System.Drawing.Size(105, 42);
this.seekpanel.TabIndex = 9;
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.Transparent;
this.panel2.Controls.Add(this.next_button);
this.panel2.Controls.Add(this.previous_button);
this.panel2.Controls.Add(this.playpause_button);
this.panel2.Dock = System.Windows.Forms.DockStyle.Left;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(137, 42);
this.panel2.TabIndex = 10;
//
// next_button
//
this.next_button.DirtyPaletteCounter = 48;
this.next_button.Location = new System.Drawing.Point(93, 3);
this.next_button.Name = "next_button";
this.next_button.Size = new System.Drawing.Size(42, 38);
this.next_button.TabIndex = 2;
this.next_button.Values.ExtraText = "";
this.next_button.Values.Image = global::Banshee.Properties.Resources.media_skip_forward;
this.next_button.Values.ImageStates.ImageCheckedNormal = null;
this.next_button.Values.ImageStates.ImageCheckedPressed = null;
this.next_button.Values.ImageStates.ImageCheckedTracking = null;
this.next_button.Values.Text = "";
this.next_button.Click += new System.EventHandler(this.next_button_Click);
//
// previous_button
//
this.previous_button.DirtyPaletteCounter = 48;
this.previous_button.Location = new System.Drawing.Point(3, 3);
this.previous_button.Name = "previous_button";
this.previous_button.Size = new System.Drawing.Size(42, 38);
this.previous_button.TabIndex = 0;
this.previous_button.Values.ExtraText = "";
this.previous_button.Values.Image = ((System.Drawing.Image)(resources.GetObject("previous_button.Values.Image")));
this.previous_button.Values.ImageStates.ImageCheckedNormal = null;
this.previous_button.Values.ImageStates.ImageCheckedPressed = null;
this.previous_button.Values.ImageStates.ImageCheckedTracking = null;
this.previous_button.Values.Text = "";
this.previous_button.Click += new System.EventHandler(this.previous_button_Click);
//
// playpause_button
//
this.playpause_button.DirtyPaletteCounter = 50;
this.playpause_button.Location = new System.Drawing.Point(48, 3);
this.playpause_button.Name = "playpause_button";
this.playpause_button.Size = new System.Drawing.Size(42, 38);
this.playpause_button.TabIndex = 1;
this.playpause_button.Values.ExtraText = "";
this.playpause_button.Values.Image = global::Banshee.Properties.Resources.media_playback_pause;
this.playpause_button.Values.ImageStates.ImageCheckedNormal = null;
this.playpause_button.Values.ImageStates.ImageCheckedPressed = null;
this.playpause_button.Values.ImageStates.ImageCheckedTracking = null;
this.playpause_button.Values.ImageStates.ImageNormal = global::Banshee.Properties.Resources.media_playback_pause;
this.playpause_button.Values.Text = "";
this.playpause_button.Click += new System.EventHandler(this.playpause_button_Click);
//
// status_panel
//
this.status_panel.Controls.Add(this.LabelStatusBar);
this.status_panel.Controls.Add(this.song_properties_button);
this.status_panel.Controls.Add(this.repeat_toggle_button);
this.status_panel.Controls.Add(this.shuffle_toggle_button);
this.status_panel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.status_panel.Location = new System.Drawing.Point(0, 419);
this.status_panel.Name = "status_panel";
this.status_panel.Padding = new System.Windows.Forms.Padding(3);
this.status_panel.Size = new System.Drawing.Size(655, 31);
this.status_panel.TabIndex = 3;
//
// LabelStatusBar
//
this.LabelStatusBar.DirtyPaletteCounter = 38;
this.LabelStatusBar.Dock = System.Windows.Forms.DockStyle.Fill;
this.LabelStatusBar.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel;
this.LabelStatusBar.Location = new System.Drawing.Point(64, 3);
this.LabelStatusBar.Name = "LabelStatusBar";
this.LabelStatusBar.Size = new System.Drawing.Size(558, 25);
this.LabelStatusBar.TabIndex = 3;
this.LabelStatusBar.Text = "Label";
this.LabelStatusBar.Values.ExtraText = "";
this.LabelStatusBar.Values.Image = null;
this.LabelStatusBar.Values.Text = "Label";
//
// song_properties_button
//
this.song_properties_button.DirtyPaletteCounter = 48;
this.song_properties_button.Dock = System.Windows.Forms.DockStyle.Right;
this.song_properties_button.Location = new System.Drawing.Point(622, 3);
this.song_properties_button.Name = "song_properties_button";
this.song_properties_button.Size = new System.Drawing.Size(30, 25);
this.song_properties_button.TabIndex = 2;
this.song_properties_button.Values.ExtraText = "";
this.song_properties_button.Values.Image = global::Banshee.Properties.Resources.document_properties;
this.song_properties_button.Values.ImageStates.ImageCheckedNormal = null;
this.song_properties_button.Values.ImageStates.ImageCheckedPressed = null;
this.song_properties_button.Values.ImageStates.ImageCheckedTracking = null;
this.song_properties_button.Values.Text = "";
this.song_properties_button.Click += new System.EventHandler(this.button3_Click);
//
// repeat_toggle_button
//
this.repeat_toggle_button.DirtyPaletteCounter = 48;
this.repeat_toggle_button.Dock = System.Windows.Forms.DockStyle.Left;
this.repeat_toggle_button.Location = new System.Drawing.Point(34, 3);
this.repeat_toggle_button.Name = "repeat_toggle_button";
this.repeat_toggle_button.Size = new System.Drawing.Size(30, 25);
this.repeat_toggle_button.TabIndex = 1;
this.repeat_toggle_button.Values.ExtraText = "";
this.repeat_toggle_button.Values.Image = global::Banshee.Properties.Resources.media_repeat_none;
this.repeat_toggle_button.Values.ImageStates.ImageCheckedNormal = null;
this.repeat_toggle_button.Values.ImageStates.ImageCheckedPressed = null;
this.repeat_toggle_button.Values.ImageStates.ImageCheckedTracking = null;
this.repeat_toggle_button.Values.Text = "";
this.repeat_toggle_button.Click += new System.EventHandler(this.repeat_toggle_button_Click);
//
// shuffle_toggle_button
//
this.shuffle_toggle_button.DirtyPaletteCounter = 49;
this.shuffle_toggle_button.Dock = System.Windows.Forms.DockStyle.Left;
this.shuffle_toggle_button.Location = new System.Drawing.Point(3, 3);
this.shuffle_toggle_button.Name = "shuffle_toggle_button";
this.shuffle_toggle_button.Size = new System.Drawing.Size(31, 25);
this.shuffle_toggle_button.TabIndex = 0;
this.shuffle_toggle_button.Values.ExtraText = "";
this.shuffle_toggle_button.Values.Image = global::Banshee.Properties.Resources.media_playlist_continuous;
this.shuffle_toggle_button.Values.ImageStates.ImageCheckedNormal = null;
this.shuffle_toggle_button.Values.ImageStates.ImageCheckedPressed = null;
this.shuffle_toggle_button.Values.ImageStates.ImageCheckedTracking = null;
this.shuffle_toggle_button.Values.Text = "";
this.shuffle_toggle_button.Click += new System.EventHandler(this.shuffle_toggle_button_Click);
//
// Manager
//
this.Manager.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Custom;
//
// posTimer
//
this.posTimer.Tick += new System.EventHandler(this.posTimer_Tick);
//
// WindowPlayer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(655, 450);
this.Controls.Add(this.SourceSplitter);
this.Controls.Add(this.header_container);
this.Controls.Add(this.mainMenu);
this.Controls.Add(this.status_panel);
this.DoubleBuffered = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.mainMenu;
this.Name = "WindowPlayer";
this.Text = "banshee";
this.Load += new System.EventHandler(this.WindowPlayer_Load);
this.Shown += new System.EventHandler(this.WindowPlayer_Shown);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.WindowPlayer_FormClosing);
this.mainMenu.ResumeLayout(false);
this.mainMenu.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.SourceSplitter.Panel1)).EndInit();
this.SourceSplitter.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.SourceSplitter.Panel2)).EndInit();
this.SourceSplitter.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.SourceSplitter)).EndInit();
this.SourceSplitter.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.event_panel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cover_art_view)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LibraryContainer)).EndInit();
this.LibraryContainer.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.playlistContainer)).EndInit();
this.playlistContainer.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.playlist_header_event_box)).EndInit();
this.playlist_header_event_box.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.header_container)).EndInit();
this.header_container.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.additional_action_buttons_box)).EndInit();
this.additional_action_buttons_box.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.sync_dap_button)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.volumeButton)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.seekpanel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel2)).EndInit();
this.panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.next_button)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.previous_button)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.playpause_button)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.status_panel)).EndInit();
this.status_panel.ResumeLayout(false);
this.status_panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.LabelStatusBar)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.song_properties_button)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.repeat_toggle_button)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.shuffle_toggle_button)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip mainMenu;
private ComponentFactory.Krypton.Toolkit.KryptonPanel header_container;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer SourceSplitter;
private ComponentFactory.Krypton.Toolkit.KryptonButton playpause_button;
private ComponentFactory.Krypton.Toolkit.KryptonButton previous_button;
private ComponentFactory.Krypton.Toolkit.KryptonButton volumeButton;
private System.Windows.Forms.ToolStripMenuItem musicToolStripMenuItem;
private ComponentFactory.Krypton.Toolkit.KryptonPanel event_panel;
private ComponentFactory.Krypton.Toolkit.KryptonPanel seekpanel;
private ComponentFactory.Krypton.Toolkit.KryptonPanel status_panel;
private ComponentFactory.Krypton.Toolkit.KryptonLabel LabelStatusBar;
private ComponentFactory.Krypton.Toolkit.KryptonButton song_properties_button;
private ComponentFactory.Krypton.Toolkit.KryptonButton repeat_toggle_button;
private ComponentFactory.Krypton.Toolkit.KryptonButton shuffle_toggle_button;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem playbackToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importFolderToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importFilesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importMusicToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem quitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectNoneToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pluginsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem playToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem previousToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem nextToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem seekForwardToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem seekBackwardToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem restartSongToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem repeatToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem allToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem noneToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem singleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem shuffleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showCoverartToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showFullScreenToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showEqualiserToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem columnsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem showLogToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem jumpToPlayingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem byAlbumToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem byArtistToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem byGenreToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem versionInfoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private ComponentFactory.Krypton.Toolkit.KryptonPanel playlist_header_event_box;
private Banshee.Base.Winforms.Controls.SearchEntry searchEntry1;
public System.Windows.Forms.Label ViewNameLabel;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
private Banshee.Widgets.TrackInfoHeader trackInfoHeader;
private ComponentFactory.Krypton.Toolkit.KryptonPanel additional_action_buttons_box;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel2;
private ComponentFactory.Krypton.Toolkit.KryptonPanel playlistContainer;
private ComponentFactory.Krypton.Toolkit.KryptonPanel LibraryContainer;
private System.Windows.Forms.ProgressBar dapDiskUsageBar;
private ComponentFactory.Krypton.Toolkit.KryptonButton sync_dap_button;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private ComponentFactory.Krypton.Toolkit.KryptonManager Manager;
private Banshee.Base.Winforms.Widgets.CoverArtView cover_art_view;
private ComponentFactory.Krypton.Toolkit.KryptonButton next_button;
private System.Windows.Forms.ToolStripMenuItem styleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem blueToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem silverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem blackToolStripMenuItem;
private PlayListView playlistView;
private System.Windows.Forms.Timer posTimer;
}
}
| |
/*
* Author: Marcus Lorentzon, 2001
* d98malor@dtek.chalmers.se
*
* Freeware: Do not remove this header
*
* File: SerialStream.cs
*
* Description: Implements a Stream for asynchronous
* transfers and COMM.
*
* Version: 2.0 beta
*
*/
namespace LoMaN.IO {
using System;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
public class SerialStream : Stream {
public class SerialAsyncResult : IAsyncResult {
public SerialAsyncResult(object asyncObject) {
m_AsyncObject = asyncObject;
m_WaitHandle = new ManualResetEvent(false);
}
internal void Init(object stateObject, AsyncCallback callback, bool bIsRead) {
m_StateObject = stateObject;
m_Callback = callback;
m_bIsRead = bIsRead;
m_bCompleted = false;
m_WaitHandle.Reset();
}
internal void Reset() {
m_StateObject = null;
m_Callback = null;
m_bCompleted = true;
m_WaitHandle.Reset();
}
internal bool m_bIsRead;
internal bool m_bCompleted = true;
public bool IsCompleted { get { return m_bCompleted; } }
public bool CompletedSynchronously { get { return false; } }
private object m_AsyncObject;
public object AsyncObject { get { return m_AsyncObject; } }
private object m_StateObject;
public object AsyncState { get { return m_StateObject; } }
private ManualResetEvent m_WaitHandle;
public WaitHandle AsyncWaitHandle { get { return m_WaitHandle; } }
private AsyncCallback m_Callback;
public AsyncCallback Callback { get { return m_Callback; } }
}
private unsafe void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) {
SerialAsyncResult sar = (SerialAsyncResult)Overlapped.Unpack(pOverlapped).AsyncResult;
if (sar.m_bIsRead)
m_iReadCount = (int)numBytes;
else
m_iWriteCount = (int)numBytes;
((ManualResetEvent)sar.AsyncWaitHandle).Set();
if (errorCode == ERROR_OPERATION_ABORTED)
sar.m_bCompleted = false;
else
sar.m_bCompleted = true;
if (sar.Callback != null)
sar.Callback.Invoke(sar);
}
private IOCompletionCallback m_IOCompletionCallback;
private int m_hFile = 0;
private string m_sPort;
public string Port {
get {
return m_sPort;
}
set {
if (m_sPort != value) {
Close();
Open(value);
}
}
}
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const uint ERROR_OPERATION_ABORTED = 995;
private const uint ERROR_IO_PENDING = 997;
public void Open(string port) {
m_hFile = CreateFile(port, (uint)((m_bRead?GENERIC_READ:0)|(m_bWrite?GENERIC_WRITE:0)), 0, 0, 3, 0x40000000, 0);
if (m_hFile <= 0) {
m_hFile = 0;
throw new FileNotFoundException("Unable to open " + port);
}
m_sPort = port;
ThreadPool.BindHandle(new IntPtr(m_hFile));
}
public SerialStream(string port, FileAccess access) {
m_bRead = ((int)access & (int)FileAccess.Read) != 0;
m_bWrite = ((int)access & (int)FileAccess.Write) != 0;
Open(port);
unsafe {
m_IOCompletionCallback = new IOCompletionCallback(AsyncFSCallback);
}
}
private bool m_bRead;
public override bool CanRead { get { return m_bRead; } }
private bool m_bWrite;
public override bool CanWrite { get { return m_bWrite; } }
public override bool CanSeek { get { return false; } }
public bool Closed { get { return m_hFile <= 0; } }
public override long Length { get { return 0; } }
public override void SetLength(long nLength) { }
public override void Close() {
CloseHandle(m_hFile);
m_hFile = 0;
m_sPort = null;
}
private int m_iReadCount;
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
SerialAsyncResult ar = new SerialAsyncResult(this);
ar.Init(state, callback, true);
Overlapped ov = new Overlapped(0, 0, ar.AsyncWaitHandle.Handle.ToInt32(), ar);
unsafe { fixed (byte* data = &buffer[0]) {
int read = 0;
NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
ReadFile(m_hFile, data, count, &read, nov);
} }
if (GetLastError() == ERROR_IO_PENDING)
return ar;
else
throw new Exception("Unable to initialize read. Errorcode: " + GetLastError().ToString());
}
private int m_iWriteCount;
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
SerialAsyncResult ar = new SerialAsyncResult(this);
ar.Init(state, callback, false);
Overlapped ov = new Overlapped(0, 0, ar.AsyncWaitHandle.Handle.ToInt32(), ar);
unsafe { fixed (byte* data = &buffer[0]) {
int write = 0;
NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
WriteFile(m_hFile, data, count, &write, nov);
} }
if (GetLastError() == ERROR_IO_PENDING)
return ar;
else
throw new Exception("Unable to initialize write. Errorcode: " + GetLastError().ToString());
}
public override int EndRead(IAsyncResult asyncResult) {
SerialAsyncResult sar = (SerialAsyncResult)asyncResult;
if (!sar.m_bIsRead)
throw new Exception("Invalid parameter: IAsyncResult is not from a read");
sar.AsyncWaitHandle.WaitOne();
if (!sar.m_bCompleted) {
((ManualResetEvent)sar.AsyncWaitHandle).Reset();
sar.AsyncWaitHandle.WaitOne();
}
sar.Reset();
return m_iReadCount;
}
public override void EndWrite(IAsyncResult asyncResult) {
SerialAsyncResult sar = (SerialAsyncResult)asyncResult;
if (sar.m_bIsRead)
throw new Exception("Invalid parameter: IAsyncResult is from a read");
sar.AsyncWaitHandle.WaitOne();
if (!sar.m_bCompleted) {
((ManualResetEvent)sar.AsyncWaitHandle).Reset();
sar.AsyncWaitHandle.WaitOne();
}
sar.Reset();
}
public override int Read(byte[] buffer, int offset, int count) {
return EndRead(BeginRead(buffer, offset, count, null, null));
}
public override void Write(byte[] buffer, int offset, int count) {
EndWrite(BeginWrite(buffer, offset, count, null, null));
}
public override void Flush() { FlushFileBuffers(m_hFile); }
private const uint PURGE_TXABORT = 0x0001; // Kill the pending/current writes to the comm port.
private const uint PURGE_RXABORT = 0x0002; // Kill the pending/current reads to the comm port.
private const uint PURGE_TXCLEAR = 0x0004; // Kill the transmit queue if there.
private const uint PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there.
public bool PurgeRead() { return(PurgeComm(m_hFile, PURGE_RXCLEAR)); }
public bool PurgeWrite() { return(PurgeComm(m_hFile, PURGE_TXCLEAR)); }
public bool CancelRead() { return(PurgeComm(m_hFile, PURGE_RXABORT)); }
public bool CancelWrite() { return(PurgeComm(m_hFile, PURGE_TXABORT)); }
public override long Seek(long offset, SeekOrigin origin) { return 0; }
public override long Position { get { return 0; } set { } }
public void SetTimeouts(int ReadIntervalTimeout, int ReadTotalTimeoutMultiplier, int ReadTotalTimeoutConstant,
int WriteTotalTimeoutMultiplier, int WriteTotalTimeoutConstant) {
SerialTimeouts Timeouts = new SerialTimeouts(ReadIntervalTimeout, ReadTotalTimeoutMultiplier, ReadTotalTimeoutConstant,
WriteTotalTimeoutMultiplier, WriteTotalTimeoutConstant);
unsafe { SetCommTimeouts(m_hFile, &Timeouts); }
}
public enum Parity {None, Odd, Even, Mark, Space};
public enum StopBits {One, OneAndHalf, Two};
public enum FlowControl {None, XOnXOff, Hardware};
[StructLayout(LayoutKind.Sequential)]
public struct DCB {
public int DCBlength;
public uint BaudRate;
public uint Flags;
public uint fBinary { get { return Flags&0x0001; }
set { Flags = Flags & ~1U | value; } }
public uint fParity { get { return (Flags>>1)&1; }
set { Flags = Flags & ~(1U << 1) | (value << 1); } }
public uint fOutxCtsFlow { get { return (Flags>>2)&1; }
set { Flags = Flags & ~(1U << 2) | (value << 2); } }
public uint fOutxDsrFlow { get { return (Flags>>3)&1; }
set { Flags = Flags & ~(1U << 3) | (value << 3); } }
public uint fDtrControl { get { return (Flags>>4)&3; }
set { Flags = Flags & ~(3U << 4) | (value << 4); } }
public uint fDsrSensitivity { get { return (Flags>>6)&1; }
set { Flags = Flags & ~(1U << 6) | (value << 6); } }
public uint fTXContinueOnXoff { get { return (Flags>>7)&1; }
set { Flags = Flags & ~(1U << 7) | (value << 7); } }
public uint fOutX { get { return (Flags>>8)&1; }
set { Flags = Flags & ~(1U << 8) | (value << 8); } }
public uint fInX { get { return (Flags>>9)&1; }
set { Flags = Flags & ~(1U << 9) | (value << 9); } }
public uint fErrorChar { get { return (Flags>>10)&1; }
set { Flags = Flags & ~(1U << 10) | (value << 10); } }
public uint fNull { get { return (Flags>>11)&1; }
set { Flags = Flags & ~(1U << 11) | (value << 11); } }
public uint fRtsControl { get { return (Flags>>12)&3; }
set { Flags = Flags & ~(3U << 12) | (value << 12); } }
public uint fAbortOnError { get { return (Flags>>13)&1; }
set { Flags = Flags & ~(1U << 13) | (value << 13); } }
public ushort wReserved;
public ushort XonLim;
public ushort XoffLim;
public byte ByteSize;
public byte Parity;
public byte StopBits;
public sbyte XonChar;
public sbyte XoffChar;
public sbyte ErrorChar;
public sbyte EofChar;
public sbyte EvtChar;
public ushort wReserved1;
public override string ToString() {
return "DCBlength: " + DCBlength + "\r\n" +
"BaudRate: " + BaudRate + "\r\n" +
"fBinary: " + fBinary + "\r\n" +
"fParity: " + fParity + "\r\n" +
"fOutxCtsFlow: " + fOutxCtsFlow + "\r\n" +
"fOutxDsrFlow: " + fOutxDsrFlow + "\r\n" +
"fDtrControl: " + fDtrControl + "\r\n" +
"fDsrSensitivity: " + fDsrSensitivity + "\r\n" +
"fTXContinueOnXoff: " + fTXContinueOnXoff + "\r\n" +
"fOutX: " + fOutX + "\r\n" +
"fInX: " + fInX + "\r\n" +
"fErrorChar: " + fErrorChar + "\r\n" +
"fNull: " + fNull + "\r\n" +
"fRtsControl: " + fRtsControl + "\r\n" +
"fAbortOnError: " + fAbortOnError + "\r\n" +
"XonLim: " + XonLim + "\r\n" +
"XoffLim: " + XoffLim + "\r\n" +
"ByteSize: " + ByteSize + "\r\n" +
"Parity: " + Parity + "\r\n" +
"StopBits: " + StopBits + "\r\n" +
"XonChar: " + XonChar + "\r\n" +
"XoffChar: " + XoffChar + "\r\n" +
"EofChar: " + EofChar + "\r\n" +
"EvtChar: " + EvtChar + "\r\n";
}
}
public bool SetPortSettings(uint baudrate, byte databits, StopBits stopbits, Parity parity, FlowControl flowcontrol) {
unsafe {
DCB dcb = new DCB();
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = baudrate;
dcb.ByteSize = databits;
dcb.StopBits = (byte)stopbits;
dcb.Parity = (byte)parity;
dcb.fParity = (parity > 0)? 1U : 0U;
dcb.fBinary = dcb.fDtrControl = dcb.fTXContinueOnXoff = 1;
dcb.fOutxCtsFlow = dcb.fAbortOnError = (flowcontrol == FlowControl.Hardware)? 1U : 0U;
dcb.fOutX = dcb.fInX = (flowcontrol == FlowControl.XOnXOff)? 1U : 0U;
dcb.fRtsControl = (flowcontrol == FlowControl.Hardware)? 2U : 1U;
dcb.XonLim = 2048;
dcb.XoffLim = 512;
dcb.XonChar = 0x11; // Ctrl-Q
dcb.XoffChar = 0x13; // Ctrl-S
return SetCommState(m_hFile, &dcb);
}
}
public bool GetPortSettings(out DCB dcb) {
unsafe {
DCB dcb2 = new DCB();
dcb2.DCBlength = sizeof(DCB);
bool ret = GetCommState(m_hFile, &dcb2);
dcb = dcb2;
return ret;
}
}
[DllImport("kernel32.dll", EntryPoint="CreateFileW", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true)]
static extern int CreateFile(string filename, uint access, uint sharemode, uint security_attributes, uint creation, uint flags, uint template);
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool CloseHandle(int handle);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool ReadFile(int hFile, byte* lpBuffer, int nNumberOfBytesToRead, int* lpNumberOfBytesRead, NativeOverlapped* lpOverlapped);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool WriteFile(int hFile, byte* lpBuffer, int nNumberOfBytesToWrite, int* lpNumberOfBytesWritten, NativeOverlapped* lpOverlapped);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool SetCommTimeouts(int hFile, SerialTimeouts* lpCommTimeouts);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool SetCommState(int hFile, DCB* lpDCB);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool GetCommState(int hFile, DCB* lpDCB);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool BuildCommDCB(string def, DCB* lpDCB);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern int GetLastError();
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool FlushFileBuffers(int hFile);
[DllImport("kernel32.dll", SetLastError=true)]
static unsafe extern bool PurgeComm(int hFile, uint dwFlags);
}
[StructLayout(LayoutKind.Sequential)]
public struct SerialTimeouts {
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
public SerialTimeouts(int r1, int r2, int r3, int w1, int w2) {
ReadIntervalTimeout = r1;
ReadTotalTimeoutMultiplier = r2;
ReadTotalTimeoutConstant = r3;
WriteTotalTimeoutMultiplier = w1;
WriteTotalTimeoutConstant = w2;
}
public override string ToString() {
return "ReadIntervalTimeout: " + ReadIntervalTimeout + "\r\n" +
"ReadTotalTimeoutMultiplier: " + ReadTotalTimeoutMultiplier + "\r\n" +
"ReadTotalTimeoutConstant: " + ReadTotalTimeoutConstant + "\r\n" +
"WriteTotalTimeoutMultiplier: " + WriteTotalTimeoutMultiplier + "\r\n" +
"WriteTotalTimeoutConstant: " + WriteTotalTimeoutConstant + "\r\n";
}
}
public class SerialSettings {
private bool m_bDirty = false;
public bool Dirty { get { return m_bDirty; } }
// Timeouts
private SerialTimeouts Timeouts = new SerialTimeouts(1, 0, 0, 0, 0);
public int ReadIntervalTimeout {
get { return Timeouts.ReadIntervalTimeout; }
set { if (Timeouts.ReadIntervalTimeout != value) {
Timeouts.ReadIntervalTimeout = value;
m_bDirty = true;
}
}
}
public int ReadTotalTimeoutMultiplier {
get { return Timeouts.ReadTotalTimeoutMultiplier; }
set { if (Timeouts.ReadTotalTimeoutMultiplier != value) {
Timeouts.ReadTotalTimeoutMultiplier = value;
m_bDirty = true;
}
}
}
public int ReadTotalTimeoutConstant {
get { return Timeouts.ReadTotalTimeoutConstant; }
set { if (Timeouts.ReadTotalTimeoutConstant != value) {
Timeouts.ReadTotalTimeoutConstant = value;
m_bDirty = true;
}
}
}
public int WriteTotalTimeoutMultiplier {
get { return Timeouts.WriteTotalTimeoutMultiplier; }
set { if (Timeouts.WriteTotalTimeoutMultiplier != value) {
Timeouts.WriteTotalTimeoutMultiplier = value;
m_bDirty = true;
}
}
}
public int WriteTotalTimeoutConstant {
get { return Timeouts.WriteTotalTimeoutConstant; }
set { if (Timeouts.WriteTotalTimeoutConstant != value) {
Timeouts.WriteTotalTimeoutConstant = value;
m_bDirty = true;
}
}
}
// Valid stuff
private static readonly object[] s_iValidBitRates = new object[] {75u, 110u, 134u, 150u, 300u, 600u, 1200u, 1800u, 2400u, 4800u,
7200u, 9600u, 14400u, 19200u, 38400u, 57600u, 115200u, 128000u};
public static object[] ValidBitRates {
get { return s_iValidBitRates; }
}
private static readonly object[] s_iValidDataBits = new object[] {(byte)5, (byte)6, (byte)7, (byte)8};
public static object[] ValidDataBits {
get { return s_iValidDataBits; }
}
// Port settings
private uint m_iBitRate = 57600;
public uint BitRate {
get { return m_iBitRate; }
set { if (m_iBitRate != value) {
m_iBitRate = value;
m_bDirty = true;
}
}
}
private byte m_iDataBits = 8;
public byte DataBits {
get { return m_iDataBits; }
set { if (m_iDataBits != value) {
m_iDataBits = value;
m_bDirty = true;
}
}
}
private SerialStream.Parity m_Parity = SerialStream.Parity.None;
public SerialStream.Parity Parity {
get { return m_Parity; }
set { if (m_Parity != value) {
m_Parity = value;
m_bDirty = true;
}
}
}
private SerialStream.StopBits m_StopBits = SerialStream.StopBits.One;
public SerialStream.StopBits StopBits {
get { return m_StopBits; }
set { if (m_StopBits != value) {
m_StopBits = value;
m_bDirty = true;
}
}
}
private SerialStream.FlowControl m_FlowControl = SerialStream.FlowControl.None;
public SerialStream.FlowControl FlowControl {
get { return m_FlowControl; }
set { if (m_FlowControl != value) {
m_FlowControl = value;
m_bDirty = true;
}
}
}
}
}
| |
// 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 Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NCache.Common.Net;
namespace Alachisoft.NCache.Caching.Topologies.Clustered
{
public class DistributeHashMap
{
public static ArrayList DistributeOrphanBuckets(ArrayList hashMap, Address leavingNode, ArrayList members)
{
HashMapBucket tempBuck;
ArrayList orphanBuckets = new ArrayList();
hashMap = ReAllocBucketsInTransfer(hashMap, leavingNode);
int[] bucketsInEachNode = NodeBucketsCount(hashMap, members); //node vs bucket count.
bool bAssigned = false;
int memberCount = members.Count;
if (memberCount == 0)
return null;
int bucketsPerNode = hashMap.Count / members.Count;
for (int i = 0, j = 0; i < hashMap.Count; i++)
{
j = (j == memberCount) ? 0 : j;
tempBuck = (HashMapBucket)hashMap[i];
if (tempBuck.PermanentAddress.CompareTo(leavingNode) == 0)
{
bAssigned = false;
for (int k = 0; k < memberCount; k++)
{
if (bucketsInEachNode[j] < bucketsPerNode)
{
Address mbr = members[j] as Address;
bucketsInEachNode[j] = (bucketsInEachNode[j])++; //increment bucket count as next j is incremented.
tempBuck.PermanentAddress = mbr;
tempBuck.TempAddress = mbr;
tempBuck.Status = BucketStatus.Functional;
j++;
bAssigned = true;
break;
}
else
{
j++;
j = (j == memberCount) ? 0 : j;
}
}
//exceptional case when last node gets few more buckets. Assign those leftover buckets to ANY node.
if (bAssigned == false)
{
tempBuck.PermanentAddress = (Address)members[j++];
}
}
}
return hashMap;
}
//While a node leaves, all those buckets that were in transfer of buckets to the leaving node, should sieze transfer and would
// clear up tempAdd to be the same as the perm. addr.
private static ArrayList ReAllocBucketsInTransfer(ArrayList hashMap, Address leavingNode)
{
for (int i = 0; i < hashMap.Count; i++)
{
if (((HashMapBucket)hashMap[i]).TempAddress.CompareTo(leavingNode) == 0)
((HashMapBucket)hashMap[i]).TempAddress = ((HashMapBucket)hashMap[i]).PermanentAddress;
}
return hashMap;
}
//Returns int array of bucket-count against each member. This is to deal with cases when node leaves while transfer.
//resulting very un-even bucket distribution over the cluster.
private static int[] NodeBucketsCount(ArrayList hashMap, ArrayList members)
{
int[] _bucketsCount = new int[members.Count];
//Bad code... need to re-visit later on
for (int i = 0; i < members.Count; i++)
{
Address addr = (Address)members[i];
int buckCount = 0;
for (int j = 0; j < hashMap.Count; j++)
{
if (((HashMapBucket)hashMap[j]).PermanentAddress.CompareTo(addr) == 0)
buckCount++;
}
_bucketsCount[i] = buckCount;
}
return _bucketsCount;
}
public static ArrayList BalanceBuckets(DistributionInfoData distInfo, ArrayList hashMap, Hashtable bucketStats, ArrayList members,long cacheSizePerNode ,ILogger NCacheLog)
{
DistributionData distData = new DistributionData(hashMap, bucketStats, members, NCacheLog, cacheSizePerNode);
Boolean bShouldBalanceWeight = false;
if (distInfo.DistribMode == DistributionMode.AvgWeightTime) //If weight and time to move has to be avg. Cut the weight to half.
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("DistributionImpl.BalanceBuckets()", "Request comes with DistributionMode.AvgWeightTime");
distData.WeightPerNode/= 2;
}
ArrayList distMatrix = distData.DistributionMatrixForNodes;
ArrayList finalBuckets = new ArrayList();
//We need to cater for the cases where we dont need to actually balance the data over nodes, as cluster itself is starting
//and no actual load is present within a cluster and on each node.
foreach (DistributionMatrix dMatrix in distMatrix)
{
if (dMatrix.DoWeightBalance == true)
{
bShouldBalanceWeight = true;
break;
}
}
//If cluster is not loaded only shuffled disribution is required. No need to balance any weight.
if (bShouldBalanceWeight == false)
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("DistributionImpl.BalanceBuckets()", "Cluster is not loaded only shuffled disribution is required. No need to balance any weight.");
distInfo.DistribMode = DistributionMode.ShuffleBuckets;
}
//For cases below we also need to calculate Weight to be balanced along with buckets sacrifices.
switch (distInfo.DistribMode)
{
case DistributionMode.OptimalTime:
foreach (DistributionMatrix dMatrix in distMatrix)
{
int [,] IdMatrix = dMatrix.IdMatrix;
for (int i = 0; i < dMatrix.MatrixDimension.Cols; i++)
finalBuckets.Add(IdMatrix[0, i]); //Always first row of the matrix to be given
}
if (NCacheLog.IsInfoEnabled)
{
NCacheLog.Info("DistributionImpl.BalanceBuckets()", "Request is DistributionMode.OptimalTime");
NCacheLog.Info("Selected Buckets are: -");
for (int i = 0; i < finalBuckets.Count; i++)
NCacheLog.Info(finalBuckets[i].ToString());
}
return finalBuckets;
case DistributionMode.ShuffleBuckets: //Although code replication is observed here. Still I prefer to make its copy rather puting fewer if-else to control. I need some time efficiency here.
foreach (DistributionMatrix dMatrix in distMatrix)
{
int[,] IdMatrix = dMatrix.IdMatrix;
int[] resultIndices;
RowsBalanceResult rbResult = DistributionCore.ShuffleSelect(dMatrix);
resultIndices = rbResult.ResultIndicies;
for (int i = 0, j = 0; i < resultIndices.Length; i++)
{
int index = resultIndices[i]; //Index would never be zero, rather the value corresponding in the Matrix be zero.
//Get row and col on the basis of matrix index (index of one-D array).
int row = index / dMatrix.MatrixDimension.Cols;
int col = index % dMatrix.MatrixDimension.Cols;
if (IdMatrix[row, col] == -1) //dealing with exceptional case when last row is selected and it got few non-indices.So replace those with lowest most indices in the matrix.
{
finalBuckets.Add(IdMatrix[0, j]);
j++;
}
else
{
finalBuckets.Add(IdMatrix[row, col]);
}
}
}
if (NCacheLog.IsInfoEnabled )
{
NCacheLog.Info("DistributionImpl.BalanceBuckets()", "Request is DistributionMode.ShuffleBuckets");
NCacheLog.Info("Selected Buckets are: -");
for (int i = 0; i < finalBuckets.Count; i++)
NCacheLog.Info(finalBuckets[i].ToString());
}
return finalBuckets;
case DistributionMode.OptimalWeight: //For both same code works. Change is only in weight that is modified above . it is called FallThrough in switch statements.
case DistributionMode.AvgWeightTime:
foreach (DistributionMatrix dMatrix in distMatrix)
{
int[,] IdMatrix = dMatrix.IdMatrix;
int[] resultIndices;
RowsBalanceResult rbResult = DistributionCore.CompareAndSelect(dMatrix);
resultIndices = rbResult.ResultIndicies;
for (int i = 0,j=0; i < resultIndices.Length; i++)
{
int index = resultIndices[i]; //Index would never be zero, rather the value corresponding in the Matrix be zero.
//Get row and col on the basis of matrix index (index of one-D array).
int row = index / dMatrix.MatrixDimension.Cols;
int col = index % dMatrix.MatrixDimension.Cols;
if (IdMatrix[row, col] == -1) //dealing with exceptional case when last row is selected and it got few non-indices.So replace those with lowest most indices in the matrix.
{
finalBuckets.Add(IdMatrix[0,j]);
j++;
}
else
{
finalBuckets.Add(IdMatrix[row, col]);
}
}
}
if (NCacheLog.IsInfoEnabled )
{
NCacheLog.Info("DistributionImpl.BalanceBuckets()", "Request is DistributionMode.AvgWeightTime/ DistributionMode.OptimalWeight");
NCacheLog.Info("Selected Buckets are: -");
for (int i = 0; i < finalBuckets.Count; i++)
NCacheLog.Info(finalBuckets[i].ToString());
}
return finalBuckets;
default:
break;
} //end switch
return null;
} //end func.
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.Collections.Generic;
using System.Linq;
using NLog.Config;
using NLog.Targets;
using Xunit;
namespace NLog.UnitTests.Targets
{
public class MethodCallTests : NLogTestBase
{
private const string CorrectClassName = "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests";
#region ToBeCalled Methods
#pragma warning disable xUnit1013 //we need public methods here
private static MethodCallRecord LastCallTest;
public static void StaticAndPublic(string param1, int param2)
{
LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2);
}
public static void StaticAndPublicWrongParameters(string param1, string param2)
{
LastCallTest = new MethodCallRecord("StaticAndPublic", param1, param2);
}
public static void StaticAndPublicTooLessParameters(string param1)
{
LastCallTest = new MethodCallRecord("StaticAndPublicTooLessParameters", param1);
}
public static void StaticAndPublicTooManyParameters(string param1, int param2, string param3)
{
LastCallTest = new MethodCallRecord("StaticAndPublicTooManyParameters", param1, param2);
}
public static void StaticAndPublicOptional(string param1, int param2, string param3 = "fixedValue")
{
LastCallTest = new MethodCallRecord("StaticAndPublicOptional", param1, param2, param3);
}
public void NonStaticAndPublic()
{
LastCallTest = new MethodCallRecord("NonStaticAndPublic");
}
public static void StaticAndPrivate()
{
LastCallTest = new MethodCallRecord("StaticAndPrivate");
}
#pragma warning restore xUnit1013
#endregion
[Fact]
public void TestMethodCall1()
{
TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", CorrectClassName);
}
[Fact]
public void TestMethodCall2()
{
//Type AssemblyQualifiedName
//to find, use typeof(MethodCallTests).AssemblyQualifiedName
TestMethodCall(new MethodCallRecord("StaticAndPublic", "test1", 2), "StaticAndPublic", "NLog.UnitTests.Targets.MethodCallTests, NLog.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b793d3de60bec2b9");
}
[Fact]
public void PrivateMethodDontThrow()
{
using (new NoThrowNLogExceptions())
{
TestMethodCall(null, "NonStaticAndPublic", CorrectClassName);
}
}
[Fact]
public void WrongClassDontThrow()
{
TestMethodCall(null, "StaticAndPublic", "NLog.UnitTests222.Targets.CallTest, NLog.UnitTests");
}
[Fact]
public void WrongParametersDontThrow()
{
using (new NoThrowNLogExceptions())
{
TestMethodCall(null, "StaticAndPublicWrongParameters", CorrectClassName);
}
}
[Fact]
public void TooLessParametersDontThrow()
{
using (new NoThrowNLogExceptions())
{
TestMethodCall(null, "StaticAndPublicTooLessParameters", CorrectClassName);
}
}
[Fact]
public void TooManyParametersDontThrow()
{
using (new NoThrowNLogExceptions())
{
TestMethodCall(null, "StaticAndPublicTooManyParameters", CorrectClassName);
}
}
[Fact]
public void OptionalParameters()
{
TestMethodCall(new MethodCallRecord("StaticAndPublicOptional", "test1", 2, "fixedValue"), "StaticAndPublicOptional", CorrectClassName);
}
[Fact]
public void FluentDelegateConfiguration()
{
var configuration = new LoggingConfiguration();
string expectedMessage = "Hello World";
string actualMessage = string.Empty;
configuration.AddRuleForAllLevels(new MethodCallTarget("Hello", (logEvent, parameters) => { actualMessage = logEvent.Message; }));
LogManager.Configuration = configuration;
LogManager.GetCurrentClassLogger().Debug(expectedMessage);
Assert.Equal(expectedMessage, actualMessage);
}
private static void TestMethodCall(MethodCallRecord expected, string methodName, string className)
{
var target = new MethodCallTarget
{
Name = "t1",
ClassName = className,
MethodName = methodName
};
target.Parameters.Add(new MethodCallParameter("param1", "test1"));
target.Parameters.Add(new MethodCallParameter("param2", "2", typeof(int)));
var configuration = new LoggingConfiguration();
configuration.AddTarget(target);
configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
LogManager.Configuration = configuration;
LastCallTest = null;
LogManager.GetCurrentClassLogger().Debug("test method 1");
Assert.Equal(expected, LastCallTest);
}
private class MethodCallRecord
{
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object"/> class.
/// </summary>
public MethodCallRecord(string method, params object[] parameterValues)
{
Method = method;
if (parameterValues != null) ParameterValues = parameterValues.ToList();
}
public string Method { get; set; }
public List<object> ParameterValues { get; set; }
protected bool Equals(MethodCallRecord other)
{
return string.Equals(Method, other.Method) && ParameterValues.SequenceEqual(other.ParameterValues);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((MethodCallRecord)obj);
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
/// <returns>
/// A hash code for the current object.
/// </returns>
public override int GetHashCode()
{
unchecked
{
return ((Method != null ? Method.GetHashCode() : 0) * 397) ^ (ParameterValues != null ? ParameterValues.GetHashCode() : 0);
}
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using NAudio.Utils;
namespace NAudio.Midi
{
/// <summary>
/// A helper class to manage collection of MIDI events
/// It has the ability to organise them in tracks
/// </summary>
public class MidiEventCollection : IEnumerable<IList<MidiEvent>>
{
private readonly int deltaTicksPerQuarterNote;
private readonly List<IList<MidiEvent>> trackEvents;
private int midiFileType;
/// <summary>
/// Creates a new Midi Event collection
/// </summary>
/// <param name="midiFileType">Initial file type</param>
/// <param name="deltaTicksPerQuarterNote">Delta Ticks Per Quarter Note</param>
public MidiEventCollection(int midiFileType, int deltaTicksPerQuarterNote)
{
this.midiFileType = midiFileType;
this.deltaTicksPerQuarterNote = deltaTicksPerQuarterNote;
StartAbsoluteTime = 0;
trackEvents = new List<IList<MidiEvent>>();
}
/// <summary>
/// The number of tracks
/// </summary>
public int Tracks
{
get { return trackEvents.Count; }
}
/// <summary>
/// The absolute time that should be considered as time zero
/// Not directly used here, but useful for timeshifting applications
/// </summary>
public long StartAbsoluteTime { get; set; }
/// <summary>
/// The number of ticks per quarter note
/// </summary>
public int DeltaTicksPerQuarterNote
{
get { return deltaTicksPerQuarterNote; }
}
/// <summary>
/// Gets events on a specific track
/// </summary>
/// <param name="trackNumber">Track number</param>
/// <returns>The list of events</returns>
public IList<MidiEvent> this[int trackNumber]
{
get { return trackEvents[trackNumber]; }
}
/// <summary>
/// The MIDI file type
/// </summary>
public int MidiFileType
{
get { return midiFileType; }
set
{
if (midiFileType != value)
{
// set MIDI file type before calling flatten or explode functions
midiFileType = value;
if (value == 0)
{
FlattenToOneTrack();
}
else
{
ExplodeToManyTracks();
}
}
}
}
/// <summary>
/// Gets an enumerator for the lists of track events
/// </summary>
public IEnumerator<IList<MidiEvent>> GetEnumerator()
{
return trackEvents.GetEnumerator();
}
/// <summary>
/// Gets an enumerator for the lists of track events
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return trackEvents.GetEnumerator();
}
/// <summary>
/// Gets events on a specified track
/// </summary>
/// <param name="trackNumber">Track number</param>
/// <returns>The list of events</returns>
public IList<MidiEvent> GetTrackEvents(int trackNumber)
{
return trackEvents[trackNumber];
}
/// <summary>
/// Adds a new track
/// </summary>
/// <returns>The new track event list</returns>
public IList<MidiEvent> AddTrack()
{
return AddTrack(null);
}
/// <summary>
/// Adds a new track
/// </summary>
/// <param name="initialEvents">Initial events to add to the new track</param>
/// <returns>The new track event list</returns>
public IList<MidiEvent> AddTrack(IList<MidiEvent> initialEvents)
{
var events = new List<MidiEvent>();
if (initialEvents != null)
{
events.AddRange(initialEvents);
}
trackEvents.Add(events);
return events;
}
/// <summary>
/// Removes a track
/// </summary>
/// <param name="track">Track number to remove</param>
public void RemoveTrack(int track)
{
trackEvents.RemoveAt(track);
}
/// <summary>
/// Clears all events
/// </summary>
public void Clear()
{
trackEvents.Clear();
}
/// <summary>
/// Adds an event to the appropriate track depending on file type
/// </summary>
/// <param name="midiEvent">The event to be added</param>
/// <param name="originalTrack">The original (or desired) track number</param>
/// <remarks>
/// When adding events in type 0 mode, the originalTrack parameter
/// is ignored. If in type 1 mode, it will use the original track number to
/// store the new events. If the original track was 0 and this is a channel based
/// event, it will create new tracks if necessary and put it on the track corresponding
/// to its channel number
/// </remarks>
public void AddEvent(MidiEvent midiEvent, int originalTrack)
{
if (midiFileType == 0)
{
EnsureTracks(1);
trackEvents[0].Add(midiEvent);
}
else
{
if (originalTrack == 0)
{
// if its a channel based event, lets move it off to
// a channel track of its own
switch (midiEvent.CommandCode)
{
case MidiCommandCode.NoteOff:
case MidiCommandCode.NoteOn:
case MidiCommandCode.KeyAfterTouch:
case MidiCommandCode.ControlChange:
case MidiCommandCode.PatchChange:
case MidiCommandCode.ChannelAfterTouch:
case MidiCommandCode.PitchWheelChange:
EnsureTracks(midiEvent.Channel + 1);
trackEvents[midiEvent.Channel].Add(midiEvent);
break;
default:
EnsureTracks(1);
trackEvents[0].Add(midiEvent);
break;
}
}
else
{
// put it on the track it was originally on
EnsureTracks(originalTrack + 1);
trackEvents[originalTrack].Add(midiEvent);
}
}
}
private void EnsureTracks(int count)
{
for (int n = trackEvents.Count; n < count; n++)
{
trackEvents.Add(new List<MidiEvent>());
}
}
private void ExplodeToManyTracks()
{
IList<MidiEvent> originalList = trackEvents[0];
Clear();
foreach (MidiEvent midiEvent in originalList)
{
AddEvent(midiEvent, 0);
}
PrepareForExport();
}
private void FlattenToOneTrack()
{
bool eventsAdded = false;
for (int track = 1; track < trackEvents.Count; track++)
{
foreach (MidiEvent midiEvent in trackEvents[track])
{
if (!MidiEvent.IsEndTrack(midiEvent))
{
trackEvents[0].Add(midiEvent);
eventsAdded = true;
}
}
}
for (int track = trackEvents.Count - 1; track > 0; track--)
{
RemoveTrack(track);
}
if (eventsAdded)
{
PrepareForExport();
}
}
/// <summary>
/// Sorts, removes empty tracks and adds end track markers
/// </summary>
public void PrepareForExport()
{
var comparer = new MidiEventComparer();
// 1. sort each track
foreach (List<MidiEvent> list in trackEvents)
{
MergeSort.Sort(list, comparer);
// 2. remove all End track events except one at the very end
int index = 0;
while (index < list.Count - 1)
{
if (MidiEvent.IsEndTrack(list[index]))
{
list.RemoveAt(index);
}
else
{
index++;
}
}
}
int track = 0;
// 3. remove empty tracks and add missing
while (track < trackEvents.Count)
{
IList<MidiEvent> list = trackEvents[track];
if (list.Count == 0)
{
RemoveTrack(track);
}
else
{
if (list.Count == 1 && MidiEvent.IsEndTrack(list[0]))
{
RemoveTrack(track);
}
else
{
if (!MidiEvent.IsEndTrack(list[list.Count - 1]))
{
list.Add(new MetaEvent(MetaEventType.EndTrack, 0, list[list.Count - 1].AbsoluteTime));
}
track++;
}
}
}
}
}
}
| |
using System;
using Content.Client.Cooldown;
using Content.Client.Stylesheets;
using Content.Shared.Actions;
using Content.Shared.Actions.ActionTypes;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.Utility;
using Robust.Shared.Input;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using static Robust.Client.UserInterface.Controls.BoxContainer;
namespace Content.Client.Actions.UI
{
/// <summary>
/// A slot in the action hotbar. Not extending BaseButton because
/// its needs diverged too much.
/// </summary>
public sealed class ActionSlot : PanelContainer
{
// shorter than default tooltip delay so user can more easily
// see what actions they've been given
private const float CustomTooltipDelay = 0.5f;
private static readonly string EnabledColor = "#7b7e9e";
private static readonly string DisabledColor = "#950000";
/// <summary>
/// Current action in this slot.
/// </summary>
public ActionType? Action { get; private set; }
/// <summary>
/// 1-10 corresponding to the number label on the slot (10 is labeled as 0)
/// </summary>
private byte SlotNumber => (byte) (SlotIndex + 1);
public byte SlotIndex { get; }
private readonly IGameTiming _gameTiming;
private readonly RichTextLabel _number;
private readonly TextureRect _bigActionIcon;
private readonly TextureRect _smallActionIcon;
private readonly SpriteView _smallItemSpriteView;
private readonly SpriteView _bigItemSpriteView;
private readonly CooldownGraphic _cooldownGraphic;
private readonly ActionsUI _actionsUI;
private readonly ActionMenu _actionMenu;
// whether button is currently pressed down by mouse or keybind down.
private bool _depressed;
private bool _beingHovered;
/// <summary>
/// Creates an action slot for the specified number
/// </summary>
/// <param name="slotIndex">slot index this corresponds to, 0-9 (0 labeled as 1, 8, labeled "9", 9 labeled as "0".</param>
public ActionSlot(ActionsUI actionsUI, ActionMenu actionMenu, byte slotIndex)
{
_actionsUI = actionsUI;
_actionMenu = actionMenu;
_gameTiming = IoCManager.Resolve<IGameTiming>();
SlotIndex = slotIndex;
MouseFilter = MouseFilterMode.Stop;
SetSize = (64, 64);
VerticalAlignment = VAlignment.Top;
TooltipDelay = CustomTooltipDelay;
TooltipSupplier = SupplyTooltip;
_number = new RichTextLabel
{
StyleClasses = {StyleNano.StyleClassHotbarSlotNumber}
};
_number.SetMessage(SlotNumberLabel());
_bigActionIcon = new TextureRect
{
HorizontalExpand = true,
VerticalExpand = true,
Stretch = TextureRect.StretchMode.Scale,
Visible = false
};
_bigItemSpriteView = new SpriteView
{
HorizontalExpand = true,
VerticalExpand = true,
Scale = (2,2),
Visible = false,
OverrideDirection = Direction.South,
};
_smallActionIcon = new TextureRect
{
HorizontalAlignment = HAlignment.Right,
VerticalAlignment = VAlignment.Bottom,
Stretch = TextureRect.StretchMode.Scale,
Visible = false
};
_smallItemSpriteView = new SpriteView
{
HorizontalAlignment = HAlignment.Right,
VerticalAlignment = VAlignment.Bottom,
Visible = false,
OverrideDirection = Direction.South,
};
_cooldownGraphic = new CooldownGraphic {Progress = 0, Visible = false};
// padding to the left of the number to shift it right
var paddingBox = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
HorizontalExpand = true,
VerticalExpand = true,
MinSize = (64, 64)
};
paddingBox.AddChild(new Control()
{
MinSize = (4, 4),
});
paddingBox.AddChild(_number);
// padding to the left of the small icon
var paddingBoxItemIcon = new BoxContainer
{
Orientation = LayoutOrientation.Horizontal,
HorizontalExpand = true,
VerticalExpand = true,
MinSize = (64, 64)
};
paddingBoxItemIcon.AddChild(new Control()
{
MinSize = (32, 32),
});
paddingBoxItemIcon.AddChild(new Control
{
Children =
{
_smallActionIcon,
_smallItemSpriteView
}
});
AddChild(_bigActionIcon);
AddChild(_bigItemSpriteView);
AddChild(_cooldownGraphic);
AddChild(paddingBox);
AddChild(paddingBoxItemIcon);
DrawModeChanged();
}
private Control? SupplyTooltip(Control sender)
{
if (Action == null)
return null;
string? extra = null;
if (Action.Charges != null)
{
extra = Loc.GetString("ui-actionslot-charges", ("charges", Action.Charges));
}
var name = FormattedMessage.FromMarkupPermissive(Loc.GetString(Action.Name));
var decr = FormattedMessage.FromMarkupPermissive(Loc.GetString(Action.Description));
var tooltip = new ActionAlertTooltip(name, decr, extra);
if (Action.Enabled && (Action.Charges == null || Action.Charges != 0))
tooltip.Cooldown = Action.Cooldown;
return tooltip;
}
protected override void MouseEntered()
{
base.MouseEntered();
_beingHovered = true;
DrawModeChanged();
if (Action?.Provider != null)
_actionsUI.System.HighlightItemSlot(Action.Provider.Value);
}
protected override void MouseExited()
{
base.MouseExited();
_beingHovered = false;
CancelPress();
DrawModeChanged();
_actionsUI.System.StopHighlightingItemSlot();
}
protected override void KeyBindDown(GUIBoundKeyEventArgs args)
{
base.KeyBindDown(args);
if (Action == null)
{
// No action for this slot. Maybe the user is trying to add a mapping action?
_actionsUI.System.TryFillSlot(_actionsUI.SelectedHotbar, SlotIndex);
return;
}
// only handle clicks, and can't do anything to this if no assignment
if (args.Function == EngineKeyFunctions.UIClick)
{
// might turn into a drag or a full press if released
Depress(true);
_actionsUI.DragDropHelper.MouseDown(this);
DrawModeChanged();
return;
}
if (args.Function != EngineKeyFunctions.UIRightClick || _actionsUI.Locked)
return;
if (_actionsUI.DragDropHelper.IsDragging || _actionMenu.IsDragging)
return;
// user right clicked on an action slot, so we clear it.
_actionsUI.System.Assignments.ClearSlot(_actionsUI.SelectedHotbar, SlotIndex, true);
// If this was a temporary action, and it is no longer assigned to any slots, then we remove the action
// altogether.
if (Action.Temporary)
{
// Theres probably a better way to do this.....
DebugTools.Assert(Action.ClientExclusive, "Temporary-actions must be client exclusive");
if (!_actionsUI.System.Assignments.Assignments.TryGetValue(Action, out var index)
|| index.Count == 0)
{
_actionsUI.Component.Actions.Remove(Action);
}
}
_actionsUI.StopTargeting();
_actionsUI.UpdateUI();
}
protected override void KeyBindUp(GUIBoundKeyEventArgs args)
{
base.KeyBindUp(args);
if (args.Function != EngineKeyFunctions.UIClick)
return;
// might be finishing a drag or using the action
if (_actionsUI.DragDropHelper.IsDragging &&
_actionsUI.DragDropHelper.Dragged == this &&
UserInterfaceManager.CurrentlyHovered is ActionSlot targetSlot &&
targetSlot != this)
{
// finish the drag, swap the 2 slots
var fromIdx = SlotIndex;
var fromAssignment = _actionsUI.System.Assignments[_actionsUI.SelectedHotbar, fromIdx];
var toIdx = targetSlot.SlotIndex;
var toAssignment = _actionsUI.System.Assignments[_actionsUI.SelectedHotbar, toIdx];
if (fromIdx == toIdx) return;
if (fromAssignment == null) return;
_actionsUI.System.Assignments.AssignSlot(_actionsUI.SelectedHotbar, toIdx, fromAssignment);
if (toAssignment != null)
{
_actionsUI.System.Assignments.AssignSlot(_actionsUI.SelectedHotbar, fromIdx, toAssignment);
}
else
{
_actionsUI.System.Assignments.ClearSlot(_actionsUI.SelectedHotbar, fromIdx, false);
}
_actionsUI.UpdateUI();
}
else
{
// perform the action
if (UserInterfaceManager.CurrentlyHovered == this)
{
Depress(false);
}
}
_actionsUI.DragDropHelper.EndDrag();
DrawModeChanged();
}
protected override void ControlFocusExited()
{
// lost focus for some reason, cancel the drag if there is one.
base.ControlFocusExited();
_actionsUI.DragDropHelper.EndDrag();
DrawModeChanged();
}
/// <summary>
/// Cancel current press without triggering the action
/// </summary>
public void CancelPress()
{
_depressed = false;
DrawModeChanged();
}
/// <summary>
/// Press this button down. If it was depressed and now set to not depressed, will
/// trigger the action.
/// </summary>
public void Depress(bool depress)
{
// action can still be toggled if it's allowed to stay selected
if (Action == null || !Action.Enabled) return;
if (_depressed && !depress)
{
// fire the action
_actionsUI.System.OnSlotPressed(this);
}
_depressed = depress;
}
/// <summary>
/// Updates the item action assigned to this slot, tied to a specific item.
/// </summary>
/// <param name="action">action to assign</param>
/// <param name="item">item the action is provided by</param>
public void Assign(ActionType action)
{
// already assigned
if (Action != null && Action == action) return;
Action = action;
HideTooltip();
UpdateIcons();
DrawModeChanged();
_number.SetMessage(SlotNumberLabel());
}
/// <summary>
/// Clears the action assigned to this slot
/// </summary>
public void Clear()
{
if (Action == null) return;
Action = null;
_depressed = false;
HideTooltip();
UpdateIcons();
DrawModeChanged();
_number.SetMessage(SlotNumberLabel());
}
/// <summary>
/// Display the action in this slot (if there is one) as enabled
/// </summary>
public void Enable()
{
DrawModeChanged();
_number.SetMessage(SlotNumberLabel());
}
/// <summary>
/// Display the action in this slot (if there is one) as disabled.
/// The slot is still clickable.
/// </summary>
public void Disable()
{
_depressed = false;
DrawModeChanged();
_number.SetMessage(SlotNumberLabel());
}
private FormattedMessage SlotNumberLabel()
{
if (SlotNumber > 10) return FormattedMessage.FromMarkup("");
var number = Loc.GetString(SlotNumber == 10 ? "0" : SlotNumber.ToString());
var color = (Action == null || Action.Enabled) ? EnabledColor : DisabledColor;
return FormattedMessage.FromMarkup("[color=" + color + "]" + number + "[/color]");
}
public void UpdateIcons()
{
UpdateItemIcon();
if (Action == null)
{
SetActionIcon(null);
return;
}
if ((_actionsUI.SelectingTargetFor?.Action == Action || Action.Toggled) && Action.IconOn != null)
SetActionIcon(Action.IconOn.Frame0());
else
SetActionIcon(Action.Icon?.Frame0());
}
private void SetActionIcon(Texture? texture)
{
if (texture == null || Action == null)
{
_bigActionIcon.Texture = null;
_bigActionIcon.Visible = false;
_smallActionIcon.Texture = null;
_smallActionIcon.Visible = false;
}
else if (Action.Provider != null && Action.ItemIconStyle == ItemActionIconStyle.BigItem)
{
_smallActionIcon.Texture = texture;
_smallActionIcon.Modulate = Action.IconColor;
_smallActionIcon.Visible = true;
_bigActionIcon.Texture = null;
_bigActionIcon.Visible = false;
}
else
{
_bigActionIcon.Texture = texture;
_bigActionIcon.Modulate = Action.IconColor;
_bigActionIcon.Visible = true;
_smallActionIcon.Texture = null;
_smallActionIcon.Visible = false;
}
}
private void UpdateItemIcon()
{
if (Action?.Provider == null || !IoCManager.Resolve<IEntityManager>().TryGetComponent(Action.Provider.Value, out SpriteComponent sprite))
{
_bigItemSpriteView.Visible = false;
_bigItemSpriteView.Sprite = null;
_smallItemSpriteView.Visible = false;
_smallItemSpriteView.Sprite = null;
}
else
{
switch (Action.ItemIconStyle)
{
case ItemActionIconStyle.BigItem:
_bigItemSpriteView.Visible = true;
_bigItemSpriteView.Sprite = sprite;
_smallItemSpriteView.Visible = false;
_smallItemSpriteView.Sprite = null;
break;
case ItemActionIconStyle.BigAction:
_bigItemSpriteView.Visible = false;
_bigItemSpriteView.Sprite = null;
_smallItemSpriteView.Visible = true;
_smallItemSpriteView.Sprite = sprite;
break;
case ItemActionIconStyle.NoItem:
_bigItemSpriteView.Visible = false;
_bigItemSpriteView.Sprite = null;
_smallItemSpriteView.Visible = false;
_smallItemSpriteView.Sprite = null;
break;
}
}
}
public void DrawModeChanged()
{
// always show the normal empty button style if no action in this slot
if (Action == null)
{
SetOnlyStylePseudoClass(ContainerButton.StylePseudoClassNormal);
return;
}
// show a hover only if the action is usable or another action is being dragged on top of this
if (_beingHovered && (_actionsUI.DragDropHelper.IsDragging || _actionMenu.IsDragging || Action.Enabled))
{
SetOnlyStylePseudoClass(ContainerButton.StylePseudoClassHover);
}
// it's only depress-able if it's usable, so if we're depressed
// show the depressed style
if (_depressed)
{
SetOnlyStylePseudoClass(ContainerButton.StylePseudoClassPressed);
return;
}
// if it's toggled on, always show the toggled on style (currently same as depressed style)
if (Action.Toggled || _actionsUI.SelectingTargetFor == this)
{
// when there's a toggle sprite, we're showing that sprite instead of highlighting this slot
SetOnlyStylePseudoClass(Action.IconOn != null ? ContainerButton.StylePseudoClassNormal :
ContainerButton.StylePseudoClassPressed);
return;
}
if (!Action.Enabled)
{
SetOnlyStylePseudoClass(ContainerButton.StylePseudoClassDisabled);
return;
}
SetOnlyStylePseudoClass(ContainerButton.StylePseudoClassNormal);
}
protected override void FrameUpdate(FrameEventArgs args)
{
base.FrameUpdate(args);
if (Action == null || Action.Cooldown == null || !Action.Enabled)
{
_cooldownGraphic.Visible = false;
_cooldownGraphic.Progress = 0;
return;
}
var cooldown = Action.Cooldown.Value;
var duration = cooldown.End - cooldown.Start;
var curTime = _gameTiming.CurTime;
var length = duration.TotalSeconds;
var progress = (curTime - cooldown.Start).TotalSeconds / length;
var ratio = (progress <= 1 ? (1 - progress) : (curTime - cooldown.End).TotalSeconds * -5);
_cooldownGraphic.Progress = MathHelper.Clamp((float)ratio, -1, 1);
if (ratio > -1f)
_cooldownGraphic.Visible = true;
else
{
_cooldownGraphic.Visible = false;
Action.Cooldown = null;
DrawModeChanged();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
namespace System.Drawing.Internal
{
/// <summary>
/// Debug help utility.
/// </summary>
[
ReflectionPermission(SecurityAction.Assert, MemberAccess = true),
EnvironmentPermission(SecurityAction.Assert, Unrestricted = true),
FileIOPermission(SecurityAction.Assert, Unrestricted = true),
SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode),
UIPermission(SecurityAction.Assert, Unrestricted = true)
]
internal sealed class DbgUtil
{
public const int
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM;
[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetUserDefaultLCID();
[DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, HandleRef arguments);
public static int gdipInitMaxFrameCount = 8;
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
public static int gdiUseMaxFrameCount = 8;
public static int finalizeMaxFrameCount = 5;
#pragma warning restore 0414
/// <summary>
/// Call this method from your Dispose(bool) to assert that unmanaged resources has been explicitly disposed.
/// </summary>
[Conditional("DEBUG")]
public static void AssertFinalization(object obj, bool disposing)
{
#if GDI_FINALIZATION_WATCH
if( disposing || AppDomain.CurrentDomain.IsFinalizingForUnload() )
{
return;
}
try
{
BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Static | BindingFlags.Instance;
FieldInfo allocSiteFld = obj.GetType().GetField("AllocationSite", bindingFlags);
string allocationSite = allocSiteFld != null ? allocSiteFld.GetValue( obj ).ToString() : "<Allocation site unavailable>";
// ignore ojects created by WindowsGraphicsCacheManager.
if( allocationSite.Contains("WindowsGraphicsCacheManager") )
{
return;
}
Debug.Fail("Object Disposed through finalization - it should be explicitly disposed.");
Debug.WriteLine("Allocation stack:\r\n" + allocationSite);
}
catch(Exception ex)
{
try
{
Debug.WriteLine("Exception thrown while trying to get allocation stack: " + ex);
}
catch
{
}
}
#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string message)
{
#if DEBUG
if (!expression)
{
Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr());
}
#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1)
{
#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1 };
AssertWin32Impl(expression, format, args);
}
#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2)
{
#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2 };
AssertWin32Impl(expression, format, args);
}
#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3)
{
#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2, arg3 };
AssertWin32Impl(expression, format, args);
}
#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3, object arg4)
{
#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2, arg3, arg4 };
AssertWin32Impl(expression, format, args);
}
#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3, object arg4, object arg5)
{
#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2, arg3, arg4, arg5 };
AssertWin32Impl(expression, format, args);
}
#endif
}
[Conditional("DEBUG")]
private static void AssertWin32Impl(bool expression, string format, object[] args)
{
#if DEBUG
if (!expression)
{
string message = string.Format(CultureInfo.CurrentCulture, format, args);
Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr());
}
#endif
}
// WARNING: Your PInvoke function needs to have the DllImport.SetLastError=true for this method
// to work properly. From the 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.
//
// You can only use this method to obtain error codes if you apply the System.Runtime.InteropServices.DllImportAttribute
// to the method signature and set the SetLastError field to true.
public static string GetLastErrorStr()
{
int MAX_SIZE = 255;
StringBuilder buffer = new StringBuilder(MAX_SIZE);
string message = String.Empty;
int err = 0;
try
{
err = Marshal.GetLastWin32Error();
int retVal = FormatMessage(
FORMAT_MESSAGE_DEFAULT,
new HandleRef(null, IntPtr.Zero),
err,
GetUserDefaultLCID(),
buffer,
MAX_SIZE,
new HandleRef(null, IntPtr.Zero));
message = retVal != 0 ? buffer.ToString() : "<error returned>";
}
catch (Exception ex)
{
if (DbgUtil.IsCriticalException(ex))
{
throw; //rethrow critical exception.
}
message = ex.ToString();
}
return String.Format(CultureInfo.CurrentCulture, "0x{0:x8} - {1}", err, message);
}
/// <summary>
/// Duplicated here from ClientUtils not to depend on that code because this class is to be compiled into
/// System.Drawing and System.Windows.Forms.
/// </summary>
private static bool IsCriticalException(Exception ex)
{
return
ex is StackOverflowException ||
ex is OutOfMemoryException ||
ex is System.Threading.ThreadAbortException;
}
public static string StackTrace
{
get
{
return Environment.StackTrace;
}
}
/// <summary>
/// Returns information about the top stack frames in a string format. The input param determines the number of
/// frames to include.
/// </summary>
public static string StackFramesToStr(int maxFrameCount)
{
string trace = String.Empty;
try
{
StackTrace st = new StackTrace(true);
int dbgUtilFrameCount = 0;
//
// Ignore frames for methods on this library.
// Note: The stack frame holds the latest frame at index 0.
//
while (dbgUtilFrameCount < st.FrameCount)
{
StackFrame sf = st.GetFrame(dbgUtilFrameCount);
if (sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil))
{
break;
}
dbgUtilFrameCount++;
}
maxFrameCount += dbgUtilFrameCount; // add ignored frames.
if (maxFrameCount > st.FrameCount)
{
maxFrameCount = st.FrameCount;
}
for (int i = dbgUtilFrameCount; i < maxFrameCount; i++)
{
StackFrame sf = st.GetFrame(i);
if (sf == null)
{
continue;
}
MethodBase mi = sf.GetMethod();
if (mi == null)
{
continue;
}
string args = String.Empty;
string fileName = sf.GetFileName();
int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf('\\');
if (backSlashIndex != -1)
{
fileName = fileName.Substring(backSlashIndex + 1, fileName.Length - backSlashIndex - 1);
}
foreach (ParameterInfo pi in mi.GetParameters())
{
args += pi.ParameterType.Name + ", ";
}
if (args.Length > 0) // remove last comma.
{
args = args.Substring(0, args.Length - 2);
}
trace += String.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args);
}
}
catch (Exception ex)
{
if (IsCriticalException(ex))
{
throw; //rethrow critical exception.
}
trace += ex.ToString();
}
return trace.ToString();
}
/// <summary>
/// Returns information about the top stack frames in a string format.
/// </summary>
public static string StackFramesToStr()
{
return StackFramesToStr(gdipInitMaxFrameCount);
}
/// <summary>
/// Returns information about the top stack frames in a string format. The input param determines the number of
/// frames to include. The 'message' parameter is used as the header of the returned string.
/// </summary>
public static string StackTraceToStr(string message, int frameCount)
{
return String.Format(CultureInfo.CurrentCulture, "{0}\r\nTop Stack Trace:\r\n{1}", message, DbgUtil.StackFramesToStr(frameCount));
}
/// <summary>
/// Returns information about the top stack frames in a string format. The 'message' parameter is used as the header of the returned string.
/// </summary>
public static string StackTraceToStr(string message)
{
return StackTraceToStr(message, DbgUtil.gdipInitMaxFrameCount);
}
}
}
| |
// Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License.
namespace Zahasoft.Feedex.Endpoint.Controllers
{
using Common;
using Factories;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Models;
using Objects;
using Security;
using Services;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
[Authorize]
[RoutePrefix("api/auth")]
public class AuthController : BaseController
{
const string LocalLoginProvider = "Local";
IdentityUserManager userManager;
readonly EmailService emailService = new EmailService();
readonly CleanService cleanService = new CleanService();
public AuthController() { }
public AuthController(IdentityUserManager userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
public IdentityUserManager UserManager
{
get
{
return userManager ?? Request.GetOwinContext().GetUserManager<IdentityUserManager>();
}
private set
{
userManager = value;
}
}
public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; }
[HttpPost]
[Route("logout")]
[Authorize]
public IHttpActionResult Logout()
{
Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
return Ok();
}
[HttpGet]
[Route("login")]
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
[AllowAnonymous]
public async Task<IHttpActionResult> Login(string provider, string error = null)
{
if (error != null)
{
return NotFound();
}
if (!User.Identity.IsAuthenticated)
{
return new AuthorizationResult(provider, this);
}
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
if (externalLogin == null)
{
return NotFound();
}
if (externalLogin.LoginProvider != provider)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
return new AuthorizationResult(provider, this);
}
User user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));
bool hasRegistered = user != null;
if (hasRegistered)
{
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = AuthorizationProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
}
else
{
IEnumerable<Claim> claims = externalLogin.GetClaims();
var identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
Authentication.SignIn(identity);
}
return Ok();
}
[HttpPost]
[Route("register")]
[AllowAnonymous]
public async Task<IHttpActionResult> Register(CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
User user = UserFactory.ConstructUser(model);
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
user = await UserManager.FindByNameAsync(model.Username);
await UserManager.AddToRoleAsync(user.Id, Constant.UserRoleConsumer);
await UserManager.UpdateAsync(user);
cleanService.Start(user.Id, 600000);
await emailService.SendMailAsync(Constant.FeedexServiceEmail, user.Email, "Confirm Registration", string.Format("Confirmation code: {0}", user.ConfirmationCode));
}
else
{
var builder = new StringBuilder();
foreach (string error in result.Errors)
{
builder.AppendLine(error);
}
return BadRequest(builder.ToString());
}
}
catch (Exception ex)
{
SaveError(string.Format("Register user : {0}", ex.Message), model.Username);
return InternalServerError();
}
return Ok();
}
[HttpPost]
[Route("confirm")]
[AllowAnonymous]
public async Task<IHttpActionResult> Confirm(ConfirmEmailModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
User user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
return NotFound();
}
if (user.ConfirmationCode == model.Code && !user.EmailConfirmed)
{
user.EmailConfirmed = true;
await UserManager.UpdateAsync(user);
}
}
catch (Exception ex)
{
SaveError(string.Format("Confirm user with code {0} : {1}", model.Code, ex.Message), model.Email);
return InternalServerError();
}
return Ok();
}
[HttpPost]
[Route("forgotpassword")]
[AllowAnonymous]
public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
User user = await UserManager.FindByNameAsync(model.Email);
if (user != null && user.EmailConfirmed)
{
return Ok(await UserManager.GeneratePasswordResetTokenAsync(user.Id));
}
}
catch (Exception ex)
{
SaveError(string.Format("Forgot password failed: {0}", ex.Message), model.Email);
return InternalServerError();
}
return NotFound();
}
[HttpPost]
[Route("resetpassword")]
[AllowAnonymous]
public async Task<IHttpActionResult> ResetPassword(ResetPasswordModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
User user = await UserManager.FindByNameAsync(model.Email);
if (user != null)
{
IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return Ok();
}
}
}
catch (Exception ex)
{
SaveError(string.Format("Reset password failed: {0}", ex.Message), model.Email);
return InternalServerError();
}
return NotFound();
}
[HttpPost]
[Route("changepassword")]
public async Task<IHttpActionResult> ChangePassword(ChangePasswordModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
model.NewPassword);
if (!result.Succeeded)
{
return NotFound();
}
}
catch (Exception ex)
{
SaveError(string.Format("Change password failed: {0}", ex.Message), User.Identity.Name);
return InternalServerError();
}
return Ok();
}
[HttpGet]
[Authorize]
[Route("profile")]
public async Task<IHttpActionResult> GetUser()
{
try
{
User user = await db.Users
.Include(x => x.Feeds)
.Include(x => x.Likes)
.SingleOrDefaultAsync(x => x.UserName == User.Identity.Name);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
catch (Exception ex)
{
SaveError(string.Format("Get current user {0}", ex.Message), User.Identity.Name);
return InternalServerError();
}
}
protected override void Dispose(bool disposing)
{
if (disposing && UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
IAuthenticationManager Authentication => Request.GetOwinContext().Authentication;
class ExternalLoginData
{
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
public string UserName { get; set; }
public IList<Claim> GetClaims()
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));
if (UserName != null)
{
claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
}
return claims;
}
public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
{
if (identity == null)
{
return null;
}
Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value))
{
return null;
}
if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
{
return null;
}
return new ExternalLoginData
{
LoginProvider = providerKeyClaim.Issuer,
ProviderKey = providerKeyClaim.Value,
UserName = identity.FindFirstValue(ClaimTypes.Name)
};
}
}
}
}
| |
//
// main.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Paul Lange <palango@gmx.de>
// Evan Briones <erbriones@gmail.com>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2006-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2010 Paul Lange
// Copyright (C) 2010 Evan Briones
// Copyright (C) 2006-2009 Stephane Delcroix
//
// 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.IO;
using System.Collections.Generic;
using Mono.Unix;
using Mono.Addins;
using Mono.Addins.Setup;
using FSpot.Settings;
using FSpot.Utils;
using Hyena;
using Hyena.CommandLine;
using Hyena.Gui;
namespace FSpot
{
public static class Driver
{
static void ShowVersion ()
{
Console.WriteLine ("F-Spot {0}", Defines.VERSION);
Console.WriteLine ("http://f-spot.org");
Console.WriteLine ("\t(c)2003-2009, Novell Inc");
Console.WriteLine ("\t(c)2009 Stephane Delcroix");
Console.WriteLine ("Personal photo management for the GNOME Desktop");
}
static void ShowAssemblyVersions ()
{
ShowVersion ();
Console.WriteLine ();
Console.WriteLine ("Mono/.NET Version: " + Environment.Version);
Console.WriteLine (string.Format ("{0}Assembly Version Information:", Environment.NewLine));
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) {
AssemblyName name = asm.GetName ();
Console.WriteLine ("\t" + name.Name + " (" + name.Version + ")");
}
}
static void ShowHelp ()
{
Console.WriteLine ("Usage: f-spot [options...] [files|URIs...]");
Console.WriteLine ();
var commands = new Hyena.CommandLine.Layout (
new LayoutGroup ("help", "Help Options",
new LayoutOption ("help", "Show this help"),
new LayoutOption ("help-options", "Show command line options"),
new LayoutOption ("help-all", "Show all options"),
new LayoutOption ("version", "Show version information"),
new LayoutOption ("versions", "Show detailed version information")),
new LayoutGroup ("options", "General options",
new LayoutOption ("basedir=DIR", "Path to the photo database folder"),
new LayoutOption ("import=URI", "Import from the given uri"),
new LayoutOption ("photodir=DIR", "Default import folder"),
new LayoutOption ("view ITEM", "View file(s) or directories"),
new LayoutOption ("shutdown", "Shut down a running instance of F-Spot"),
new LayoutOption ("slideshow", "Display a slideshow"),
new LayoutOption ("debug", "Run in debug mode")));
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-options": Console.WriteLine (commands.ToString ("options")); 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 (
"The following help arguments are invalid: {0}",
Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", "))));
}
}
static string [] FixArgs (string [] args)
{
// Makes sure command line arguments are parsed backwards compatible.
var outargs = new List<string> ();
for (int i = 0; i < args.Length; i++) {
switch (args [i]) {
case "-h":
case "-help":
case "-usage":
outargs.Add ("--help");
break;
case "-V":
case "-version":
outargs.Add ("--version");
break;
case "-versions":
outargs.Add ("--versions");
break;
case "-shutdown":
outargs.Add ("--shutdown");
break;
case "-b":
case "-basedir":
case "--basedir":
outargs.Add ("--basedir=" + (i + 1 == args.Length ? string.Empty : args [++i]));
break;
case "-p":
case "-photodir":
case "--photodir":
outargs.Add ("--photodir=" + (i + 1 == args.Length ? string.Empty : args [++i]));
break;
case "-i":
case "-import":
case "--import":
outargs.Add ("--import=" + (i + 1 == args.Length ? string.Empty : args [++i]));
break;
case "-v":
case "-view":
outargs.Add ("--view");
break;
case "-slideshow":
outargs.Add ("--slideshow");
break;
default:
outargs.Add (args [i]);
break;
}
}
return outargs.ToArray ();
}
static int Main (string [] args)
{
args = FixArgs (args);
ApplicationContext.ApplicationName = "F-Spot";
ApplicationContext.TrySetProcessName (Defines.PACKAGE);
Paths.ApplicationName = "f-spot";
ThreadAssist.InitializeMainThread ();
ThreadAssist.ProxyToMainHandler = RunIdle;
// Options and Option parsing
bool shutdown = false;
bool view = false;
bool slideshow = false;
bool import = false;
GLib.GType.Init ();
Catalog.Init ("f-spot", Defines.LOCALE_DIR);
Global.PhotoUri = new SafeUri (Preferences.Get<string> (Preferences.STORAGE_PATH));
ApplicationContext.CommandLine = new CommandLineParser (args, 0);
if (ApplicationContext.CommandLine.ContainsStart ("help")) {
ShowHelp ();
return 0;
}
if (ApplicationContext.CommandLine.Contains ("version")) {
ShowVersion ();
return 0;
}
if (ApplicationContext.CommandLine.Contains ("versions")) {
ShowAssemblyVersions ();
return 0;
}
if (ApplicationContext.CommandLine.Contains ("shutdown")) {
Log.Information ("Shutting down existing F-Spot server...");
shutdown = true;
}
if (ApplicationContext.CommandLine.Contains ("slideshow")) {
Log.Information ("Running F-Spot in slideshow mode.");
slideshow = true;
}
if (ApplicationContext.CommandLine.Contains ("basedir")) {
string dir = ApplicationContext.CommandLine ["basedir"];
if (!string.IsNullOrEmpty (dir)) {
Global.BaseDirectory = dir;
Log.InformationFormat ("BaseDirectory is now {0}", dir);
} else {
Log.Error ("f-spot: -basedir option takes one argument");
return 1;
}
}
if (ApplicationContext.CommandLine.Contains ("photodir")) {
string dir = ApplicationContext.CommandLine ["photodir"];
if (!string.IsNullOrEmpty (dir)) {
Global.PhotoUri = new SafeUri (dir);
Log.InformationFormat ("PhotoDirectory is now {0}", dir);
} else {
Log.Error ("f-spot: -photodir option takes one argument");
return 1;
}
}
if (ApplicationContext.CommandLine.Contains ("import"))
import = true;
if (ApplicationContext.CommandLine.Contains ("view"))
view = true;
if (ApplicationContext.CommandLine.Contains ("debug")) {
Log.Debugging = true;
// Debug GdkPixbuf critical warnings
var logFunc = new GLib.LogFunc (GLib.Log.PrintTraceLogFunction);
GLib.Log.SetLogHandler ("GdkPixbuf", GLib.LogLevelFlags.Critical, logFunc);
// Debug Gtk critical warnings
GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, logFunc);
// Debug GLib critical warnings
GLib.Log.SetLogHandler ("GLib", GLib.LogLevelFlags.Critical, logFunc);
//Debug GLib-GObject critical warnings
GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.Critical, logFunc);
GLib.Log.SetLogHandler ("GLib-GIO", GLib.LogLevelFlags.Critical, logFunc);
}
// Validate command line options
if ((import && (view || shutdown || slideshow)) ||
(view && (shutdown || slideshow)) ||
(shutdown && slideshow)) {
Log.Error ("Can't mix -import, -view, -shutdown or -slideshow");
return 1;
}
InitializeAddins ();
// Gtk initialization
Gtk.Application.Init (Defines.PACKAGE, ref args);
// Maybe we'll add this at a future date
//Xwt.Application.InitializeAsGuest (Xwt.ToolkitType.Gtk);
// init web proxy globally
Platform.WebProxy.Init ();
if (File.Exists (Preferences.Get<string> (Preferences.GTK_RC))) {
if (File.Exists (Path.Combine (Global.BaseDirectory, "gtkrc")))
Gtk.Rc.AddDefaultFile (Path.Combine (Global.BaseDirectory, "gtkrc"));
Global.DefaultRcFiles = Gtk.Rc.DefaultFiles;
Gtk.Rc.AddDefaultFile (Preferences.Get<string> (Preferences.GTK_RC));
Gtk.Rc.ReparseAllForSettings (Gtk.Settings.Default, true);
}
try {
Gtk.Window.DefaultIconList = new Gdk.Pixbuf [] {
GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 16, 0),
GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 22, 0),
GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 32, 0),
GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 48, 0)
};
} catch (Exception ex) {
Log.Exception ("Loading default f-spot icons", ex);
}
GLib.ExceptionManager.UnhandledException += exceptionArgs =>
{
Console.WriteLine ("Unhandeled exception handler:");
var exception = exceptionArgs.ExceptionObject as Exception;
if (exception != null) {
Console.WriteLine ("Message: " + exception.Message);
Console.WriteLine ("Stack trace: " + exception.StackTrace);
}
else {
Console.WriteLine ("Unknown exception type: " + exceptionArgs.ExceptionObject.GetType ().ToString ());
}
};
CleanRoomStartup.Startup (Startup);
// Running threads are preventing the application from quitting
// we force it for now until this is fixed
Environment.Exit (0);
return 0;
}
static void InitializeAddins ()
{
uint timer = Log.InformationTimerStart ("Initializing Mono.Addins");
try {
UpdatePlugins ();
} catch (Exception) {
Log.Debug ("Failed to initialize plugins, will remove addin-db and try again.");
ResetPluginDb ();
}
var setupService = new SetupService (AddinManager.Registry);
foreach (AddinRepository repo in setupService.Repositories.GetRepositories ()) {
if (repo.Url.StartsWith ("http://addins.f-spot.org/")) {
Log.InformationFormat ("Unregistering {0}", repo.Url);
setupService.Repositories.RemoveRepository (repo.Url);
}
}
Log.DebugTimerPrint (timer, "Mono.Addins Initialization took {0}");
}
static void UpdatePlugins ()
{
AddinManager.Initialize (Global.BaseDirectory);
AddinManager.Registry.Update (null);
}
static void ResetPluginDb ()
{
// Nuke addin-db
var directory = GLib.FileFactory.NewForUri (new SafeUri (Global.BaseDirectory));
using (var list = directory.EnumerateChildren ("standard::name", GLib.FileQueryInfoFlags.None, null)) {
foreach (GLib.FileInfo info in list) {
if (info.Name.StartsWith ("addin-db-")) {
var file = GLib.FileFactory.NewForPath (Path.Combine (directory.Path, info.Name));
file.DeleteRecursive ();
}
}
}
// Try again
UpdatePlugins ();
}
static void Startup ()
{
if (ApplicationContext.CommandLine.Contains ("slideshow"))
App.Instance.Slideshow (null);
else if (ApplicationContext.CommandLine.Contains ("shutdown"))
App.Instance.Shutdown ();
else if (ApplicationContext.CommandLine.Contains ("view")) {
if (ApplicationContext.CommandLine.Files.Count == 0) {
Log.Error ("f-spot: -view option takes at least one argument");
Environment.Exit (1);
}
var list = new UriList ();
foreach (var f in ApplicationContext.CommandLine.Files)
list.AddUnknown (f);
if (list.Count == 0) {
ShowHelp ();
Environment.Exit (1);
}
App.Instance.View (list);
} else if (ApplicationContext.CommandLine.Contains ("import")) {
string dir = ApplicationContext.CommandLine ["import"];
if (string.IsNullOrEmpty (dir)) {
Log.Error ("f-spot: -import option takes one argument");
Environment.Exit (1);
}
App.Instance.Import (dir);
} else
App.Instance.Organize ();
if (!App.Instance.IsRunning)
Gtk.Application.Run ();
}
public static void RunIdle (InvokeHandler handler)
{
GLib.Idle.Add (delegate { handler (); return false; });
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
using UnityStandardAssets.ImageEffects;
public enum Weapon
{
UNARMED = 0,
RELAX = 8
}
[System.Serializable]
public class RPGCharacterControllerFREE : MonoBehaviour
{
#region Variables
//Components
Rigidbody rb;
public Animator animator;
public GameObject target;
private Vector3 targetDashDirection;
public Camera sceneCamera;
//news
public Collider[] availableTargets = new Collider[50];
public List<GameObject> tempTargets = new List<GameObject>();
public int selectedTarget = 0;
public float canTargetArea = 10f;
public float distanceFromTarget = 0f;
//jumping variables
public float gravity = -9.8f;
bool canJump;
bool isJumping = false;
bool isGrounded;
public float jumpSpeed = 12;
public float doublejumpSpeed = 12;
bool doublejumping = true;
bool canDoubleJump = false;
bool isDoubleJumping = false;
bool doublejumped = false;
bool isFalling;
bool startFall;
float fallingVelocity = -1f;
// Used for continuing momentum while in air
public float inAirSpeed = 8f;
float maxVelocity = 2f;
float minVelocity = -2f;
//rolling variables
public float rollSpeed = 8;
bool isRolling = false;
public float rollduration;
//movement variables
bool canMove = true;
public float walkSpeed = 1.35f;
float moveSpeed;
public float runSpeed = 6f;
float rotationSpeed = 40f;
float x;
float z;
float dv;
float dh;
public Vector3 inputVec;
Vector3 newVelocity;
//Weapon and Shield
private Weapon weapon;
int rightWeapon = 0;
int leftWeapon = 0;
//bool isRelax = false;
//isStrafing/action variables
bool canAction = true;
public bool isStrafing = false;
bool isDead = false;
bool isBlocking = false;
public float knockbackMultiplier = 1f;
bool isKnockback;
#endregion
bool oldTriggerHeld = false;
#region Initialization
void Start()
{
//set the animator component
animator = GetComponentInChildren<Animator>();
rb = GetComponent<Rigidbody>();
UpdateAvailableTargets(canTargetArea);
}
#endregion
#region UpdateAndInput
void Update()
{
//make sure there is animator on character
if (animator)
{
if (canMove && !isBlocking && !isDead)
{
CameraRelativeMovement();
}
Rolling();
Jumping();
//if(Input.GetButtonDown("LightHit") && canAction && isGrounded && !isBlocking)
//{
// GetHit();
//}
//if(Input.GetButtonDown("Death") && canAction && isGrounded && !isBlocking)
//{
// if(!isDead)
// {
// StartCoroutine(_Death());
// }
// else
// {
// StartCoroutine(_Revive());
// }
//}
//if(Input.GetButtonDown("AttackL") && canAction && isGrounded && !isBlocking)
//{
// Attack(1);
//}
//if(Input.GetButtonDown("AttackR") && canAction && isGrounded && !isBlocking)
//{
// Attack(2);
//}
//if(Input.GetButtonDown("CastL") && canAction && isGrounded && !isBlocking && !isStrafing)
//{
// AttackKick(1);
//}
//if(Input.GetButtonDown("CastR") && canAction && isGrounded && !isBlocking && !isStrafing)
//{
// AttackKick(2);
//}
//if strafing
if(currentTarget == null)
{
ResetTarget();
isStrafing = false;
animator.SetBool("Strafing", false);
}
float value = Input.GetAxis("PS4_R2");
bool newTriggerHeld = value == 1;
if (!oldTriggerHeld == newTriggerHeld && value > -1) {
Debug.LogWarning("R2 Pressed:" + value + " dis: " + distanceFromTarget);
Camera.main.GetComponent<CameraController>().rotateAround = this.transform.eulerAngles.y - 45f;
//ResetTarget();
UpdateAvailableTargets(canTargetArea);
if (tempTargets.Count > 0)
{
TargetEnemy();
isStrafing = true;
animator.SetBool("Strafing", true);
}
}
oldTriggerHeld = newTriggerHeld;
if (Input.GetButtonDown("PS4_CIRCLE"))
{
isStrafing = false;
animator.SetBool("Strafing", false);
ResetTarget();
}
if (isStrafing)
{
if (distanceFromTarget > 15f)
{
isStrafing = false;
animator.SetBool("Strafing", false);
ResetTarget();
}
else
{
if (Input.GetButtonDown("PS4_R1"))
{
targetDashDirection = transform.right;
StartCoroutine(_Roll(2));
}
if (Input.GetButtonDown("PS4_L1"))
{
targetDashDirection = -transform.right;
StartCoroutine(_Roll(4));
}
}
}
}
else
{
Debug.Log("ERROR: There is no animator for character.");
}
}
#endregion
#region Fixed/Late Updates
void FixedUpdate()
{
CheckForGrounded();
//apply gravity force
rb.AddForce(0, gravity, 0, ForceMode.Acceleration);
AirControl();
//check if character can move
if (canMove && !isBlocking && !isDead)
{
moveSpeed = UpdateMovement();
}
//check if falling
if (rb.velocity.y < fallingVelocity)
{
isFalling = true;
animator.SetInteger("Jumping", 2);
canJump = false;
}
else
{
isFalling = false;
}
if (currentTarget != null)
{
distanceFromTarget = Vector3.Distance(transform.position, currentTarget.transform.position);
}
else
{
distanceFromTarget = 0;
}
}
//get velocity of rigid body and pass the value to the animator to control the animations
void LateUpdate()
{
//Get local velocity of charcter
float velocityXel = transform.InverseTransformDirection(rb.velocity).x;
float velocityZel = transform.InverseTransformDirection(rb.velocity).z;
//Update animator with movement values
animator.SetFloat("Velocity X", velocityXel / runSpeed);
animator.SetFloat("Velocity Z", velocityZel / runSpeed);
//if character is alive and can move, set our animator
if (!isDead && canMove)
{
if (moveSpeed > 0)
{
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
}
}
#endregion
#region UpdateMovement
void CameraRelativeMovement() {
float inputDashVertical = Input.GetAxisRaw("DashVertical");
float inputDashHorizontal = Input.GetAxisRaw("DashHorizontal");
float inputHorizontal = Input.GetAxisRaw("PS4_PAD_LEFT_X");
float inputVertical = Input.GetAxisRaw("PS4_PAD_LEFT_Y");
//converts control input vectors into camera facing vectors
Transform cameraTransform = sceneCamera.transform;
//Forward vector relative to the camera along the x-z plane
Vector3 forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
//Right vector relative to the camera always orthogonal to the forward vector
Vector3 right = new Vector3(forward.z, 0, -forward.x);
//directional inputs
dv = inputDashVertical;
dh = inputDashHorizontal;
if (!isRolling)
{
targetDashDirection = dh * right + dv * -forward;
}
x = inputHorizontal;
z = inputVertical;
inputVec = x * right + z * forward;
}
//rotate character towards direction moved
void RotateTowardsMovementDir()
{
if (inputVec != Vector3.zero && !isStrafing && !isRolling && !isBlocking)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
float UpdateMovement()
{
CameraRelativeMovement();
Vector3 motion = inputVec;
if (isGrounded)
{
//reduce input for diagonal movement
if (motion.magnitude > 1)
{
motion.Normalize();
}
if (canMove && !isBlocking)
{
//set speed by walking / running
if (isStrafing)
{
newVelocity = motion * walkSpeed;
}
else
{
newVelocity = motion * runSpeed;
}
//if rolling use rolling speed and direction
if (isRolling)
{
//force the dash movement to 1
targetDashDirection.Normalize();
newVelocity = rollSpeed * targetDashDirection;
}
}
}
else
{
//if we are falling use momentum
newVelocity = rb.velocity;
}
if (!isStrafing || !canMove)
{
RotateTowardsMovementDir();
}
if (isStrafing && currentTarget != null)
{
//make character point at target
LookAtTarget();
}
newVelocity.y = rb.velocity.y;
rb.velocity = newVelocity;
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region Jumping
//checks if character is within a certain distance from the ground, and markes it IsGrounded
void CheckForGrounded()
{
float distanceToGround;
float threshold = .55f;
RaycastHit hit;
Vector3 offset = new Vector3(0, .4f, 0);
Debug.DrawRay((transform.position + offset), -Vector3.up);
//Debug.Log(rb.velocity.y);
if (Physics.Raycast((transform.position + offset), -Vector3.up, out hit, 100f))
{
distanceToGround = hit.distance;
if (distanceToGround < threshold)
{
if (rb.velocity.y > -1f)
{
isGrounded = true;
canJump = true;
startFall = false;
doublejumped = false;
canDoubleJump = false;
isFalling = false;
if (!isJumping)
{
animator.SetInteger("Jumping", 0);
}
}
}
else
{
isGrounded = false;
}
}
}
void Jumping()
{
if (isGrounded)
{
if (canJump && Input.GetButtonDown("PS4_X"))
{
StartCoroutine(_Jump());
}
}
else
{
canDoubleJump = true;
canJump = false;
if (isFalling)
{
//set the animation back to falling
animator.SetInteger("Jumping", 2);
//prevent from going into land animation while in air
if (!startFall)
{
animator.SetTrigger("JumpTrigger");
startFall = true;
}
}
//if (canDoubleJump && doublejumping && Input.GetButtonDown("Jump") && !doublejumped && isFalling)
//{
// // Apply the current movement to launch velocity
// rb.velocity += doublejumpSpeed * Vector3.up;
// animator.SetInteger("Jumping", 3);
// doublejumped = true;
//}
}
}
IEnumerator _Jump()
{
isJumping = true;
animator.SetInteger("Jumping", 1);
animator.SetTrigger("JumpTrigger");
// Apply the current movement to launch velocity
rb.velocity += jumpSpeed * Vector3.up;
canJump = false;
yield return new WaitForSeconds(.5f);
isJumping = false;
}
void AirControl()
{
if (!isGrounded)
{
CameraRelativeMovement();
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? 0.7f : 1;
rb.AddForce(motion * inAirSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (rb.velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
{
velocityX = 0;
}
rb.AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (rb.velocity.x < minVelocity)
{
velocityX = rb.velocity.x - minVelocity;
if (velocityX > 0)
{
velocityX = 0;
}
rb.AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (rb.velocity.z > maxVelocity)
{
velocityZ = rb.velocity.z - maxVelocity;
if (velocityZ < 0)
{
velocityZ = 0;
}
rb.AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (rb.velocity.z < minVelocity)
{
velocityZ = rb.velocity.z - minVelocity;
if (velocityZ > 0)
{
velocityZ = 0;
}
rb.AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
}
}
#endregion
#region MiscMethods
//0 = No side
//1 = Left
//2 = Right
//3 = Dual
void Attack(int attackSide)
{
if (canAction)
{
if (weapon == Weapon.UNARMED)
{
int maxAttacks = 3;
int attackNumber = 0;
if (attackSide == 1 || attackSide == 3)
{
attackNumber = Random.Range(3, maxAttacks);
}
else if (attackSide == 2)
{
attackNumber = Random.Range(6, maxAttacks + 3);
}
if (isGrounded)
{
if (attackSide != 3)
{
animator.SetTrigger("Attack" + (attackNumber).ToString() + "Trigger");
if (leftWeapon == 12 || leftWeapon == 14 || rightWeapon == 13 || rightWeapon == 15)
{
StartCoroutine(_LockMovementAndAttack(0, .75f));
}
else
{
StartCoroutine(_LockMovementAndAttack(0, .6f));
}
}
else
{
animator.SetTrigger("AttackDual" + (attackNumber).ToString() + "Trigger");
StartCoroutine(_LockMovementAndAttack(0, .75f));
}
}
}
//2 handed weapons
else
{
if (isGrounded)
{
animator.SetTrigger("Attack" + (6).ToString() + "Trigger");
StartCoroutine(_LockMovementAndAttack(0, .85f));
}
}
}
}
void AttackKick(int kickSide)
{
if (isGrounded)
{
if (kickSide == 1)
{
animator.SetTrigger("AttackKick1Trigger");
}
else
{
animator.SetTrigger("AttackKick2Trigger");
}
StartCoroutine(_LockMovementAndAttack(0, .8f));
}
}
//0 = No side
//1 = Left
//2 = Right
//3 = Dual
void CastAttack(int attackSide)
{
if (weapon == Weapon.UNARMED)
{
int maxAttacks = 3;
if (attackSide == 1)
{
int attackNumber = Random.Range(0, maxAttacks);
if (isGrounded)
{
animator.SetTrigger("CastAttack" + (attackNumber + 1).ToString() + "Trigger");
StartCoroutine(_LockMovementAndAttack(0, .8f));
}
}
if (attackSide == 2)
{
int attackNumber = Random.Range(3, maxAttacks + 3);
if (isGrounded)
{
animator.SetTrigger("CastAttack" + (attackNumber + 1).ToString() + "Trigger");
StartCoroutine(_LockMovementAndAttack(0, .8f));
}
}
if (attackSide == 3)
{
int attackNumber = Random.Range(0, maxAttacks);
if (isGrounded)
{
animator.SetTrigger("CastDualAttack" + (attackNumber + 1).ToString() + "Trigger");
StartCoroutine(_LockMovementAndAttack(0, 1f));
}
}
}
}
void GetHit()
{
int hits = 5;
int hitNumber = Random.Range(0, hits);
animator.SetTrigger("GetHit" + (hitNumber + 1).ToString() + "Trigger");
StartCoroutine(_LockMovementAndAttack(.1f, .4f));
//apply directional knockback force
if (hitNumber <= 1)
{
StartCoroutine(_Knockback(-transform.forward, 8, 4));
}
else if (hitNumber == 2)
{
StartCoroutine(_Knockback(transform.forward, 8, 4));
}
else if (hitNumber == 3)
{
StartCoroutine(_Knockback(transform.right, 8, 4));
}
else if (hitNumber == 4)
{
StartCoroutine(_Knockback(-transform.right, 8, 4));
}
}
public void UpdateAvailableTargets(float range)
{
float distance = 0;
tempTargets.Clear();
//availableTargets = GameObject.FindGameObjectsWithTag("Enemy").ToList<GameObject>();
availableTargets = Physics.OverlapSphere(this.transform.position, 15f);
for (int i = 0; i < availableTargets.Length; i++)
{
if (availableTargets[i] != null)
{
if( availableTargets[i].tag == "Enemy")
{
Debug.Log(availableTargets[i].tag);
tempTargets.Add(availableTargets[i].gameObject);
}
}
}
System.Array.Resize(ref availableTargets, 0);
}
public GameObject currentTarget;
public void ResetTarget()
{
selectedTarget = 0;
tempTargets.Clear();
currentTarget = null;
distanceFromTarget = 0;
}
public void TargetEnemy()
{
currentTarget = tempTargets[selectedTarget];
Debug.Log("Eccolo");
selectedTarget += 1;
if (selectedTarget == tempTargets.Count)
{
selectedTarget = 0;
}
}
public void LookAtTarget()
{
if (currentTarget != null)
{
Quaternion targetRotation;
Vector3 targetPos = currentTarget.transform.position;
targetRotation = Quaternion.LookRotation(targetPos - new Vector3(transform.position.x, 0, transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, (rotationSpeed * Time.deltaTime) * rotationSpeed);
}
}
IEnumerator _Knockback(Vector3 knockDirection, int knockBackAmount, int variableAmount)
{
isKnockback = true;
StartCoroutine(_KnockbackForce(knockDirection, knockBackAmount, variableAmount));
yield return new WaitForSeconds(.1f);
isKnockback = false;
}
IEnumerator _KnockbackForce(Vector3 knockDirection, int knockBackAmount, int variableAmount)
{
while(isKnockback)
{
rb.AddForce(knockDirection * ((knockBackAmount + Random.Range(-variableAmount, variableAmount)) * (knockbackMultiplier * 10)), ForceMode.Impulse);
yield return null;
}
}
IEnumerator _Death()
{
animator.SetTrigger("Death1Trigger");
StartCoroutine(_LockMovementAndAttack(.1f, 1.5f));
isDead = true;
animator.SetBool("Moving", false);
inputVec = new Vector3(0, 0, 0);
yield return null;
}
IEnumerator _Revive()
{
animator.SetTrigger("Revive1Trigger");
isDead = false;
yield return null;
}
//Animation Events
void Hit()
{
}
void FootL()
{
}
void FootR()
{
}
void Jump()
{
}
void Land()
{
}
#endregion
#region Rolling
void Rolling()
{
if(!isRolling && isGrounded)
{
if(Input.GetAxis("DashVertical") > .5 || Input.GetAxis("DashVertical") < -.5 || Input.GetAxis("DashHorizontal") > .5 || Input.GetAxis("DashHorizontal") < -.5)
{
StartCoroutine(_DirectionalRoll(Input.GetAxis("DashVertical"), Input.GetAxis("DashHorizontal")));
}
}
}
public IEnumerator _DirectionalRoll(float x, float v)
{
//check which way the dash is pressed relative to the character facing
float angle = Vector3.Angle(targetDashDirection,-transform.forward);
float sign = Mathf.Sign(Vector3.Dot(transform.up,Vector3.Cross(targetDashDirection,transform.forward)));
// angle in [-179,180]
float signed_angle = angle * sign;
//angle in 0-360
float angle360 = (signed_angle + 180) % 360;
//deternime the animation to play based on the angle
if(angle360 > 315 || angle360 < 45)
{
StartCoroutine(_Roll(1));
}
if(angle360 > 45 && angle360 < 135)
{
StartCoroutine(_Roll(2));
}
if(angle360 > 135 && angle360 < 225)
{
StartCoroutine(_Roll(3));
}
if(angle360 > 225 && angle360 < 315)
{
StartCoroutine(_Roll(4));
}
yield return null;
}
IEnumerator _Roll(int rollNumber)
{
if(rollNumber == 1)
{
animator.SetTrigger("RollForwardTrigger");
}
if(rollNumber == 2)
{
animator.SetTrigger("RollRightTrigger");
}
if(rollNumber == 3)
{
animator.SetTrigger("RollBackwardTrigger");
}
if(rollNumber == 4)
{
animator.SetTrigger("RollLeftTrigger");
}
isRolling = true;
yield return new WaitForSeconds(rollduration);
isRolling = false;
}
#endregion
#region _Coroutines
//method to keep character from moveing while attacking, etc
public IEnumerator _LockMovementAndAttack(float delayTime, float lockTime)
{
yield return new WaitForSeconds(delayTime);
canAction = false;
canMove = false;
animator.SetBool("Moving", false);
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
inputVec = new Vector3(0, 0, 0);
animator.applyRootMotion = true;
yield return new WaitForSeconds(lockTime);
canAction = true;
canMove = true;
animator.applyRootMotion = false;
}
#endregion
#region GUI
void OnGUI()
{
// if(!isDead)
// {
// if(canAction && !isRelax)
// {
// if(isGrounded)
// {
// if(!isBlocking)
// {
// if(!isBlocking)
// {
// if(GUI.Button(new Rect(25, 15, 100, 30), "Roll Forward"))
// {
// targetDashDirection = transform.forward;
// StartCoroutine(_Roll(1));
// }
// if(GUI.Button(new Rect(130, 15, 100, 30), "Roll Backward"))
// {
// targetDashDirection = -transform.forward;
// StartCoroutine(_Roll(3));
// }
// if(GUI.Button(new Rect(25, 45, 100, 30), "Roll Left"))
// {
// targetDashDirection = -transform.right;
// StartCoroutine(_Roll(4));
// }
// if(GUI.Button(new Rect(130, 45, 100, 30), "Roll Right"))
// {
// targetDashDirection = transform.right;
// StartCoroutine(_Roll(2));
// }
// //ATTACK LEFT
// if(GUI.Button(new Rect(25, 85, 100, 30), "Attack L"))
// {
// Attack(1);
// }
// //ATTACK RIGHT
// if(GUI.Button(new Rect(130, 85, 100, 30), "Attack R"))
// {
// Attack(2);
// }
// if(weapon == Weapon.UNARMED)
// {
// if(GUI.Button (new Rect (25, 115, 100, 30), "Left Kick"))
// {
// AttackKick (1);
// }
// if(GUI.Button (new Rect (130, 115, 100, 30), "Right Kick"))
// {
// AttackKick (2);
// }
// }
// if(GUI.Button(new Rect(30, 240, 100, 30), "Get Hit"))
// {
// GetHit();
// }
// }
// }
// }
// if(canJump || canDoubleJump)
// {
// if(isGrounded)
// {
// if(GUI.Button(new Rect(25, 165, 100, 30), "Jump"))
// {
// if(canJump && isGrounded)
// {
// StartCoroutine(_Jump());
// }
// }
// }
// else
// {
// if(GUI.Button(new Rect(25, 165, 100, 30), "Double Jump"))
// {
// if(canDoubleJump && !isDoubleJumping)
// {
// StartCoroutine(_Jump());
// }
// }
// }
// }
// if(!isBlocking && isGrounded)
// {
// if(GUI.Button(new Rect(30, 270, 100, 30), "Death"))
// {
// StartCoroutine(_Death());
// }
// }
// }
// }
// if(isDead)
// {
// if(GUI.Button(new Rect(30, 270, 100, 30), "Revive"))
// {
// StartCoroutine(_Revive());
// }
//}
}
#endregion
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics);
/// <summary>
/// Synthesized expression evaluation method.
/// </summary>
internal sealed class EEMethodSymbol : MethodSymbol
{
// We only create a single EE method (per EE type) that represents an arbitrary expression,
// whose lowering may produce synthesized members (lambdas, dynamic sites, etc).
// We may thus assume that the method ordinal is always 0.
//
// Consider making the implementation more flexible in order to avoid this assumption.
// In future we might need to compile multiple expression and then we'll need to assign
// a unique method ordinal to each of them to avoid duplicate synthesized member names.
private const int _methodOrdinal = 0;
internal readonly TypeMap TypeMap;
internal readonly MethodSymbol SubstitutedSourceMethod;
internal readonly ImmutableArray<LocalSymbol> Locals;
internal readonly ImmutableArray<LocalSymbol> LocalsForBinding;
private readonly EENamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<Location> _locations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly ParameterSymbol _thisParameter;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
/// <summary>
/// Invoked at most once to generate the method body.
/// (If the compilation has no errors, it will be invoked
/// exactly once, otherwise it may be skipped.)
/// </summary>
private readonly GenerateMethodBody _generateMethodBody;
private TypeSymbol _lazyReturnType;
// NOTE: This is only used for asserts, so it could be conditional on DEBUG.
private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters;
internal EEMethodSymbol(
EENamedTypeSymbol container,
string name,
Location location,
MethodSymbol sourceMethod,
ImmutableArray<LocalSymbol> sourceLocals,
ImmutableArray<LocalSymbol> sourceLocalsForBinding,
ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables,
GenerateMethodBody generateMethodBody)
{
Debug.Assert(sourceMethod.IsDefinition);
Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition);
Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod));
_container = container;
_name = name;
_locations = ImmutableArray.Create(location);
// What we want is to map all original type parameters to the corresponding new type parameters
// (since the old ones have the wrong owners). Unfortunately, we have a circular dependency:
// 1) Each new type parameter requires the entire map in order to be able to construct its constraint list.
// 2) The map cannot be constructed until all new type parameters exist.
// Our solution is to pass each new type parameter a lazy reference to the type map. We then
// initialize the map as soon as the new type parameters are available - and before they are
// handed out - so that there is never a period where they can require the type map and find
// it uninitialized.
var sourceMethodTypeParameters = sourceMethod.TypeParameters;
var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters);
var getTypeMap = new Func<TypeMap>(() => this.TypeMap);
_typeParameters = sourceMethodTypeParameters.SelectAsArray(
(tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap),
(object)null);
_allTypeParameters = container.TypeParameters.Concat(_typeParameters);
this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters);
EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters);
var substitutedSourceType = container.SubstitutedSourceType;
this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType);
if (sourceMethod.Arity > 0)
{
this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>());
}
TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters);
// Create a map from original parameter to target parameter.
var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance();
var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter;
var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null;
if (substitutedSourceHasThisParameter)
{
_thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter);
Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType);
parameterBuilder.Add(_thisParameter);
}
var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0);
foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters)
{
var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset;
Debug.Assert(ordinal == parameterBuilder.Count);
var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter);
parameterBuilder.Add(parameter);
}
_parameters = parameterBuilder.ToImmutableAndFree();
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocals)
{
var local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
localsBuilder.Add(local);
}
this.Locals = localsBuilder.ToImmutableAndFree();
localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocalsForBinding)
{
LocalSymbol local;
if (!localsMap.TryGetValue(sourceLocal, out local))
{
local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
}
localsBuilder.Add(local);
}
this.LocalsForBinding = localsBuilder.ToImmutableAndFree();
// Create a map from variable name to display class field.
var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance();
foreach (var pair in sourceDisplayClassVariables)
{
var variable = pair.Value;
var displayClassInstanceFromLocal = variable.DisplayClassInstance as DisplayClassInstanceFromLocal;
var displayClassInstance = (displayClassInstanceFromLocal == null) ?
(DisplayClassInstance)new DisplayClassInstanceFromThis(_parameters[0]) :
new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[displayClassInstanceFromLocal.Local]);
variable = variable.SubstituteFields(displayClassInstance, this.TypeMap);
displayClassVariables.Add(pair.Key, variable);
}
_displayClassVariables = displayClassVariables.ToImmutableDictionary();
displayClassVariables.Free();
localsMap.Free();
_generateMethodBody = generateMethodBody;
}
private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter)
{
return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers);
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get { return false; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override bool TryGetThisParameter(out ParameterSymbol thisParameter)
{
thisParameter = null;
return true;
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsVararg
{
get { return this.SubstitutedSourceMethod.IsVararg; }
}
public override bool ReturnsVoid
{
get { return this.ReturnType.SpecialType == SpecialType.System_Void; }
}
public override bool IsAsync
{
get { return false; }
}
public override TypeSymbol ReturnType
{
get
{
if (_lazyReturnType == null)
{
throw new InvalidOperationException();
}
return _lazyReturnType;
}
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
var cc = Cci.CallingConvention.Default;
if (this.IsVararg)
{
cc |= Cci.CallingConvention.ExtraArguments;
}
if (this.IsGenericMethod)
{
cc |= Cci.CallingConvention.Generic;
}
return cc;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
var body = _generateMethodBody(this, diagnostics);
var compilation = compilationState.Compilation;
_lazyReturnType = CalculateReturnType(compilation, body);
// Can't do this until the return type has been computed.
TypeParameterChecker.Check(this, _allTypeParameters);
if (diagnostics.HasAnyErrors())
{
return;
}
DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this);
if (diagnostics.HasAnyErrors())
{
return;
}
// Check for use-site diagnostics (e.g. missing types in the signature).
DiagnosticInfo useSiteDiagnosticInfo = null;
this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo);
if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]);
return;
}
var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance();
try
{
// Rewrite local declaration statement.
body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body);
// Verify local declaration names.
foreach (var local in declaredLocals)
{
Debug.Assert(local.Locations.Length > 0);
var name = local.Name;
if (name.StartsWith("$", StringComparison.Ordinal))
{
diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]);
return;
}
}
// Rewrite references to placeholder "locals".
body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body);
}
finally
{
declaredLocals.Free();
}
var syntax = body.Syntax;
var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance();
statementsBuilder.Add(body);
// Insert an implicit return statement if necessary.
if (body.Kind != BoundKind.ReturnStatement)
{
statementsBuilder.Add(new BoundReturnStatement(syntax, expressionOpt: null));
}
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsSet = PooledHashSet<LocalSymbol>.GetInstance();
foreach (var local in this.LocalsForBinding)
{
Debug.Assert(!localsSet.Contains(local));
localsBuilder.Add(local);
localsSet.Add(local);
}
foreach (var local in this.Locals)
{
if (!localsSet.Contains(local))
{
localsBuilder.Add(local);
}
}
localsSet.Free();
body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true };
Debug.Assert(!diagnostics.HasAnyErrors());
Debug.Assert(!body.HasErrors);
bool sawLambdas;
bool sawAwaitInExceptionHandler;
body = LocalRewriter.Rewrite(
compilation: this.DeclaringCompilation,
method: this,
methodOrdinal: _methodOrdinal,
containingType: _container,
statement: body,
compilationState: compilationState,
previousSubmissionFields: null,
allowOmissionOfConditionalCalls: false,
diagnostics: diagnostics,
sawLambdas: out sawLambdas,
sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler);
Debug.Assert(!sawAwaitInExceptionHandler);
if (body.HasErrors)
{
return;
}
// Variables may have been captured by lambdas in the original method
// or in the expression, and we need to preserve the existing values of
// those variables in the expression. This requires rewriting the variables
// in the expression based on the closure classes from both the original
// method and the expression, and generating a preamble that copies
// values into the expression closure classes.
//
// Consider the original method:
// static void M()
// {
// int x, y, z;
// ...
// F(() => x + y);
// }
// and the expression in the EE: "F(() => x + z)".
//
// The expression is first rewritten using the closure class and local <1>
// from the original method: F(() => <1>.x + z)
// Then lambda rewriting introduces a new closure class that includes
// the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z)
// And a preamble is added to initialize the fields of <2>:
// <2> = new <>c__DisplayClass0();
// <2>.<1> = <1>;
// <2>.z = z;
// Rewrite "this" and "base" references to parameter in this method.
// Rewrite variables within body to reference existing display classes.
body = (BoundStatement)CapturedVariableRewriter.Rewrite(
this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0],
compilation.Conversions,
_displayClassVariables,
body,
diagnostics);
if (body.HasErrors)
{
Debug.Assert(false, "Please add a test case capturing whatever caused this assert.");
return;
}
if (diagnostics.HasAnyErrors())
{
return;
}
if (sawLambdas)
{
var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();
var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
body = LambdaRewriter.Rewrite(
loweredBody: body,
thisType: this.SubstitutedSourceMethod.ContainingType,
thisParameter: _thisParameter,
method: this,
methodOrdinal: _methodOrdinal,
closureDebugInfoBuilder: closureDebugInfoBuilder,
lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
slotAllocatorOpt: null,
compilationState: compilationState,
diagnostics: diagnostics,
assignLocals: true);
// we don't need this information:
closureDebugInfoBuilder.Free();
lambdaDebugInfoBuilder.Free();
}
// Insert locals from the original method,
// followed by any new locals.
var block = (BoundBlock)body;
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in this.Locals)
{
Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count));
localBuilder.Add(local);
}
foreach (var local in block.Locals)
{
var oldLocal = local as EELocalSymbol;
if (oldLocal != null)
{
Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal);
continue;
}
localBuilder.Add(local);
}
body = block.Update(localBuilder.ToImmutableAndFree(), block.Statements);
TypeParameterChecker.Check(body, _allTypeParameters);
compilationState.AddSynthesizedMethod(this, body);
}
private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt)
{
if (bodyOpt == null)
{
// If the method doesn't do anything, then it doesn't return anything.
return compilation.GetSpecialType(SpecialType.System_Void);
}
switch (bodyOpt.Kind)
{
case BoundKind.ReturnStatement:
return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type;
case BoundKind.ExpressionStatement:
case BoundKind.LocalDeclaration:
case BoundKind.MultipleLocalDeclarations:
return compilation.GetSpecialType(SpecialType.System_Void);
default:
throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind);
}
}
internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedReturnTypeAttributes(ref attributes);
if (this.ReturnType.ContainsDynamic())
{
var compilation = this.DeclaringCompilation;
if ((object)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor) != null)
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(this.ReturnType, this.ReturnTypeCustomModifiers.Length));
}
}
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
return localPosition;
}
}
}
| |
using System;
using Foundation;
using HomeKit;
using UIKit;
namespace HomeKitCatalog
{
// A view controller which facilitates the creation of timer triggers.
public partial class TimerTriggerViewController : TriggerViewController
{
static readonly NSString recurrenceCell = (NSString)"RecurrenceCell";
static readonly string[] RecurrenceTitles = {
"Every Hour",
"Every Day",
"Every Week",
};
[Outlet ("datePicker")]
UIDatePicker datePicker { get; set; }
// Sets the stored fireDate to the new value.
// HomeKit only accepts dates aligned with minute boundaries,
// so we use NSDateComponents to only get the appropriate pieces of information from that date.
// Eventually we will end up with a date following this format: "MM/dd/yyyy hh:mm"
HMTimerTrigger TimerTrigger {
get {
return Trigger as HMTimerTrigger;
}
}
TimerTriggerCreator TimerTriggerCreator {
get {
return TriggerCreator as TimerTriggerCreator;
}
}
#region ctors
public TimerTriggerViewController (IntPtr handle)
: base (handle)
{
}
[Export ("initWithCoder:")]
public TimerTriggerViewController (NSCoder coder)
: base (coder)
{
}
#endregion
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
TableView.RowHeight = UITableView.AutomaticDimension;
TableView.EstimatedRowHeight = 44;
TriggerCreator = new TimerTriggerCreator (Trigger, Home);
datePicker.Date = TimerTriggerCreator.FireDate;
TableView.RegisterClassForCellReuse (typeof(UITableViewCell), recurrenceCell);
}
// Reset our saved fire date to the date in the picker.
[Export ("didChangeDate:")]
void didChangeDate (UIDatePicker picker)
{
TimerTriggerCreator.RawFireDate = picker.Date;
}
#region Table View Methods
// returns: The number of rows in the Recurrence section; defaults to the super implementation for other sections
public override nint RowsInSection (UITableView tableView, nint section)
{
switch (SectionForIndex ((int)section)) {
case TriggerTableViewSection.Recurrence:
return RecurrenceTitles.Length;
case TriggerTableViewSection.Name:
case TriggerTableViewSection.Enabled:
case TriggerTableViewSection.ActionSets:
case TriggerTableViewSection.DateAndTime:
case TriggerTableViewSection.Conditions:
case TriggerTableViewSection.Location:
case TriggerTableViewSection.Region:
case TriggerTableViewSection.Characteristics:
return base.RowsInSection (tableView, section);
default:
throw new InvalidOperationException ("Unexpected `TriggerTableViewSection` value.");
}
}
// Generates a recurrence cell. Defaults to the super implementation for other sections
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
switch (SectionForIndex (indexPath.Section)) {
case TriggerTableViewSection.Recurrence:
return GetRecurrenceCell (tableView, indexPath);
case TriggerTableViewSection.Name:
case TriggerTableViewSection.Enabled:
case TriggerTableViewSection.ActionSets:
case TriggerTableViewSection.DateAndTime:
case TriggerTableViewSection.Conditions:
case TriggerTableViewSection.Location:
case TriggerTableViewSection.Region:
case TriggerTableViewSection.Characteristics:
return base.GetCell (tableView, indexPath);
default:
throw new InvalidOperationException ("Unexpected `TriggerTableViewSection` value.");
}
}
// Creates a cell that represents a recurrence type.
UITableViewCell GetRecurrenceCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell (recurrenceCell, indexPath);
var title = RecurrenceTitles [indexPath.Row];
cell.TextLabel.Text = title;
// The current preferred recurrence style should have a check mark.
cell.Accessory = indexPath.Row == TimerTriggerCreator.SelectedRecurrenceIndex
? UITableViewCellAccessory.Checkmark
: UITableViewCellAccessory.None;
return cell;
}
// Tell the tableView to automatically size the custom rows, while using the superclass's
// static sizing for the static cells.
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
switch (SectionForIndex (indexPath.Section)) {
case TriggerTableViewSection.Recurrence:
return UITableView.AutomaticDimension;
case TriggerTableViewSection.Name:
case TriggerTableViewSection.Enabled:
case TriggerTableViewSection.ActionSets:
case TriggerTableViewSection.DateAndTime:
case TriggerTableViewSection.Conditions:
case TriggerTableViewSection.Location:
case TriggerTableViewSection.Region:
case TriggerTableViewSection.Characteristics:
return base.GetHeightForRow (tableView, indexPath);
default:
throw new InvalidOperationException ("Unexpected `TriggerTableViewSection` value.");
}
}
// Handles recurrence cell selection. Defaults to the super implementation for other sections
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
tableView.DeselectRow (indexPath, true);
switch (SectionForIndex (indexPath.Section)) {
case TriggerTableViewSection.Recurrence:
SelectRecurrenceComponent (tableView, indexPath);
break;
case TriggerTableViewSection.Name:
case TriggerTableViewSection.Enabled:
case TriggerTableViewSection.ActionSets:
case TriggerTableViewSection.DateAndTime:
case TriggerTableViewSection.Conditions:
case TriggerTableViewSection.Location:
case TriggerTableViewSection.Region:
case TriggerTableViewSection.Characteristics:
base.RowSelected (tableView, indexPath);
break;
default:
throw new InvalidOperationException ("Unexpected `TriggerTableViewSection` value.");
}
}
// Handles selection of a recurrence cell.
// If the newly selected recurrence component is the previously selected
// recurrence component, reset the current selected component to `-1` and deselect that row.
void SelectRecurrenceComponent (UITableView tableView, NSIndexPath indexPath)
{
bool isPreviouslySelected = indexPath.Row == TimerTriggerCreator.SelectedRecurrenceIndex;
TimerTriggerCreator.SelectedRecurrenceIndex = isPreviouslySelected ? -1 : indexPath.Row;
tableView.ReloadSections (NSIndexSet.FromIndex (indexPath.Section), UITableViewRowAnimation.Automatic);
}
protected override TriggerTableViewSection SectionForIndex (int index)
{
switch (index) {
case 0:
return TriggerTableViewSection.Name;
case 1:
return TriggerTableViewSection.Enabled;
case 2:
return TriggerTableViewSection.DateAndTime;
case 3:
return TriggerTableViewSection.Recurrence;
case 4:
return TriggerTableViewSection.ActionSets;
default:
return TriggerTableViewSection.None;
}
}
#endregion
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.Threading;
namespace SharpDX.DirectInput
{
public partial class Device
{
private DeviceProperties _properties;
/// <summary>
/// Initializes a new instance of the <see cref="Device"/> class based on a given globally unique identifier (Guid).
/// </summary>
/// <param name="directInput">The direct input.</param>
/// <param name="deviceGuid">The device GUID.</param>
protected Device(DirectInput directInput, Guid deviceGuid)
{
IntPtr temp;
directInput.CreateDevice(deviceGuid, out temp, null);
NativePointer = temp;
}
/// <summary>
/// Gets the device properties.
/// </summary>
/// <value>The device properties.</value>
public DeviceProperties Properties
{
get
{
if (_properties == null)
_properties = new DeviceProperties(this);
return _properties;
}
}
/// <summary>
/// Sends a hardware-specific command to the force-feedback driver.
/// </summary>
/// <param name="command">Driver-specific command number. Consult the driver documentation for a list of valid commands. </param>
/// <param name="inData">Buffer containing the data required to perform the operation. </param>
/// <param name="outData">Buffer in which the operation's output data is returned. </param>
/// <returns>Number of bytes written to the output buffer</returns>
/// <remarks>
/// Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the <see cref="DeviceInstance"/> structure against the value the application is expecting.
/// </remarks>
public int Escape(int command, byte[] inData, byte[] outData)
{
var effectEscape = new EffectEscape();
unsafe
{
fixed (void* pInData = &inData[0])
fixed (void* pOutData = &outData[0])
{
effectEscape.Size = sizeof (EffectEscape);
effectEscape.Command = command;
effectEscape.InBufferPointer = (IntPtr) pInData;
effectEscape.InBufferSize = inData.Length;
effectEscape.OutBufferPointer = (IntPtr) pOutData;
effectEscape.OutBufferSize = outData.Length;
Escape(ref effectEscape);
return effectEscape.OutBufferSize;
}
}
}
/// <summary>
/// Gets information about a device image for use in a configuration property sheet.
/// </summary>
/// <returns>A structure that receives information about the device image.</returns>
public DeviceImageHeader GetDeviceImages()
{
var imageHeader = new DeviceImageHeader();
GetImageInfo(imageHeader);
if (imageHeader.BufferUsed > 0)
{
unsafe
{
imageHeader.BufferSize = imageHeader.BufferUsed;
var pImages = stackalloc DeviceImage.__Native[imageHeader.BufferSize/sizeof (DeviceImage.__Native)];
imageHeader.ImageInfoArrayPointer = (IntPtr)pImages;
}
GetImageInfo(imageHeader);
}
return imageHeader;
}
/// <summary>
/// Gets all effects.
/// </summary>
/// <returns>A collection of <see cref="EffectInfo"/></returns>
public IList<EffectInfo> GetEffects()
{
return GetEffects(EffectType.All);
}
/// <summary>
/// Gets the effects for a particular <see cref="EffectType"/>.
/// </summary>
/// <param name="effectType">Effect type.</param>
/// <returns>A collection of <see cref="EffectInfo"/></returns>
public IList<EffectInfo> GetEffects(EffectType effectType)
{
var enumEffectsCallback = new EnumEffectsCallback();
EnumEffects(enumEffectsCallback.NativePointer, IntPtr.Zero, effectType);
return enumEffectsCallback.EffectInfos;
}
/// <summary>
/// Gets the effects stored in a RIFF Force Feedback file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>A collection of <see cref="EffectFile"/></returns>
public IList<EffectFile> GetEffectsInFile(string fileName)
{
return GetEffectsInFile(fileName, EffectFileFlags.None);
}
/// <summary>
/// Gets the effects stored in a RIFF Force Feedback file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="effectFileFlags">Flags used to filter effects.</param>
/// <returns>A collection of <see cref="EffectFile"/></returns>
public IList<EffectFile> GetEffectsInFile(string fileName, EffectFileFlags effectFileFlags)
{
var enumEffectsInFileCallback = new EnumEffectsInFileCallback();
EnumEffectsInFile(fileName, enumEffectsInFileCallback.NativePointer, IntPtr.Zero, effectFileFlags);
return enumEffectsInFileCallback.EffectsInFile;
}
/// <summary>
/// Gets information about a device object, such as a button or axis.
/// </summary>
/// <param name="objectId">The object type/instance identifier. This identifier is returned in the <see cref="DeviceObjectInstance.ObjectId"/> member of the <see cref="DeviceObjectInstance"/> structure returned from a previous call to the <see cref="GetObjects()"/> method.</param>
/// <returns>A <see cref="DeviceObjectInstance"/> information</returns>
public DeviceObjectInstance GetObjectInfoById(DeviceObjectId objectId)
{
return GetObjectInfo((int)objectId, PropertyHowType.Byid);
}
/// <summary>
/// Gets information about a device object, such as a button or axis.
/// </summary>
/// <param name="usageCode">the HID Usage Page and Usage values.</param>
/// <returns>A <see cref="DeviceObjectInstance"/> information</returns>
public DeviceObjectInstance GetObjectInfoByUsage(int usageCode)
{
return GetObjectInfo(usageCode, PropertyHowType.Byusage);
}
/// <summary>
/// Gets the properties about a device object, such as a button or axis.
/// </summary>
/// <param name="objectId">The object type/instance identifier. This identifier is returned in the <see cref="DeviceObjectInstance.Type"/> member of the <see cref="DeviceObjectInstance"/> structure returned from a previous call to the <see cref="GetObjects()"/> method.</param>
/// <returns>an ObjectProperties</returns>
public ObjectProperties GetObjectPropertiesById(DeviceObjectId objectId)
{
return new ObjectProperties(this, (int)objectId, PropertyHowType.Byid);
}
/// <summary>
/// Gets the properties about a device object, such as a button or axis.
/// </summary>
/// <param name="usageCode">the HID Usage Page and Usage values.</param>
/// <returns>an ObjectProperties</returns>
public ObjectProperties GetObjectPropertiesByUsage(int usageCode)
{
return new ObjectProperties(this, usageCode, PropertyHowType.Byusage);
}
/// <summary>
/// Retrieves a collection of objects on the device.
/// </summary>
/// <returns>A collection of all device objects on the device.</returns>
public IList<DeviceObjectInstance> GetObjects()
{
return GetObjects(DeviceObjectTypeFlags.All);
}
/// <summary>
/// Retrieves a collection of objects on the device.
/// </summary>
/// <param name="deviceObjectTypeFlag">A filter for the returned device objects collection.</param>
/// <returns>A collection of device objects matching the specified filter.</returns>
public IList<DeviceObjectInstance> GetObjects(DeviceObjectTypeFlags deviceObjectTypeFlag)
{
var enumEffectsInFileCallback = new EnumObjectsCallback();
EnumObjects(enumEffectsInFileCallback.NativePointer, IntPtr.Zero, (int)deviceObjectTypeFlag);
return enumEffectsInFileCallback.Objects;
}
/// <summary>
/// Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.
/// </summary>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void RunControlPanel()
{
RunControlPanel(IntPtr.Zero, 0);
}
/// <summary>
/// Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.
/// </summary>
/// <param name="parentHwnd">The parent control.</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void RunControlPanel(IntPtr parentHwnd)
{
RunControlPanel(parentHwnd, 0);
}
// Disabled as it seems to be not used anymore
///// <summary>
///// Sends data to a device that accepts output. Applications should not use this method. Force Feedback is the recommended way to send data to a device. If you want to send other data to a device, such as changing LED or internal device states, the HID application programming interface (API) is the recommended way.
///// </summary>
///// <param name="data">An array of object data.</param>
///// <param name="overlay">if set to <c>true</c> the device data sent is overlaid on the previously sent device data..</param>
///// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
//public Result SendData(ObjectData[] data, bool overlay)
//{
// unsafe
// {
// int count = data==null?0:data.Length;
// return SendDeviceData(sizeof (ObjectData), data, ref count, overlay ? 1 : 0);
// }
//}
/// <summary>
/// Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.
/// </summary>
/// <param name="eventHandle">Handle to the event that is to be set when the device state changes. DirectInput uses the Microsoft Win32 SetEvent function on the handle when the state of the device changes. If the eventHandle parameter is null, notification is disabled.</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void SetNotification(WaitHandle eventHandle)
{
Microsoft.Win32.SafeHandles.SafeWaitHandle safeHandle;
#if NET45 || BEFORE_NET45
safeHandle = eventHandle?.SafeWaitHandle;
#else
safeHandle = eventHandle?.GetSafeWaitHandle();
#endif
SetEventNotification(safeHandle?.DangerousGetHandle() ?? IntPtr.Zero);
}
/// <summary>
/// Writes the effects to a file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="effects">The effects.</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void WriteEffectsToFile(string fileName, EffectFile[] effects)
{
WriteEffectsToFile(fileName, effects, false);
}
/// <summary>
/// Writes the effects to file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="effects">The effects.</param>
/// <param name="includeNonstandardEffects">if set to <c>true</c> [include nonstandard effects].</param>
/// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
public void WriteEffectsToFile(string fileName, EffectFile[] effects, bool includeNonstandardEffects)
{
WriteEffectToFile(fileName, effects.Length, effects, (int)(includeNonstandardEffects?EffectFileFlags.IncludeNonStandard:0));
}
/// <summary>
/// Gets the created effects.
/// </summary>
/// <value>The created effects.</value>
public IList<Effect> CreatedEffects
{
get
{
var enumCreatedEffectsCallback = new EnumCreatedEffectsCallback();
EnumCreatedEffectObjects(enumCreatedEffectsCallback.NativePointer, IntPtr.Zero, 0);
return enumCreatedEffectsCallback.Effects;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CloudServiceManager.cs" company="Google">
//
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal.CrossPlatform
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using GoogleARCore.CrossPlatform;
using UnityEngine;
internal class CloudServiceManager
{
private static CloudServiceManager s_Instance;
private List<CloudAnchorRequest> m_CloudAnchorRequests = new List<CloudAnchorRequest>();
public static CloudServiceManager Instance
{
get
{
if (s_Instance == null)
{
s_Instance = new CloudServiceManager();
LifecycleManager.Instance.EarlyUpdate += s_Instance._OnEarlyUpdate;
}
return s_Instance;
}
}
public GoogleARCore.AsyncTask<CloudAnchorResult> CreateCloudAnchor(
GoogleARCore.Anchor anchor)
{
Action<CloudAnchorResult> onComplete;
GoogleARCore.AsyncTask<CloudAnchorResult> task;
if (!_CreateCloudAnchorResultAsyncTask(out onComplete, out task))
{
return task;
}
_CreateCloudAnchor(onComplete, anchor.m_NativeHandle);
return task;
}
public GoogleARCore.AsyncTask<CloudAnchorResult> CreateCloudAnchor(UnityEngine.Pose pose)
{
Action<CloudAnchorResult> onComplete;
GoogleARCore.AsyncTask<CloudAnchorResult> task;
if (!_CreateCloudAnchorResultAsyncTask(out onComplete, out task))
{
return task;
}
// Create an native Pose and Anchor.
var poseHandle = LifecycleManager.Instance.NativeSession.PoseApi.Create(pose);
IntPtr arkitAnchorHandle = IntPtr.Zero;
ExternApi.ARKitAnchor_create(poseHandle, ref arkitAnchorHandle);
_CreateCloudAnchor(onComplete, arkitAnchorHandle);
// Clean up handles for the Pose and ARKitAnchor.
LifecycleManager.Instance.NativeSession.PoseApi.Destroy(poseHandle);
ExternApi.ARKitAnchor_release(arkitAnchorHandle);
return task;
}
public GoogleARCore.AsyncTask<CloudAnchorResult> ResolveCloudAnchor(String cloudAnchorId)
{
Action<CloudAnchorResult> onComplete;
GoogleARCore.AsyncTask<CloudAnchorResult> task;
if (!_CreateCloudAnchorResultAsyncTask(out onComplete, out task))
{
return task;
}
IntPtr cloudAnchorHandle = IntPtr.Zero;
var status = LifecycleManager.Instance.NativeSession.SessionApi
.ResolveCloudAnchor(cloudAnchorId, out cloudAnchorHandle);
if (status != ApiArStatus.Success)
{
onComplete(new CloudAnchorResult()
{
Response = status.ToCloudServiceResponse(),
Anchor = null,
});
return task;
}
_CreateAndTrackCloudAnchorRequest(cloudAnchorHandle, onComplete, cloudAnchorId);
return task;
}
/// <summary>
/// Helper for creating and initializing the Action and AsyncTask for CloudAnchorResult.
/// </summary>
/// <param name="onComplete">The on complete Action initialized from the AsyncTask.
/// This will always contain a valid task even when function returns false.</param>
/// <param name="task">The created task.
/// This will always contain a valid task even when function returns false.</param>
/// <returns>Returns true if cloud anchor creation should continue. Returns false if cloud
/// creation should abort.</returns>
protected internal bool _CreateCloudAnchorResultAsyncTask(
out Action<CloudAnchorResult> onComplete,
out GoogleARCore.AsyncTask<CloudAnchorResult> task)
{
// Action<CloudAnchorResult> onComplete;
task = new GoogleARCore.AsyncTask<CloudAnchorResult>(out onComplete);
if (LifecycleManager.Instance.NativeSession == null)
{
onComplete(new CloudAnchorResult()
{
Response = CloudServiceResponse.ErrorNotSupportedByConfiguration,
Anchor = null,
});
return false;
}
return true;
}
/// <summary>
/// Creates the and track cloud anchor request.
/// </summary>
/// <param name="cloudAnchorHandle">Cloud anchor handle.</param>
/// <param name="onComplete">The on complete Action that was created for the
/// AsyncTask<CloudAnchorResult>.</param>
protected internal void _CreateAndTrackCloudAnchorRequest(IntPtr cloudAnchorHandle,
Action<CloudAnchorResult> onComplete, String cloudAnchorId = null)
{
if (LifecycleManager.Instance.NativeSession == null || cloudAnchorHandle == IntPtr.Zero)
{
Debug.LogError("Cannot create cloud anchor request when NativeSession is null or " +
"cloud anchor handle is IntPtr.Zero.");
onComplete(new CloudAnchorResult()
{
Response = CloudServiceResponse.ErrorInternal,
Anchor = null,
});
return;
}
var request = new CloudAnchorRequest()
{
IsComplete = false,
NativeSession = LifecycleManager.Instance.NativeSession,
CloudAnchorId = cloudAnchorId,
AnchorHandle = cloudAnchorHandle,
OnTaskComplete = onComplete,
};
_UpdateCloudAnchorRequest(request, true);
}
/// <summary>
/// Helper for creating a cloud anchor for the given anchor handle.
/// </summary>
/// <param name="onComplete">The on complete Action that was created for the
/// AsyncTask<CloudAnchorResult>.</param>
/// <param name="anchorNativeHandle">The native handle for the anchor.</param>
protected internal void _CreateCloudAnchor(Action<CloudAnchorResult> onComplete,
IntPtr anchorNativeHandle)
{
IntPtr cloudAnchorHandle = IntPtr.Zero;
var status = LifecycleManager.Instance.NativeSession.SessionApi
.CreateCloudAnchor(anchorNativeHandle, out cloudAnchorHandle);
if (status != ApiArStatus.Success)
{
onComplete(new CloudAnchorResult()
{
Response = status.ToCloudServiceResponse(),
Anchor = null,
});
return;
}
_CreateAndTrackCloudAnchorRequest(cloudAnchorHandle, onComplete);
return;
}
protected internal void _CancelCloudAnchorRequest(String cloudAnchorId)
{
bool cancelledCloudAnchorRequest = false;
foreach (var request in m_CloudAnchorRequests)
{
if (request.CloudAnchorId == null || !request.CloudAnchorId.Equals(cloudAnchorId))
{
continue;
}
request.NativeSession.AnchorApi.Detach(request.AnchorHandle);
request.NativeSession.AnchorApi.Release(request.AnchorHandle);
var result = new CloudAnchorResult()
{
// TODO (b/128930901): Change to "ErrorRequestCancelled" for API promotion.
Response = CloudServiceResponse.ErrorCloudIdNotFound,
Anchor = null,
};
request.OnTaskComplete(result);
request.IsComplete = true;
cancelledCloudAnchorRequest = true;
}
m_CloudAnchorRequests.RemoveAll(x => x.IsComplete);
if (!cancelledCloudAnchorRequest)
{
Debug.LogWarning("Didn't find pending operation for cloudAnchorId: " +
cloudAnchorId);
}
}
private void _OnEarlyUpdate()
{
foreach (var request in m_CloudAnchorRequests)
{
_UpdateCloudAnchorRequest(request);
}
m_CloudAnchorRequests.RemoveAll(x => x.IsComplete);
}
private void _UpdateCloudAnchorRequest(
CloudAnchorRequest request, bool isNewRequest = false)
{
var cloudState =
request.NativeSession.AnchorApi.GetCloudAnchorState(request.AnchorHandle);
if (cloudState == ApiCloudAnchorState.Success)
{
XPAnchor xpAnchor = null;
CloudServiceResponse response = CloudServiceResponse.Success;
try
{
xpAnchor = XPAnchor.Factory(request.NativeSession, request.AnchorHandle);
}
catch (Exception e)
{
Debug.LogError("Failed to create XP Anchor: " + e.Message);
response = CloudServiceResponse.ErrorInternal;
}
var result = new CloudAnchorResult()
{
Response = response,
Anchor = xpAnchor,
};
request.OnTaskComplete(result);
request.IsComplete = true;
}
else if (cloudState != ApiCloudAnchorState.TaskInProgress)
{
request.NativeSession.AnchorApi.Detach(request.AnchorHandle);
request.NativeSession.AnchorApi.Release(request.AnchorHandle);
var result = new CloudAnchorResult()
{
Response = cloudState.ToCloudServiceResponse(),
Anchor = null
};
request.OnTaskComplete(result);
request.IsComplete = true;
}
else if (isNewRequest)
{
m_CloudAnchorRequests.Add(request);
}
}
private struct ExternApi
{
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ARKitAnchor_create(
IntPtr poseHandle, ref IntPtr arkitAnchorHandle);
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ARKitAnchor_release(IntPtr arkitAnchorHandle);
}
private class CloudAnchorRequest
{
public bool IsComplete;
public NativeSession NativeSession;
public String CloudAnchorId;
public IntPtr AnchorHandle;
public Action<CloudAnchorResult> OnTaskComplete;
}
}
}
| |
/*
* 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.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using System.Reflection;
using System.Text;
using System.Data;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLAuthenticationData : IAuthenticationData
{
private string m_Realm;
private List<string> m_ColumnNames = null;
private int m_LastExpire = 0;
private string m_ConnectionString;
private PGSQLManager m_database;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public PGSQLAuthenticationData(string connectionString, string realm)
{
m_Realm = realm;
m_ConnectionString = connectionString;
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "AuthStore");
m_database = new PGSQLManager(m_ConnectionString);
m.Update();
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
string sql = string.Format("select * from {0} where uuid = :principalID", m_Realm);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID));
conn.Open();
using (NpgsqlDataReader result = cmd.ExecuteReader())
{
if (result.Read())
{
ret.PrincipalID = principalID;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID"||s == "uuid")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
}
}
return null;
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
if (data.Data.ContainsKey("uuid"))
data.Data.Remove("uuid");
/*
Dictionary<string, object> oAuth = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> oDado in data.Data)
{
if (oDado.Key != oDado.Key.ToLower())
{
oAuth.Add(oDado.Key.ToLower(), oDado.Value);
}
}
foreach (KeyValuePair<string, object> oDado in data.Data)
{
if (!oAuth.ContainsKey(oDado.Key.ToLower())) {
oAuth.Add(oDado.Key.ToLower(), oDado.Value);
}
}
*/
string[] fields = new List<string>(data.Data.Keys).ToArray();
StringBuilder updateBuilder = new StringBuilder();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
updateBuilder.AppendFormat("update {0} set ", m_Realm);
bool first = true;
foreach (string field in fields)
{
if (!first)
updateBuilder.Append(", ");
updateBuilder.AppendFormat("\"{0}\" = :{0}",field);
first = false;
cmd.Parameters.Add(m_database.CreateParameter("" + field, data.Data[field]));
}
updateBuilder.Append(" where uuid = :principalID");
cmd.CommandText = updateBuilder.ToString();
cmd.Connection = conn;
cmd.Parameters.Add(m_database.CreateParameter("principalID", data.PrincipalID));
conn.Open();
if (cmd.ExecuteNonQuery() < 1)
{
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.AppendFormat("insert into {0} (uuid, \"", m_Realm);
insertBuilder.Append(String.Join("\", \"", fields));
insertBuilder.Append("\") values (:principalID, :");
insertBuilder.Append(String.Join(", :", fields));
insertBuilder.Append(")");
cmd.CommandText = insertBuilder.ToString();
if (cmd.ExecuteNonQuery() < 1)
{
return false;
}
}
}
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
string sql = string.Format("update {0} set {1} = :{1} where uuid = :UUID", m_Realm, item);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("" + item, value));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
string sql = "insert into tokens (uuid, token, validity) values (:principalID, :token, :lifetime)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("token", token));
cmd.Parameters.Add(m_database.CreateParameter("lifetime", DateTime.Now.AddMinutes(lifetime)));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
return true;
}
}
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
DateTime validDate = DateTime.Now.AddMinutes(lifetime);
string sql = "update tokens set validity = :validDate where uuid = :principalID and token = :token and validity > (CURRENT_DATE + CURRENT_TIME)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("principalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("token", token));
cmd.Parameters.Add(m_database.CreateParameter("validDate", validDate));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
return true;
}
}
return false;
}
private void DoExpire()
{
DateTime currentDateTime = DateTime.Now;
string sql = "delete from tokens where validity < :currentDateTime";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.Add(m_database.CreateParameter("currentDateTime", currentDateTime));
cmd.ExecuteNonQuery();
}
m_LastExpire = System.Environment.TickCount;
}
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DynamoDB.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDB.Model.Internal.MarshallTransformations
{
/// <summary>
/// Get Item Request Marshaller
/// </summary>
internal class GetItemRequestMarshaller : IMarshaller<IRequest, GetItemRequest>
{
public IRequest Marshall(GetItemRequest getItemRequest)
{
IRequest request = new DefaultRequest(getItemRequest, "AmazonDynamoDB");
string target = "DynamoDB_20111205.GetItem";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.0";
string uriResourcePath = "";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter())
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
if (getItemRequest != null && getItemRequest.IsSetTableName())
{
writer.WritePropertyName("TableName");
writer.Write(getItemRequest.TableName);
}
if (getItemRequest != null)
{
Key key = getItemRequest.Key;
if (key != null)
{
writer.WritePropertyName("Key");
writer.WriteObjectStart();
if (key != null)
{
AttributeValue hashKeyElement = key.HashKeyElement;
if (hashKeyElement != null)
{
writer.WritePropertyName("HashKeyElement");
writer.WriteObjectStart();
if (hashKeyElement != null && hashKeyElement.IsSetS())
{
writer.WritePropertyName("S");
writer.Write(hashKeyElement.S);
}
if (hashKeyElement != null && hashKeyElement.IsSetN())
{
writer.WritePropertyName("N");
writer.Write(hashKeyElement.N);
}
if (hashKeyElement != null && hashKeyElement.IsSetB())
{
writer.WritePropertyName("B");
writer.Write(StringUtils.FromMemoryStream(hashKeyElement.B));
}
if (hashKeyElement != null && hashKeyElement.SS != null && hashKeyElement.SS.Count > 0)
{
List<string> sSList = hashKeyElement.SS;
writer.WritePropertyName("SS");
writer.WriteArrayStart();
foreach (string sSListValue in sSList)
{
writer.Write(StringUtils.FromString(sSListValue));
}
writer.WriteArrayEnd();
}
if (hashKeyElement != null && hashKeyElement.NS != null && hashKeyElement.NS.Count > 0)
{
List<string> nSList = hashKeyElement.NS;
writer.WritePropertyName("NS");
writer.WriteArrayStart();
foreach (string nSListValue in nSList)
{
writer.Write(StringUtils.FromString(nSListValue));
}
writer.WriteArrayEnd();
}
if (hashKeyElement != null && hashKeyElement.BS != null && hashKeyElement.BS.Count > 0)
{
List<MemoryStream> bSList = hashKeyElement.BS;
writer.WritePropertyName("BS");
writer.WriteArrayStart();
foreach (MemoryStream bSListValue in bSList)
{
writer.Write(StringUtils.FromMemoryStream(bSListValue));
}
writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
}
}
if (key != null)
{
AttributeValue rangeKeyElement = key.RangeKeyElement;
if (rangeKeyElement != null)
{
writer.WritePropertyName("RangeKeyElement");
writer.WriteObjectStart();
if (rangeKeyElement != null && rangeKeyElement.IsSetS())
{
writer.WritePropertyName("S");
writer.Write(rangeKeyElement.S);
}
if (rangeKeyElement != null && rangeKeyElement.IsSetN())
{
writer.WritePropertyName("N");
writer.Write(rangeKeyElement.N);
}
if (rangeKeyElement != null && rangeKeyElement.IsSetB())
{
writer.WritePropertyName("B");
writer.Write(StringUtils.FromMemoryStream(rangeKeyElement.B));
}
if (rangeKeyElement != null && rangeKeyElement.SS != null && rangeKeyElement.SS.Count > 0)
{
List<string> sSList = rangeKeyElement.SS;
writer.WritePropertyName("SS");
writer.WriteArrayStart();
foreach (string sSListValue in sSList)
{
writer.Write(StringUtils.FromString(sSListValue));
}
writer.WriteArrayEnd();
}
if (rangeKeyElement != null && rangeKeyElement.NS != null && rangeKeyElement.NS.Count > 0)
{
List<string> nSList = rangeKeyElement.NS;
writer.WritePropertyName("NS");
writer.WriteArrayStart();
foreach (string nSListValue in nSList)
{
writer.Write(StringUtils.FromString(nSListValue));
}
writer.WriteArrayEnd();
}
if (rangeKeyElement != null && rangeKeyElement.BS != null && rangeKeyElement.BS.Count > 0)
{
List<MemoryStream> bSList = rangeKeyElement.BS;
writer.WritePropertyName("BS");
writer.WriteArrayStart();
foreach (MemoryStream bSListValue in bSList)
{
writer.Write(StringUtils.FromMemoryStream(bSListValue));
}
writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
}
}
writer.WriteObjectEnd();
}
}
if (getItemRequest != null && getItemRequest.AttributesToGet != null && getItemRequest.AttributesToGet.Count > 0)
{
List<string> attributesToGetList = getItemRequest.AttributesToGet;
writer.WritePropertyName("AttributesToGet");
writer.WriteArrayStart();
foreach (string attributesToGetListValue in attributesToGetList)
{
writer.Write(StringUtils.FromString(attributesToGetListValue));
}
writer.WriteArrayEnd();
}
if (getItemRequest != null && getItemRequest.IsSetConsistentRead())
{
writer.WritePropertyName("ConsistentRead");
writer.Write(getItemRequest.ConsistentRead);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Diagnostics
{
// Overview
// --------
// We have a few constraints we're working under here:
// - waitpid is used on Unix to get the exit status (including exit code) of a child process, but the first call
// to it after the child has completed will reap the child removing the chance of subsequent calls getting status.
// - The Process design allows for multiple independent Process objects to be handed out, and each of those
// objects may be used concurrently with each other, even if they refer to the same underlying process.
// Same with ProcessWaitHandle objects. This is based on the Windows design where anyone with a handle to the
// process can retrieve completion information about that process.
// - There is no good Unix equivalent to a process handle nor to being able to asynchronously be notified
// of a process' exit (without more intrusive mechanisms like ptrace), which means such support
// needs to be layered on top of waitpid.
//
// As a result, we have the following scheme:
// - We maintain a static/shared table that maps process ID to ProcessWaitState objects.
// Access to this table requires taking a global lock, so we try to minimize the number of
// times we need to access the table, primarily just the first time a Process object needs
// access to process exit/wait information and subsequently when that Process object gets GC'd.
// - Each process holds a ProcessWaitState.Holder object; when that object is constructed,
// it ensures there's an appropriate entry in the mapping table and increments that entry's ref count.
// - When a Process object is dropped and its ProcessWaitState.Holder is finalized, it'll
// decrement the ref count, and when no more process objects exist for a particular process ID,
// that entry in the table will be cleaned up.
// - This approach effectively allows for multiple independent Process objects for the same process ID to all
// share the same ProcessWaitState. And since they are sharing the same wait state object,
// the wait state object uses its own lock to protect the per-process state. This includes
// caching exit / exit code / exit time information so that a Process object for a process that's already
// had waitpid called for it can get at its exit information.
//
// A negative ramification of this is that if a process exits, but there are outstanding wait handles
// handed out (and rooted, so they can't be GC'd), and then a new process is created and the pid is recycled,
// new calls to get that process's wait state will get the old process's wait state. However, pid recycling
// will be a more general issue, since pids are the only identifier we have to a process, so if a Process
// object is created for a particular pid, then that process goes away and a new one comes in with the same pid,
// our Process object will silently switch to referring to the new pid. Unix systems typically have a simple
// policy for pid recycling, which is that they start at a low value, increment up to a system maximum (e.g.
// 32768), and then wrap around and start reusing value that aren't currently in use. On Linux,
// proc/sys/kernel/pid_max defines the max pid value. Given the conditions that would be required for this
// to happen, it's possible but unlikely.
/// <summary>Exit information and waiting capabilities for a process.</summary>
internal sealed class ProcessWaitState : IDisposable
{
/// <summary>
/// Finalizable holder for a process wait state. Instantiating one
/// will ensure that a wait state object exists for a process, will
/// grab it, and will increment its ref count. Dropping or disposing
/// one will decrement the ref count and clean up after it if the ref
/// count hits zero.
/// </summary>
internal sealed class Holder : IDisposable
{
internal ProcessWaitState _state;
internal Holder(int processId)
{
_state = ProcessWaitState.AddRef(processId);
}
~Holder()
{
// Don't try to Dispose resources (like ManualResetEvents) if
// the process is shutting down.
if (_state != null && !Environment.HasShutdownStarted)
{
_state.ReleaseRef();
}
}
public void Dispose()
{
if (_state != null)
{
GC.SuppressFinalize(this);
_state.ReleaseRef();
_state = null;
}
}
}
/// <summary>
/// Global table that maps process IDs to the associated shared wait state information.
/// </summary>
private static readonly Dictionary<int, ProcessWaitState> s_processWaitStates =
new Dictionary<int, ProcessWaitState>();
/// <summary>
/// Ensures that the mapping table contains an entry for the process ID,
/// increments its ref count, and returns it.
/// </summary>
/// <param name="processId">The process ID for which we need wait state.</param>
/// <returns>The wait state object.</returns>
internal static ProcessWaitState AddRef(int processId)
{
lock (s_processWaitStates)
{
ProcessWaitState pws;
if (!s_processWaitStates.TryGetValue(processId, out pws))
{
pws = new ProcessWaitState(processId);
s_processWaitStates.Add(processId, pws);
}
pws._outstandingRefCount++;
return pws;
}
}
/// <summary>
/// Decrements the ref count on the wait state object, and if it's the last one,
/// removes it from the table.
/// </summary>
internal void ReleaseRef()
{
ProcessWaitState pws;
lock (ProcessWaitState.s_processWaitStates)
{
bool foundState = ProcessWaitState.s_processWaitStates.TryGetValue(_processId, out pws);
Debug.Assert(foundState);
if (foundState)
{
--pws._outstandingRefCount;
if (pws._outstandingRefCount == 0)
{
s_processWaitStates.Remove(_processId);
}
else
{
pws = null;
}
}
}
pws?.Dispose();
}
/// <summary>
/// Synchronization object used to protect all instance state. Any number of
/// Process and ProcessWaitHandle objects may be using a ProcessWaitState
/// instance concurrently.
/// </summary>
private readonly object _gate = new object();
/// <summary>ID of the associated process.</summary>
private readonly int _processId;
/// <summary>If a wait operation is in progress, the Task that represents it; otherwise, null.</summary>
private Task _waitInProgress;
/// <summary>The number of alive users of this object.</summary>
private int _outstandingRefCount;
/// <summary>Whether the associated process exited.</summary>
private bool _exited;
/// <summary>If the process exited, it's exit code, or null if we were unable to determine one.</summary>
private int? _exitCode;
/// <summary>
/// The approximate time the process exited. We do not have the ability to know exact time a process
/// exited, so we approximate it by storing the time that we discovered it exited.
/// </summary>
private DateTime _exitTime;
/// <summary>A lazily-initialized event set when the process exits.</summary>
private ManualResetEvent _exitedEvent;
/// <summary>Initialize the wait state object.</summary>
/// <param name="processId">The associated process' ID.</param>
private ProcessWaitState(int processId)
{
Debug.Assert(processId >= 0);
_processId = processId;
}
/// <summary>Releases managed resources used by the ProcessWaitState.</summary>
public void Dispose()
{
Debug.Assert(!Monitor.IsEntered(_gate));
lock (_gate)
{
if (_exitedEvent != null)
{
_exitedEvent.Dispose();
_exitedEvent = null;
}
}
}
/// <summary>Notes that the process has exited.</summary>
private void SetExited()
{
Debug.Assert(Monitor.IsEntered(_gate));
_exited = true;
_exitTime = DateTime.Now;
_exitedEvent?.Set();
}
/// <summary>Ensures an exited event has been initialized and returns it.</summary>
/// <returns></returns>
internal ManualResetEvent EnsureExitedEvent()
{
Debug.Assert(!Monitor.IsEntered(_gate));
lock (_gate)
{
// If we already have an initialized event, just return it.
if (_exitedEvent == null)
{
// If we don't, create one, and if the process hasn't yet exited,
// make sure we have a task that's actively monitoring the completion state.
_exitedEvent = new ManualResetEvent(initialState: _exited);
if (!_exited)
{
// If we haven't exited, we need to spin up an asynchronous operation that
// will completed the exitedEvent when the other process exits. If there's already
// another operation underway, then we'll just tack ours onto the end of it.
_waitInProgress = _waitInProgress == null ?
WaitForExitAsync() :
_waitInProgress.ContinueWith((_, state) => ((ProcessWaitState)state).WaitForExitAsync(),
this, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap();
}
}
return _exitedEvent;
}
}
internal DateTime ExitTime
{
get
{
lock (_gate)
{
Debug.Assert(_exited);
return _exitTime;
}
}
}
internal bool HasExited
{
get
{
int? ignored;
return GetExited(out ignored);
}
}
internal bool GetExited(out int? exitCode)
{
lock (_gate)
{
// Have we already exited? If so, return the cached results.
if (_exited)
{
exitCode = _exitCode;
return true;
}
// Is another wait operation in progress? If so, then we haven't exited,
// and that task owns the right to call CheckForExit.
if (_waitInProgress != null)
{
exitCode = null;
return false;
}
// We don't know if we've exited, but no one else is currently
// checking, so check.
CheckForExit();
// We now have an up-to-date snapshot for whether we've exited,
// and if we have, what the exit code is (if we were able to find out).
exitCode = _exitCode;
return _exited;
}
}
private void CheckForExit(bool blockingAllowed = false)
{
Debug.Assert(Monitor.IsEntered(_gate));
Debug.Assert(!blockingAllowed); // see "PERF NOTE" comment in WaitForExit
// Try to get the state of the (child) process
int status;
int waitResult = Interop.Sys.WaitPid(_processId, out status,
blockingAllowed ? Interop.Sys.WaitPidOptions.None : Interop.Sys.WaitPidOptions.WNOHANG);
if (waitResult == _processId)
{
// Process has exited
if (Interop.Sys.WIfExited(status))
{
_exitCode = Interop.Sys.WExitStatus(status);
}
else if (Interop.Sys.WIfSignaled(status))
{
const int ExitCodeSignalOffset = 128;
_exitCode = ExitCodeSignalOffset + Interop.Sys.WTermSig(status);
}
SetExited();
return;
}
else if (waitResult == 0)
{
// Process is still running
return;
}
else if (waitResult == -1)
{
// Something went wrong, e.g. it's not a child process,
// or waitpid was already called for this child, or
// that the call was interrupted by a signal.
Interop.Error errno = Interop.Sys.GetLastError();
if (errno == Interop.Error.ECHILD)
{
// waitpid was used with a non-child process. We won't be
// able to get an exit code, but we'll at least be able
// to determine if the process is still running (assuming
// there's not a race on its id).
int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.None); // None means don't send a signal
if (killResult == 0)
{
// Process is still running. This could also be a defunct process that has completed
// its work but still has an entry in the processes table due to its parent not yet
// having waited on it to clean it up.
return;
}
else // error from kill
{
errno = Interop.Sys.GetLastError();
if (errno == Interop.Error.ESRCH)
{
// Couldn't find the process; assume it's exited
SetExited();
return;
}
else if (errno == Interop.Error.EPERM)
{
// Don't have permissions to the process; assume it's alive
return;
}
else Debug.Fail("Unexpected errno value from kill");
}
}
else Debug.Fail("Unexpected errno value from waitpid");
}
else Debug.Fail("Unexpected process ID from waitpid.");
SetExited();
}
/// <summary>Waits for the associated process to exit.</summary>
/// <param name="millisecondsTimeout">The amount of time to wait, or -1 to wait indefinitely.</param>
/// <returns>true if the process exited; false if the timeout occurred.</returns>
internal bool WaitForExit(int millisecondsTimeout)
{
Debug.Assert(!Monitor.IsEntered(_gate));
// Track the time the we start waiting.
long startTime = Stopwatch.GetTimestamp();
// Polling loop
while (true)
{
bool createdTask = false;
CancellationTokenSource cts = null;
Task waitTask;
// We're in a polling loop... determine how much time remains
int remainingTimeout = millisecondsTimeout == Timeout.Infinite ?
Timeout.Infinite :
(int)Math.Max(millisecondsTimeout - ((Stopwatch.GetTimestamp() - startTime) / (double)Stopwatch.Frequency * 1000), 0);
lock (_gate)
{
// If we already know that the process exited, we're done.
if (_exited)
{
return true;
}
// If a timeout of 0 was supplied, then we simply need to poll
// to see if the process has already exited.
if (remainingTimeout == 0)
{
// If there's currently a wait-in-progress, then we know the other process
// hasn't exited (barring races and the polling interval).
if (_waitInProgress != null)
{
return false;
}
// No one else is checking for the process' exit... so check.
// We're currently holding the _gate lock, so we don't want to
// allow CheckForExit to block indefinitely.
CheckForExit();
return _exited;
}
// The process has not yet exited (or at least we don't know it yet)
// so we need to wait for it to exit, outside of the lock.
// If there's already a wait in progress, we'll do so later
// by waiting on that existing task. Otherwise, we'll spin up
// such a task.
if (_waitInProgress != null)
{
waitTask = _waitInProgress;
}
else
{
createdTask = true;
CancellationToken token = remainingTimeout == Timeout.Infinite ?
CancellationToken.None :
(cts = new CancellationTokenSource(remainingTimeout)).Token;
waitTask = WaitForExitAsync(token);
// PERF NOTE:
// At the moment, we never call CheckForExit(true) (which in turn allows
// waitpid to block until the child has completed) because we currently call it while
// holding the _gate lock. This is probably unnecessary in some situations, and in particular
// here if remainingTimeout == Timeout.Infinite. In that case, we should be able to set
// _waitInProgress to be a TaskCompletionSource task, and then below outside of the lock
// we could do a CheckForExit(blockingAllowed:true) and complete the TaskCompletionSource
// after that. We would just need to make sure that there's no risk of the other state
// on this instance experiencing torn reads.
}
} // lock(_gate)
if (createdTask)
{
// We created this task, and it'll get canceled automatically after our timeout.
// This Wait should only wake up when either the process has exited or the timeout
// has expired. Either way, we'll loop around again; if the process exited, that'll
// be caught first thing in the loop where we check _exited, and if it didn't exit,
// our remaining time will be zero, so we'll do a quick remaining check and bail.
waitTask.Wait();
cts?.Dispose();
}
else
{
// It's someone else's task. We'll wait for it to complete. This could complete
// either because our remainingTimeout expired or because the task completed,
// which could happen because the process exited or because whoever created
// that task gave it a timeout. In any case, we'll loop around again, and the loop
// will catch these cases, potentially issuing another wait to make up any
// remaining time.
waitTask.Wait(remainingTimeout);
}
}
}
/// <summary>Spawns an asynchronous polling loop for process completion.</summary>
/// <param name="cancellationToken">A token to monitor to exit the polling loop.</param>
/// <returns>The task representing the loop.</returns>
private Task WaitForExitAsync(CancellationToken cancellationToken = default(CancellationToken))
{
Debug.Assert(Monitor.IsEntered(_gate));
Debug.Assert(_waitInProgress == null);
return _waitInProgress = Task.Run(async delegate // Task.Run used because of potential blocking in CheckForExit
{
// Arbitrary values chosen to balance delays with polling overhead. Start with fast polling
// to handle quickly completing processes, but fall back to longer polling to minimize
// overhead for those that take longer to complete.
const int StartingPollingIntervalMs = 1, MaxPollingIntervalMs = 100;
int pollingIntervalMs = StartingPollingIntervalMs;
try
{
// While we're not canceled
while (!cancellationToken.IsCancellationRequested)
{
// Poll
lock (_gate)
{
if (!_exited)
{
CheckForExit();
}
if (_exited) // may have been updated by CheckForExit
{
return;
}
}
// Wait
try
{
await Task.Delay(pollingIntervalMs, cancellationToken);
pollingIntervalMs = Math.Min(pollingIntervalMs * 2, MaxPollingIntervalMs);
}
catch (OperationCanceledException) { }
}
}
finally
{
// Task is no longer active
lock (_gate)
{
_waitInProgress = null;
}
}
});
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>BiddingSeasonalityAdjustment</c> resource.</summary>
public sealed partial class BiddingSeasonalityAdjustmentName : gax::IResourceName, sys::IEquatable<BiddingSeasonalityAdjustmentName>
{
/// <summary>The possible contents of <see cref="BiddingSeasonalityAdjustmentName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
CustomerSeasonalityEvent = 1,
}
private static gax::PathTemplate s_customerSeasonalityEvent = new gax::PathTemplate("customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}");
/// <summary>
/// Creates a <see cref="BiddingSeasonalityAdjustmentName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="BiddingSeasonalityAdjustmentName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static BiddingSeasonalityAdjustmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new BiddingSeasonalityAdjustmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="BiddingSeasonalityAdjustmentName"/> with the pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="BiddingSeasonalityAdjustmentName"/> constructed from the provided ids.
/// </returns>
public static BiddingSeasonalityAdjustmentName FromCustomerSeasonalityEvent(string customerId, string seasonalityEventId) =>
new BiddingSeasonalityAdjustmentName(ResourceNameType.CustomerSeasonalityEvent, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), seasonalityEventId: gax::GaxPreconditions.CheckNotNullOrEmpty(seasonalityEventId, nameof(seasonalityEventId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with
/// pattern <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </returns>
public static string Format(string customerId, string seasonalityEventId) =>
FormatCustomerSeasonalityEvent(customerId, seasonalityEventId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with
/// pattern <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="BiddingSeasonalityAdjustmentName"/> with pattern
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>.
/// </returns>
public static string FormatCustomerSeasonalityEvent(string customerId, string seasonalityEventId) =>
s_customerSeasonalityEvent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(seasonalityEventId, nameof(seasonalityEventId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="BiddingSeasonalityAdjustmentName"/> if successful.</returns>
public static BiddingSeasonalityAdjustmentName Parse(string biddingSeasonalityAdjustmentName) =>
Parse(biddingSeasonalityAdjustmentName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="BiddingSeasonalityAdjustmentName"/> if successful.</returns>
public static BiddingSeasonalityAdjustmentName Parse(string biddingSeasonalityAdjustmentName, bool allowUnparsed) =>
TryParse(biddingSeasonalityAdjustmentName, allowUnparsed, out BiddingSeasonalityAdjustmentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingSeasonalityAdjustmentName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingSeasonalityAdjustmentName, out BiddingSeasonalityAdjustmentName result) =>
TryParse(biddingSeasonalityAdjustmentName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="BiddingSeasonalityAdjustmentName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="biddingSeasonalityAdjustmentName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="BiddingSeasonalityAdjustmentName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string biddingSeasonalityAdjustmentName, bool allowUnparsed, out BiddingSeasonalityAdjustmentName result)
{
gax::GaxPreconditions.CheckNotNull(biddingSeasonalityAdjustmentName, nameof(biddingSeasonalityAdjustmentName));
gax::TemplatedResourceName resourceName;
if (s_customerSeasonalityEvent.TryParseName(biddingSeasonalityAdjustmentName, out resourceName))
{
result = FromCustomerSeasonalityEvent(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(biddingSeasonalityAdjustmentName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private BiddingSeasonalityAdjustmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string seasonalityEventId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
SeasonalityEventId = seasonalityEventId;
}
/// <summary>
/// Constructs a new instance of a <see cref="BiddingSeasonalityAdjustmentName"/> class from the component parts
/// of pattern <c>customers/{customer_id}/biddingSeasonalityAdjustments/{seasonality_event_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="seasonalityEventId">The <c>SeasonalityEvent</c> ID. Must not be <c>null</c> or empty.</param>
public BiddingSeasonalityAdjustmentName(string customerId, string seasonalityEventId) : this(ResourceNameType.CustomerSeasonalityEvent, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), seasonalityEventId: gax::GaxPreconditions.CheckNotNullOrEmpty(seasonalityEventId, nameof(seasonalityEventId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>SeasonalityEvent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string SeasonalityEventId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerSeasonalityEvent: return s_customerSeasonalityEvent.Expand(CustomerId, SeasonalityEventId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as BiddingSeasonalityAdjustmentName);
/// <inheritdoc/>
public bool Equals(BiddingSeasonalityAdjustmentName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(BiddingSeasonalityAdjustmentName a, BiddingSeasonalityAdjustmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(BiddingSeasonalityAdjustmentName a, BiddingSeasonalityAdjustmentName b) => !(a == b);
}
public partial class BiddingSeasonalityAdjustment
{
/// <summary>
/// <see cref="gagvr::BiddingSeasonalityAdjustmentName"/>-typed view over the <see cref="ResourceName"/>
/// resource name property.
/// </summary>
internal BiddingSeasonalityAdjustmentName ResourceNameAsBiddingSeasonalityAdjustmentName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BiddingSeasonalityAdjustmentName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::BiddingSeasonalityAdjustmentName"/>-typed view over the <see cref="Name"/> resource name
/// property.
/// </summary>
internal BiddingSeasonalityAdjustmentName BiddingSeasonalityAdjustmentName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::BiddingSeasonalityAdjustmentName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaigns"/> resource name property.
/// </summary>
internal gax::ResourceNameList<CampaignName> CampaignsAsCampaignNames
{
get => new gax::ResourceNameList<CampaignName>(Campaigns, s => string.IsNullOrEmpty(s) ? null : CampaignName.Parse(s, allowUnparsed: true));
}
}
}
| |
using System;
using System.Collections;
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using HttpUtility = System.Web.HttpUtility;
using System.Threading;
namespace Refit
{
class RequestBuilderFactory : IRequestBuilderFactory
{
public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null)
{
return new RequestBuilderImplementation(interfaceType, settings);
}
}
class RequestBuilderImplementation : IRequestBuilder
{
readonly Type targetType;
readonly Dictionary<string, RestMethodInfo> interfaceHttpMethods;
readonly RefitSettings settings;
public RequestBuilderImplementation(Type targetInterface, RefitSettings refitSettings = null)
{
settings = refitSettings ?? new RefitSettings();
if (targetInterface == null || !targetInterface.IsInterface()) {
throw new ArgumentException("targetInterface must be an Interface");
}
targetType = targetInterface;
interfaceHttpMethods = targetInterface.GetMethods()
.SelectMany(x => {
var attrs = x.GetCustomAttributes(true);
var hasHttpMethod = attrs.OfType<HttpMethodAttribute>().Any();
if (!hasHttpMethod) return Enumerable.Empty<RestMethodInfo>();
return EnumerableEx.Return(new RestMethodInfo(targetInterface, x, settings));
})
.ToDictionary(k => k.Name, v => v);
}
public IEnumerable<string> InterfaceHttpMethods {
get { return interfaceHttpMethods.Keys; }
}
Func<object[], HttpRequestMessage> buildRequestFactoryForMethod(string methodName, string basePath, bool paramsContainsCancellationToken)
{
if (!interfaceHttpMethods.ContainsKey(methodName)) {
throw new ArgumentException("Method must be defined and have an HTTP Method attribute");
}
var restMethod = interfaceHttpMethods[methodName];
return paramList => {
// make sure we strip out any cancelation tokens
if (paramsContainsCancellationToken) {
paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray();
}
var ret = new HttpRequestMessage {
Method = restMethod.HttpMethod,
};
// set up multipart content
MultipartFormDataContent multiPartContent = null;
if (restMethod.IsMultipart) {
multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
ret.Content = multiPartContent;
}
string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath;
var queryParamsToAdd = new Dictionary<string, string>();
var headersToAdd = new Dictionary<string, string>(restMethod.Headers);
for(int i=0; i < paramList.Length; i++) {
// if part of REST resource URL, substitute it in
if (restMethod.ParameterMap.ContainsKey(i)) {
urlTarget = Regex.Replace(
urlTarget,
"{" + restMethod.ParameterMap[i] + "}",
settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]),
RegexOptions.IgnoreCase);
continue;
}
// if marked as body, add to content
if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) {
var streamParam = paramList[i] as Stream;
var stringParam = paramList[i] as string;
var httpContentParam = paramList[i] as HttpContent;
if (httpContentParam != null) {
ret.Content = httpContentParam;
} else if (streamParam != null) {
ret.Content = new StreamContent(streamParam);
} else if (stringParam != null) {
ret.Content = new StringContent(stringParam);
} else {
switch (restMethod.BodyParameterInfo.Item1) {
case BodySerializationMethod.UrlEncoded:
ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i]));
break;
case BodySerializationMethod.Json:
ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json");
break;
}
}
continue;
}
// if header, add to request headers
if (restMethod.HeaderParameterMap.ContainsKey(i)) {
headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null
? paramList[i].ToString()
: null;
continue;
}
// ignore nulls
if (paramList[i] == null) continue;
// for anything that fell through to here, if this is not
// a multipart method, add the parameter to the query string
if (!restMethod.IsMultipart) {
queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]);
continue;
}
// we are in a multipart method, add the part to the content
// the parameter name should be either the attachment name or the parameter name (as fallback)
string itemName;
if (! restMethod.AttachmentNameMap.TryGetValue(i, out itemName)) itemName = restMethod.QueryParameterMap[i];
addMultipartItem(multiPartContent, itemName, paramList[i]);
}
// NB: We defer setting headers until the body has been
// added so any custom content headers don't get left out.
foreach (var header in headersToAdd) {
setHeader(ret, header.Key, header.Value);
}
// NB: The URI methods in .NET are dumb. Also, we do this
// UriBuilder business so that we preserve any hardcoded query
// parameters as well as add the parameterized ones.
var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget));
var query = HttpUtility.ParseQueryString(uri.Query ?? "");
foreach(var kvp in queryParamsToAdd) {
query.Add(kvp.Key, kvp.Value);
}
if (query.HasKeys()) {
var pairs = query.Keys.Cast<string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x]));
uri.Query = String.Join("&", pairs);
} else {
uri.Query = null;
}
ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative);
return ret;
};
}
static void setHeader(HttpRequestMessage request, string name, string value)
{
// Clear any existing version of this header that might be set, because
// we want to allow removal/redefinition of headers.
// We also don't want to double up content headers which may have been
// set for us automatically.
// NB: We have to enumerate the header names to check existence because
// Contains throws if it's the wrong header type for the collection.
if (request.Headers.Any(x => x.Key == name)) {
request.Headers.Remove(name);
}
if (request.Content != null && request.Content.Headers.Any(x => x.Key == name)) {
request.Content.Headers.Remove(name);
}
if (value == null) return;
var added = request.Headers.TryAddWithoutValidation(name, value);
// Don't even bother trying to add the header as a content header
// if we just added it to the other collection.
if (!added && request.Content != null) {
request.Content.Headers.TryAddWithoutValidation(name, value);
}
}
void addMultipartItem(MultipartFormDataContent multiPartContent, string itemName, object itemValue)
{
var streamValue = itemValue as Stream;
var stringValue = itemValue as String;
var byteArrayValue = itemValue as byte[];
if (streamValue != null) {
var streamContent = new StreamContent(streamValue);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = itemName
};
multiPartContent.Add(streamContent);
return;
}
if (stringValue != null) {
multiPartContent.Add(new StringContent(stringValue), itemName);
return;
}
#if !NETFX_CORE
var fileInfoValue = itemValue as FileInfo;
if (fileInfoValue != null) {
var fileContent = new StreamContent(fileInfoValue.OpenRead());
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = fileInfoValue.Name
};
multiPartContent.Add(fileContent);
return;
}
#endif
if (byteArrayValue != null) {
var fileContent = new ByteArrayContent(byteArrayValue);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = itemName
};
multiPartContent.Add(fileContent);
return;
}
throw new ArgumentException(string.Format("Unexpected parameter type in a Multipart request. Parameter {0} is of type {1}, whereas allowed types are String, Stream, FileInfo, and Byte array", itemName, itemValue.GetType().Name), "itemValue");
}
public Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName)
{
if (!interfaceHttpMethods.ContainsKey(methodName)) {
throw new ArgumentException("Method must be defined and have an HTTP Method attribute");
}
var restMethod = interfaceHttpMethods[methodName];
if (restMethod.ReturnType == typeof(Task)) {
return buildVoidTaskFuncForMethod(restMethod);
} else if (restMethod.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) {
// NB: This jacked up reflection code is here because it's
// difficult to upcast Task<object> to an arbitrary T, especially
// if you need to AOT everything, so we need to reflectively
// invoke buildTaskFuncForMethod.
var taskFuncMi = GetType().GetMethod("buildTaskFuncForMethod", BindingFlags.NonPublic | BindingFlags.Instance);
var taskFunc = (MulticastDelegate)taskFuncMi.MakeGenericMethod(restMethod.SerializedReturnType)
.Invoke(this, new[] { restMethod });
return (client, args) => {
return taskFunc.DynamicInvoke(new object[] { client, args } );
};
} else {
// Same deal
var rxFuncMi = GetType().GetMethod("buildRxFuncForMethod", BindingFlags.NonPublic | BindingFlags.Instance);
var rxFunc = (MulticastDelegate)rxFuncMi.MakeGenericMethod(restMethod.SerializedReturnType)
.Invoke(this, new[] { restMethod });
return (client, args) => {
return rxFunc.DynamicInvoke(new object[] { client, args });
};
}
}
Func<HttpClient, object[], Task> buildVoidTaskFuncForMethod(RestMethodInfo restMethod)
{
return async (client, paramList) => {
var factory = buildRequestFactoryForMethod(restMethod.Name, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null);
var rq = factory(paramList);
var ct = CancellationToken.None;
if (restMethod.CancellationToken != null) {
ct = paramList.OfType<CancellationToken>().FirstOrDefault();
}
using (var resp = await client.SendAsync(rq, ct).ConfigureAwait(false)) {
if (!resp.IsSuccessStatusCode) {
throw await ApiException.Create(rq.RequestUri, restMethod.HttpMethod, resp, settings).ConfigureAwait(false);
}
}
};
}
Func<HttpClient, object[], Task<T>> buildTaskFuncForMethod<T>(RestMethodInfo restMethod)
{
var ret = buildCancellableTaskFuncForMethod<T>(restMethod);
return (client, paramList) => {
if(restMethod.CancellationToken != null) {
return ret(client, paramList.OfType<CancellationToken>().FirstOrDefault(), paramList);
}
return ret(client, CancellationToken.None, paramList);
};
}
Func<HttpClient, CancellationToken, object[], Task<T>> buildCancellableTaskFuncForMethod<T>(RestMethodInfo restMethod)
{
return async (client, ct, paramList) => {
var factory = buildRequestFactoryForMethod(restMethod.Name, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null);
var rq = factory(paramList);
var resp = await client.SendAsync(rq, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
if (restMethod.SerializedReturnType == typeof(HttpResponseMessage)) {
// NB: This double-casting manual-boxing hate crime is the only way to make
// this work without a 'class' generic constraint. It could blow up at runtime
// and would be A Bad Idea if we hadn't already vetted the return type.
return (T)(object)resp;
}
if (!resp.IsSuccessStatusCode) {
throw await ApiException.Create(rq.RequestUri, restMethod.HttpMethod, resp, restMethod.RefitSettings).ConfigureAwait(false);
}
if (restMethod.SerializedReturnType == typeof(HttpContent)) {
return (T)(object)resp.Content;
}
var ms = new MemoryStream();
using (var fromStream = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false)) {
await fromStream.CopyToAsync(ms, 4096, ct).ConfigureAwait(false);
}
var bytes = ms.ToArray();
var content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
if (restMethod.SerializedReturnType == typeof(string)) {
return (T)(object)content;
}
return JsonConvert.DeserializeObject<T>(content, settings.JsonSerializerSettings);
};
}
Func<HttpClient, object[], IObservable<T>> buildRxFuncForMethod<T>(RestMethodInfo restMethod)
{
var taskFunc = buildCancellableTaskFuncForMethod<T>(restMethod);
return (client, paramList) => {
return new TaskToObservable<T>(ct => {
var methodCt = CancellationToken.None;
if (restMethod.CancellationToken != null) {
methodCt = paramList.OfType<CancellationToken>().FirstOrDefault();
}
// link the two
var cts = CancellationTokenSource.CreateLinkedTokenSource(methodCt, ct);
return taskFunc(client, cts.Token, paramList);
});
};
}
class TaskToObservable<T> : IObservable<T>
{
Func<CancellationToken, Task<T>> taskFactory;
public TaskToObservable(Func<CancellationToken, Task<T>> taskFactory)
{
this.taskFactory = taskFactory;
}
public IDisposable Subscribe(IObserver<T> observer)
{
var cts = new CancellationTokenSource();
taskFactory(cts.Token).ContinueWith(t => {
if (cts.IsCancellationRequested) return;
if (t.Exception != null) {
observer.OnError(t.Exception.InnerExceptions.First());
return;
}
try {
observer.OnNext(t.Result);
} catch (Exception ex) {
observer.OnError(ex);
}
observer.OnCompleted();
});
return new AnonymousDisposable(cts.Cancel);
}
}
}
sealed class AnonymousDisposable : IDisposable
{
readonly Action block;
public AnonymousDisposable(Action block)
{
this.block = block;
}
public void Dispose()
{
block();
}
}
public class RestMethodInfo
{
public string Name { get; set; }
public Type Type { get; set; }
public MethodInfo MethodInfo { get; set; }
public HttpMethod HttpMethod { get; set; }
public string RelativePath { get; set; }
public bool IsMultipart { get; private set; }
public Dictionary<int, string> ParameterMap { get; set; }
public ParameterInfo CancellationToken { get; set; }
public Dictionary<string, string> Headers { get; set; }
public Dictionary<int, string> HeaderParameterMap { get; set; }
public Tuple<BodySerializationMethod, int> BodyParameterInfo { get; set; }
public Dictionary<int, string> QueryParameterMap { get; set; }
public Dictionary<int, string> AttachmentNameMap { get; set; }
public Dictionary<int, ParameterInfo> ParameterInfoMap { get; set; }
public Type ReturnType { get; set; }
public Type SerializedReturnType { get; set; }
public RefitSettings RefitSettings { get; set; }
static readonly Regex parameterRegex = new Regex(@"{(.*?)}");
static readonly HttpMethod patchMethod = new HttpMethod("PATCH");
public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null)
{
RefitSettings = refitSettings ?? new RefitSettings();
Type = targetInterface;
Name = methodInfo.Name;
MethodInfo = methodInfo;
var hma = methodInfo.GetCustomAttributes(true)
.OfType<HttpMethodAttribute>()
.First();
HttpMethod = hma.Method;
RelativePath = hma.Path;
IsMultipart = methodInfo.GetCustomAttributes(true)
.OfType<MultipartAttribute>()
.Any();
verifyUrlPathIsSane(RelativePath);
determineReturnTypeInfo(methodInfo);
// Exclude cancellation token parameters from this list
var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList();
ParameterInfoMap = parameterList
.Select((parameter, index) => new { index, parameter })
.ToDictionary(x => x.index, x => x.parameter);
ParameterMap = buildParameterMap(RelativePath, parameterList);
BodyParameterInfo = findBodyParameter(parameterList, IsMultipart, hma.Method);
Headers = parseHeaders(methodInfo);
HeaderParameterMap = buildHeaderParameterMap(parameterList);
// get names for multipart attachments
AttachmentNameMap = new Dictionary<int, string>();
if (IsMultipart) {
for (int i = 0; i < parameterList.Count; i++) {
if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i)) {
continue;
}
var attachmentName = getAttachmentNameForParameter(parameterList[i]);
if (attachmentName == null) continue;
AttachmentNameMap[i] = attachmentName;
}
}
QueryParameterMap = new Dictionary<int, string>();
for (int i=0; i < parameterList.Count; i++) {
if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item2 == i) || AttachmentNameMap.ContainsKey(i)) {
continue;
}
QueryParameterMap[i] = getUrlNameForParameter(parameterList[i]);
}
var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList();
if(ctParams.Count > 1) {
throw new ArgumentException("Argument list can only contain a single CancellationToken");
}
CancellationToken = ctParams.FirstOrDefault();
}
void verifyUrlPathIsSane(string relativePath)
{
if (relativePath == "")
return;
if (!relativePath.StartsWith("/")) {
goto bogusPath;
}
var parts = relativePath.Split('/');
if (parts.Length == 0) {
goto bogusPath;
}
return;
bogusPath:
throw new ArgumentException("URL path must be of the form '/foo/bar/baz'");
}
Dictionary<int, string> buildParameterMap(string relativePath, List<ParameterInfo> parameterInfo)
{
var ret = new Dictionary<int, string>();
var parameterizedParts = relativePath.Split('/', '?')
.SelectMany(x => parameterRegex.Matches(x).Cast<Match>())
.ToList();
if (parameterizedParts.Count == 0) {
return ret;
}
var paramValidationDict = parameterInfo.ToDictionary(k => getUrlNameForParameter(k).ToLowerInvariant(), v => v);
foreach (var match in parameterizedParts) {
var name = match.Groups[1].Value.ToLowerInvariant();
if (!paramValidationDict.ContainsKey(name)) {
throw new ArgumentException(String.Format("URL has parameter {0}, but no method parameter matches", name));
}
ret.Add(parameterInfo.IndexOf(paramValidationDict[name]), name);
}
return ret;
}
string getUrlNameForParameter(ParameterInfo paramInfo)
{
var aliasAttr = paramInfo.GetCustomAttributes(true)
.OfType<AliasAsAttribute>()
.FirstOrDefault();
return aliasAttr != null ? aliasAttr.Name : paramInfo.Name;
}
string getAttachmentNameForParameter(ParameterInfo paramInfo)
{
var nameAttr = paramInfo.GetCustomAttributes(true)
.OfType<AttachmentNameAttribute>()
.FirstOrDefault();
return nameAttr != null ? nameAttr.Name : null;
}
static Tuple<BodySerializationMethod, int> findBodyParameter(IList<ParameterInfo> parameterList, bool isMultipart, HttpMethod method)
{
// The body parameter is found using the following logic / order of precedence:
// 1) [Body] attribute
// 2) POST/PUT/PATCH: Reference type other than string
// 3) If there are two reference types other than string, without the body attribute, throw
var bodyParams = parameterList
.Select(x => new { Parameter = x, BodyAttribute = x.GetCustomAttributes(true).OfType<BodyAttribute>().FirstOrDefault() })
.Where(x => x.BodyAttribute != null)
.ToList();
// multipart requests may not contain a body, implicit or explicit
if (isMultipart) {
if (bodyParams.Count > 0) {
throw new ArgumentException("Multipart requests may not contain a Body parameter");
}
return null;
}
if (bodyParams.Count > 1) {
throw new ArgumentException("Only one parameter can be a Body parameter");
}
// #1, body attribute wins
if (bodyParams.Count == 1) {
var ret = bodyParams[0];
return Tuple.Create(ret.BodyAttribute.SerializationMethod, parameterList.IndexOf(ret.Parameter));
}
// Not in post/put/patch? bail
if (!method.Equals(HttpMethod.Post) && !method.Equals(HttpMethod.Put) && !method.Equals(patchMethod)) {
return null;
}
// see if we're a post/put/patch
var refParams = parameterList.Where(pi => !pi.ParameterType.GetTypeInfo().IsValueType && pi.ParameterType != typeof(string)).ToList();
// Check for rule #3
if (refParams.Count > 1) {
throw new ArgumentException("Multiple complex types found. Specify one parameter as the body using BodyAttribute");
}
if (refParams.Count == 1) {
return Tuple.Create(BodySerializationMethod.Json, parameterList.IndexOf(refParams[0]));
}
return null;
}
Dictionary<string, string> parseHeaders(MethodInfo methodInfo)
{
var ret = new Dictionary<string, string>();
var declaringTypeAttributes = methodInfo.DeclaringType != null
? methodInfo.DeclaringType.GetCustomAttributes(true)
: new Attribute[0];
// Headers set on the declaring type have to come first,
// so headers set on the method can replace them. Switching
// the order here will break stuff.
var headers = declaringTypeAttributes.Concat(methodInfo.GetCustomAttributes(true))
.OfType<HeadersAttribute>()
.SelectMany(ha => ha.Headers);
foreach (var header in headers) {
if (string.IsNullOrWhiteSpace(header)) continue;
// NB: Silverlight doesn't have an overload for String.Split()
// with a count parameter, but header values can contain
// ':' so we have to re-join all but the first part to get the
// value.
var parts = header.Split(':');
ret[parts[0].Trim()] = parts.Length > 1 ?
String.Join(":", parts.Skip(1)).Trim() : null;
}
return ret;
}
Dictionary<int, string> buildHeaderParameterMap(List<ParameterInfo> parameterList)
{
var ret = new Dictionary<int, string>();
for (int i = 0; i < parameterList.Count; i++) {
var header = parameterList[i].GetCustomAttributes(true)
.OfType<HeaderAttribute>()
.Select(ha => ha.Header)
.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(header)) {
ret[i] = header.Trim();
}
}
return ret;
}
void determineReturnTypeInfo(MethodInfo methodInfo)
{
if (methodInfo.ReturnType.IsGenericType() == false) {
if (methodInfo.ReturnType != typeof (Task)) {
goto bogusMethod;
}
ReturnType = methodInfo.ReturnType;
SerializedReturnType = typeof(void);
return;
}
var genericType = methodInfo.ReturnType.GetGenericTypeDefinition();
if (genericType != typeof(Task<>) && genericType != typeof(IObservable<>)) {
goto bogusMethod;
}
ReturnType = methodInfo.ReturnType;
SerializedReturnType = methodInfo.ReturnType.GetGenericArguments()[0];
return;
bogusMethod:
throw new ArgumentException("All REST Methods must return either Task<T> or IObservable<T>");
}
}
class FormValueDictionary : Dictionary<string, string>
{
static readonly Dictionary<Type, PropertyInfo[]> propertyCache
= new Dictionary<Type, PropertyInfo[]>();
public FormValueDictionary(object source)
{
if (source == null) return;
var dictionary = source as IDictionary;
if (dictionary != null) {
foreach (var key in dictionary.Keys) {
Add(key.ToString(), string.Format("{0}", dictionary[key]));
}
return;
}
var type = source.GetType();
lock (propertyCache) {
if (!propertyCache.ContainsKey(type)) {
propertyCache[type] = getProperties(type);
}
foreach (var property in propertyCache[type]) {
Add(getFieldNameForProperty(property), string.Format("{0}", property.GetValue(source, null)));
}
}
}
PropertyInfo[] getProperties(Type type)
{
return type.GetProperties()
.Where(p => p.CanRead)
.ToArray();
}
string getFieldNameForProperty(PropertyInfo propertyInfo)
{
var aliasAttr = propertyInfo.GetCustomAttributes(true)
.OfType<AliasAsAttribute>()
.FirstOrDefault();
return aliasAttr != null ? aliasAttr.Name : propertyInfo.Name;
}
}
class AuthenticatedHttpClientHandler : DelegatingHandler
{
readonly Func<Task<string>> getToken;
public AuthenticatedHttpClientHandler(Func<Task<string>> getToken, HttpMessageHandler innerHandler = null)
: base(innerHandler ?? new HttpClientHandler())
{
if (getToken == null) throw new ArgumentNullException("getToken");
this.getToken = getToken;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// See if the request has an authorize header
var auth = request.Headers.Authorization;
if (auth != null) {
var token = await getToken().ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using Newtonsoft.Json;
using System.IO;
using OneApi.Model;
using OneApi.Exceptions;
namespace OneApi.Config
{
public class Configuration
{
protected static readonly log4net.ILog LOGGER = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const string DEFAULT_CONFIG_FILE = "client.cfg";
private Authentication authentication = new Authentication();
private string apiUrl = "https://oneapi.infobip.com";
private int versionOneAPISMS = 1;
private int inboundMessagesRetrievingInterval = 5000;
private int dlrRetrievingInterval = 5000;
private int dlrStatusPushServerSimulatorPort = 3000;
private int inboundMessagesPushServerSimulatorPort = 3001;
private int hlrPushServerSimulatorPort = 3002;
/// <summary>
/// Initialize configuration object
/// </summary>
public Configuration()
{
}
/// <summary>
/// Initialize Configuration object ((load data from the 'client.cfg' configuration file)) </summary>
/// <param name="loadFromFile"> determines if data will be loaded from the default configuration file </param>
public Configuration(bool loadFromFile)
{
if (loadFromFile)
{
Load();
}
}
/// <summary>
/// Initialize configuration object using the 'BASIC' Authentication credentials (to use 'IBSSO' Authentication you need to call 'CustomerProfileClient.Login()' method after client initialization) </summary>
/// <param name="username"> - 'BASIC' Authentication user name </param>
/// <param name="password"> - 'BASIC' Authentication password </param>
public Configuration(string username, string password)
{
authentication.Username = username;
authentication.Password = password;
authentication.Type = OneApi.Model.Authentication.AuthType.BASIC;
}
/// <summary>
/// Initialize configuration object using the 'OAuth' Authentication </summary>
/// <param name="accessToken"> - 'OAuth' Authentication Access Token </param>
public Configuration(string accessToken)
{
authentication.AccessToken = accessToken;
authentication.Type = OneApi.Model.Authentication.AuthType.OAUTH;
}
/// <summary>
/// Initialize configuration object using the 'IBSSO' Authentication credentials </summary>
/// <param name="messagingBaseUrl"> - Base URL containing host name and port of the OneAPI SMS server </param>
/// <param name="versionOneAPISMS"> - Version of OneAPI SMS you are accessing (the default is the latest version supported by that server) </param>
/// <param name="username"> - 'IBSSO' Authentication user name </param>
/// <param name="password"> - 'IBSSO' Authentication password </param>
public Configuration(string messagingBaseUrl, int versionOneAPISMS, string username, string password) : this(username, password)
{
this.apiUrl = messagingBaseUrl;
this.versionOneAPISMS = versionOneAPISMS;
}
/// <summary>
/// Initialize configuration object using the 'OAuth' Authentication </summary>
/// <param name="messagingBaseUrl"> - Base URL containing host name and port of the OneAPI SMS server </param>
/// <param name="versionOneAPISMS"> - Version of OneAPI SMS you are accessing (the default is the latest version supported by that server) </param>
/// <param name="accessToken"> - 'OAuth' Authentication Access Token </param>
public Configuration(string messagingBaseUrl, int versionOneAPISMS, string accessToken) : this(accessToken)
{
this.apiUrl = messagingBaseUrl;
this.versionOneAPISMS = versionOneAPISMS;
}
/// <summary>
/// Load data from the default configuration file (client.cfg)
/// </summary>
public void Load()
{
Load("");
}
/// <summary>
/// Load data from the configuration file
/// </summary>
public void Load(string configFilePath)
{
try
{
if (configFilePath.Trim().Length == 0) {
configFilePath = DEFAULT_CONFIG_FILE;
}
StreamReader sr = new StreamReader(configFilePath);
string json = sr.ReadToEnd();
sr.Close();
Configuration tmpConfig = JsonConvert.DeserializeObject<Configuration>(json);
authentication = tmpConfig.authentication;
apiUrl = tmpConfig.apiUrl;
versionOneAPISMS = tmpConfig.versionOneAPISMS;
inboundMessagesRetrievingInterval = tmpConfig.inboundMessagesRetrievingInterval;
dlrRetrievingInterval = tmpConfig.dlrRetrievingInterval;
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Data successfully loaded from '" + DEFAULT_CONFIG_FILE + "' configuration file.");
}
}
catch (Exception e)
{
throw new ConfigurationException(e);
}
}
/// <summary>
/// Save data to the default configuration file (client.cfg)
/// </summary>
public void Save()
{
Save("");
}
/// <summary>
/// Save data to the configuration file
/// </summary>
public void Save(string configFilePath)
{
try
{
if (configFilePath.Trim().Length == 0)
{
configFilePath = DEFAULT_CONFIG_FILE;
}
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
StreamWriter sw = new StreamWriter(configFilePath);
sw.Write(json);
sw.Close();
if (LOGGER.IsInfoEnabled)
{
LOGGER.Info("Data successfully saved to '" + DEFAULT_CONFIG_FILE + "' configuration file.");
}
}
catch (Exception e)
{
throw new ConfigurationException(e);
}
}
/// <summary>
/// Object containing 'OneAPI' Authentication data </summary>
/// <returns> Authentication </returns>
[JsonProperty(PropertyName = "authentication")]
public Authentication Authentication
{
get
{
return authentication;
}
set
{
this.authentication = value;
}
}
/// <summary>
/// Base URL containing host name and port of the OneAPI SMS server </summary>
/// <returns> messagingBaseUrl </returns>
[JsonProperty(PropertyName = "apiUrl")]
public string ApiUrl
{
get
{
return apiUrl;
}
set
{
this.apiUrl = value;
}
}
/// <summary>
/// Version of OneAPI SMS you are accessing (the default is the latest version supported by that server) </summary>
/// <returns> versionOneAPISMS </returns>
[JsonProperty(PropertyName = "versionOneAPISMS")]
public int VersionOneAPISMS
{
get
{
return versionOneAPISMS;
}
set
{
this.versionOneAPISMS = value;
}
}
/// <summary>
/// Interval to automatically pool inbounds messages in milliseconds </summary>
/// <returns> inboundMessagesRetrievingInterval </returns>
[JsonProperty(PropertyName = "inboundMessagesRetrievingInterval")]
public int InboundMessagesRetrievingInterval
{
get
{
return inboundMessagesRetrievingInterval;
}
set
{
this.inboundMessagesRetrievingInterval = value;
}
}
/// <summary>
/// Interval to automatically pool delivery reports in milliseconds </summary>
/// <returns> dlrRetrievingInterval </returns>
[JsonProperty(PropertyName = "dlrRetrievingInterval")]
public int DlrRetrievingInterval
{
get
{
return dlrRetrievingInterval;
}
set
{
this.dlrRetrievingInterval = value;
}
}
/// <summary>
/// Delivery Notification Status Push server port (default = 3000) </summary>
/// <returns> dlrStatusPushServerSimulatorPort </returns>
[JsonProperty(PropertyName = "dlrStatusPushServerSimulatorPort")]
public int DlrStatusPushServerPort
{
get
{
return dlrStatusPushServerSimulatorPort;
}
set
{
this.dlrStatusPushServerSimulatorPort = value;
}
}
/// <summary>
/// Inbound Messages Notifications Push server port (default = 3001) </summary>
/// <returns> inboundMessagesPushServerSimulatorPort </returns>
[JsonProperty(PropertyName = "inboundMessagesPushServerSimulatorPort")]
public int InboundMessagesPushServerSimulatorPort
{
get
{
return inboundMessagesPushServerSimulatorPort;
}
set
{
this.inboundMessagesPushServerSimulatorPort = value;
}
}
/// <summary>
/// Hlr Notifications Push server port (default = 3002) </summary>
/// <returns> hlrPushServerSimulatorPort </returns>
[JsonProperty(PropertyName = "hlrPushServerSimulatorPort")]
public int HlrPushServerSimulatorPort
{
get
{
return hlrPushServerSimulatorPort;
}
set
{
this.hlrPushServerSimulatorPort = value;
}
}
}
}
| |
/*
Myrtille: A native HTML4/5 Remote Desktop Protocol client.
Copyright(c) 2014-2021 Cedric Coste
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.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Myrtille.Helpers;
using Myrtille.PdfScribe;
namespace Myrtille.Services
{
[RunInstaller(true)]
public class ServicesInstaller : Installer
{
public override void Install(
IDictionary stateSaver)
{
// enable the line below to debug this installer; disable otherwise
//MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug");
// if the installer is running in repair mode, it will try to re-install Myrtille... which is fine
// problem is, it won't uninstall it first... which is not fine because some components can't be installed twice!
// thus, prior to any install, try to uninstall first
Context.LogMessage("Myrtille.Services is being installed, cleaning first");
try
{
Uninstall(null);
}
catch (Exception exc)
{
Context.LogMessage(string.Format("Failed to clean Myrtille.Services ({0})", exc));
}
Context.LogMessage("Installing Myrtille.Services");
base.Install(stateSaver);
try
{
var process = new Process();
bool debug = true;
#if !DEBUG
debug = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
#endif
process.StartInfo.FileName = string.Format(@"{0}\WindowsPowerShell\v1.0\powershell.exe", Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess ? Environment.SystemDirectory.ToLower().Replace("system32", "sysnative") : Environment.SystemDirectory);
process.StartInfo.Arguments = "-ExecutionPolicy Bypass" +
" -Command \"& '" + Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin", "Myrtille.Services.Install.ps1") + "'" +
" -BinaryPath '" + Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin", "Myrtille.Services.exe") + "'" +
" -DebugMode " + (debug ? "1" : "0") +
" | Tee-Object -FilePath '" + Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log", "Myrtille.Services.Install.log") + "'" + "\"";
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception(string.Format("An error occured while running {0}. See {1} for more information.",
Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin", "Myrtille.Services.Install.ps1"),
Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log", "Myrtille.Services.Install.log")));
}
// load config
var config = new XmlDocument();
var configPath = Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin", "Myrtille.Services.exe.config");
config.Load(configPath);
var navigator = config.CreateNavigator();
// services port
int servicesPort = 8080;
if (!string.IsNullOrEmpty(Context.Parameters["SERVICESPORT"]))
{
int.TryParse(Context.Parameters["SERVICESPORT"], out servicesPort);
}
if (servicesPort != 8080)
{
// services endpoints
var services = XmlTools.GetNode(navigator, "/configuration/system.serviceModel/services");
if (services != null)
{
services.InnerXml = services.InnerXml.Replace("8080", servicesPort.ToString());
}
}
// multifactor authentication
string oasisApiKey = null;
if (!string.IsNullOrEmpty(Context.Parameters["OASISAPIKEY"]))
{
oasisApiKey = Context.Parameters["OASISAPIKEY"];
}
string oasisAppKey = null;
if (!string.IsNullOrEmpty(Context.Parameters["OASISAPPKEY"]))
{
oasisAppKey = Context.Parameters["OASISAPPKEY"];
}
string oasisAppId = null;
if (!string.IsNullOrEmpty(Context.Parameters["OASISAPPID"]))
{
oasisAppId = Context.Parameters["OASISAPPID"];
}
// enterprise mode
string enterpriseAdminGroup = null;
if (!string.IsNullOrEmpty(Context.Parameters["ENTERPRISEADMINGROUP"]))
{
enterpriseAdminGroup = Context.Parameters["ENTERPRISEADMINGROUP"];
}
string enterpriseDomain = null;
if (!string.IsNullOrEmpty(Context.Parameters["ENTERPRISEDOMAIN"]))
{
enterpriseDomain = Context.Parameters["ENTERPRISEDOMAIN"];
}
string enterpriseNetbiosDomain = null;
if (!string.IsNullOrEmpty(Context.Parameters["ENTERPRISENETBIOSDOMAIN"]))
{
enterpriseNetbiosDomain = Context.Parameters["ENTERPRISENETBIOSDOMAIN"];
}
// app settings
var appSettings = XmlTools.GetNode(navigator, "/configuration/appSettings");
if (appSettings != null)
{
// MFAAuthAdapter
if (!string.IsNullOrEmpty(oasisApiKey) && !string.IsNullOrEmpty(oasisAppKey) && !string.IsNullOrEmpty(oasisAppId))
{
XmlTools.UncommentConfigKey(config, appSettings, "MFAAuthAdapter");
XmlTools.WriteConfigKey(appSettings, "OASISApiKey", oasisApiKey);
XmlTools.WriteConfigKey(appSettings, "OASISAppKey", oasisAppKey);
XmlTools.WriteConfigKey(appSettings, "OASISAppID", oasisAppId);
}
// EnterpriseAdapter
if (!string.IsNullOrEmpty(enterpriseAdminGroup) && !string.IsNullOrEmpty(enterpriseDomain))
{
XmlTools.UncommentConfigKey(config, appSettings, "EnterpriseAdapter");
XmlTools.WriteConfigKey(appSettings, "EnterpriseAdminGroup", enterpriseAdminGroup);
XmlTools.WriteConfigKey(appSettings, "EnterpriseDomain", enterpriseDomain);
XmlTools.WriteConfigKey(appSettings, "EnterpriseNetbiosDomain", enterpriseNetbiosDomain);
}
}
// save config
config.Save(configPath);
// pdf printer
if (!string.IsNullOrEmpty(Context.Parameters["PDFPRINTER"]))
{
// install Myrtille PDF printer
var scribeInstaller = new PdfScribeInstaller(Context);
var printerDir = Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin");
var driversDir = Path.Combine(printerDir, Environment.Is64BitOperatingSystem ? "amd64" : "x86");
if (!scribeInstaller.InstallPdfScribePrinter(driversDir, Path.Combine(printerDir, "Myrtille.Printer.exe"), string.Empty))
{
MessageBox.Show(
ActiveWindow.Active,
"the myrtille virtual pdf printer could not be installed. Please check logs (into the install log folder)",
"Myrtille.Services",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
Context.LogMessage("Installed Myrtille.Services");
}
catch (Exception exc)
{
Context.LogMessage(string.Format("Failed to install Myrtille.Services ({0})", exc));
throw;
}
}
public override void Commit(
IDictionary savedState)
{
base.Commit(savedState);
// insert code as needed
}
public override void Rollback(
IDictionary savedState)
{
base.Rollback(savedState);
DoUninstall();
}
public override void Uninstall(
IDictionary savedState)
{
base.Uninstall(savedState);
DoUninstall();
}
private void DoUninstall()
{
// enable the line below to debug this installer; disable otherwise
//MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug");
Context.LogMessage("Uninstalling Myrtille.Services");
try
{
var process = new Process();
bool debug = true;
#if !DEBUG
debug = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
#endif
process.StartInfo.FileName = string.Format(@"{0}\WindowsPowerShell\v1.0\powershell.exe", Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess ? Environment.SystemDirectory.ToLower().Replace("system32", "sysnative") : Environment.SystemDirectory);
process.StartInfo.Arguments = "-ExecutionPolicy Bypass" +
" -Command \"& '" + Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin", "Myrtille.Services.Uninstall.ps1") + "'" +
" -DebugMode " + (debug ? "1" : "0") +
" | Tee-Object -FilePath '" + Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log", "Myrtille.Services.Uninstall.log") + "'" + "\"";
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception(string.Format("An error occured while running {0}. See {1} for more information.",
Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "bin", "Myrtille.Services.Uninstall.ps1"),
Path.Combine(Path.GetFullPath(Context.Parameters["targetdir"]), "log", "Myrtille.Services.Uninstall.log")));
}
// uninstall Myrtille PDF printer, if exists
var scribeInstaller = new PdfScribeInstaller(Context);
scribeInstaller.UninstallPdfScribePrinter();
Context.LogMessage("Uninstalled Myrtille.Services");
}
catch (Exception exc)
{
// in case of any error, don't rethrow the exception or myrtille won't be uninstalled otherwise (rollback action)
// if myrtille can't be uninstalled, it can't be re-installed either! (at least, with an installer of the same product code)
Context.LogMessage(string.Format("Failed to uninstall Myrtille.Services ({0})", exc));
}
}
}
}
| |
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("MegaShapes/Hose New")]
[RequireComponent(typeof(MeshFilter)), RequireComponent(typeof(MeshRenderer))]
public class MegaHoseNew : MonoBehaviour
{
public bool freecreate = true;
public bool updatemesh = true;
//Matrix4x4 S = Matrix4x4.identity;
const float HalfIntMax = 16383.5f;
const float PIover2 = 1.570796327f;
const float EPSILON = 0.0001f;
public MegaSpline hosespline = new MegaSpline();
Mesh mesh;
public Vector3[] verts = new Vector3[1];
public Vector2[] uvs = new Vector2[1];
public int[] faces = new int[1];
public Vector3[] normals;
public bool optimize = false;
public bool calctangents = false;
public bool recalcCollider = false;
public bool calcnormals = false;
public bool capends = true;
public GameObject custnode2;
public GameObject custnode;
public Vector3 offset = Vector3.zero;
public Vector3 offset1 = Vector3.zero;
public Vector3 rotate = Vector3.zero;
public Vector3 rotate1 = Vector3.zero;
public Vector3 scale = Vector3.one;
public Vector3 scale1 = Vector3.one;
public int endsmethod = 0;
public float noreflength = 1.0f;
public int segments = 45;
public MegaHoseSmooth smooth = MegaHoseSmooth.SMOOTHALL;
public MegaHoseType wiretype = MegaHoseType.Round;
public float rnddia = 0.2f;
public int rndsides = 8;
public float rndrot = 0.0f;
public float rectwidth = 0.2f;
public float rectdepth = 0.2f;
public float rectfillet = 0.0f;
public int rectfilletsides = 0;
public float rectrotangle = 0.0f;
public float dsecwidth = 0.2f;
public float dsecdepth = 0.2f;
public float dsecfillet = 0.0f;
public int dsecfilletsides = 0;
public int dsecrndsides = 4;
public float dsecrotangle = 0.0f;
public bool mapmemapme = true;
public bool flexon = false;
public float flexstart = 0.1f;
public float flexstop = 0.9f;
public int flexcycles = 5;
public float flexdiameter = -0.2f;
public float tension1 = 10.0f;
public float tension2 = 10.0f;
public bool usebulgecurve = false;
public AnimationCurve bulge = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
public float bulgeamount = 1.0f;
public float bulgeoffset = 0.0f;
public Vector2 uvscale = Vector2.one;
public bool animatebulge = false;
public float bulgespeed = 0.0f;
public float minbulge = -1.0f;
public float maxbulge = 2.0f;
public bool usesizecurve = false;
public AnimationCurve size = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1));
public bool displayspline = true;
bool visible = true;
public bool InvisibleUpdate = false;
public bool dolateupdate = false;
[ContextMenu("Help")]
public void Help()
{
Application.OpenURL("http://www.west-racing.com/mf/?page_id=3436");
}
void Awake()
{
updatemesh = true;
rebuildcross = true;
Rebuild();
}
void Reset()
{
Rebuild();
}
void OnBecameVisible()
{
visible = true;
}
void OnBecameInvisible()
{
visible = false;
}
public void SetEndTarget(int end, GameObject target)
{
if ( end == 0 )
{
custnode = target;
}
else
{
custnode2 = target;
}
updatemesh = true;
}
public void Rebuild()
{
MeshFilter mf = GetComponent<MeshFilter>();
if ( mf != null )
{
Mesh mesh = mf.sharedMesh; //Utils.GetMesh(gameObject);
if ( mesh == null )
{
mesh = new Mesh();
mf.sharedMesh = mesh;
}
if ( mesh != null )
{
BuildMesh();
}
//updatemesh = false;
}
}
void MakeSaveVertex(int NvertsPerRing, int nfillets, int nsides, MegaHoseType wtype)
{
if ( wtype == MegaHoseType.Round )
{
//Debug.Log("Verts " + NvertsPerRing);
float ang = (Mathf.PI * 2.0f) / (float)(NvertsPerRing - 1);
float diar = rnddia;
diar *= 0.5f;
for ( int i = 0; i < NvertsPerRing; i++ )
{
float u = (float)(i + 1) * ang;
SaveVertex[i] = new Vector3(diar * (float)Mathf.Cos(u), diar * (float)Mathf.Sin(u), 0.0f);
}
}
else
{
if ( wtype == MegaHoseType.Rectangle )
{
int savevertcnt = 0;
int qtrverts = 1 + nfillets;
int hlfverts = 2 * qtrverts;
int thrverts = qtrverts + hlfverts;
float Wr = rectwidth * 0.5f;
float Dr = rectdepth * 0.5f;
float Zfr = rectfillet;
if ( Zfr < 0.0f )
Zfr = 0.0f;
if ( nfillets > 0 )
{
float WmZ = Wr - Zfr, DmZ = Dr - Zfr;
float ZmW = -WmZ, ZmD = -DmZ;
SaveVertex[0] = new Vector3(Wr , DmZ, 0.0f);
SaveVertex[nfillets] = new Vector3(WmZ, Dr , 0.0f);
SaveVertex[qtrverts] = new Vector3(ZmW, Dr , 0.0f);
SaveVertex[qtrverts + nfillets] = new Vector3(-Wr, DmZ, 0.0f);
SaveVertex[hlfverts] = new Vector3(-Wr, ZmD, 0.0f);
SaveVertex[hlfverts + nfillets] = new Vector3(ZmW, -Dr, 0.0f);
SaveVertex[thrverts] = new Vector3(WmZ, -Dr, 0.0f);
SaveVertex[thrverts + nfillets] = new Vector3(Wr , ZmD, 0.0f);
if ( nfillets > 1 )
{
float ang = PIover2 / (float)nfillets;
savevertcnt = 1;
for ( int i = 0; i < nfillets - 1; i++ )
{
float u = (float)(i + 1) * ang;
float cu = Zfr * Mathf.Cos(u), su = Zfr * Mathf.Sin(u);
SaveVertex[savevertcnt] = new Vector3(WmZ + cu, DmZ + su, 0.0f);
SaveVertex[savevertcnt + qtrverts] = new Vector3(ZmW - su, DmZ + cu, 0.0f);
SaveVertex[savevertcnt + hlfverts] = new Vector3(ZmW - cu, ZmD - su, 0.0f);
SaveVertex[savevertcnt + thrverts] = new Vector3(WmZ + su, ZmD - cu, 0.0f);
savevertcnt++;
}
}
SaveVertex[SaveVertex.Length - 1] = SaveVertex[0];
}
else
{
if ( smooth == MegaHoseSmooth.SMOOTHNONE )
{
SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(-Wr, Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(-Wr, Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(-Wr, -Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(-Wr, -Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(Wr, -Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(Wr, -Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f);
}
else
{
SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(-Wr, Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(-Wr, -Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(Wr, -Dr, 0.0f);
SaveVertex[savevertcnt++] = new Vector3(Wr, Dr, 0.0f);
}
}
}
else
{
int savevertcnt = 0;
float sang = Mathf.PI / (float)nsides;
float Wr = dsecwidth * 0.5f;
float Dr = dsecdepth * 0.5f;
float Zfr = dsecfillet;
if ( Zfr < 0.0f )
Zfr = 0.0f;
float LeftCenter = Dr-Wr;
if ( nfillets > 0 )
{
float DmZ = Dr-Zfr,
ZmD = -DmZ,
WmZ = Wr-Zfr;
int oneqtrverts = 1 + nfillets;
int threeqtrverts = oneqtrverts + 1 + nsides;
SaveVertex[0] = new Vector3(Wr , DmZ, 0.0f);
SaveVertex[nfillets] = new Vector3(WmZ, Dr , 0.0f);
SaveVertex[oneqtrverts] = new Vector3(LeftCenter, Dr, 0.0f);
SaveVertex[oneqtrverts + nsides] = new Vector3(LeftCenter, -Dr, 0.0f);
SaveVertex[threeqtrverts] = new Vector3(WmZ, -Dr , 0.0f);
SaveVertex[threeqtrverts + nfillets] = new Vector3(Wr, ZmD, 0.0f);
if ( nfillets > 1 )
{
float ang = PIover2 / (float)nfillets;
savevertcnt = 1;
for ( int i = 0; i < nfillets - 1; i++ )
{
float u = (float)(i + 1) * ang;
float cu = Zfr * Mathf.Cos(u);
float su = Zfr * Mathf.Sin(u);
SaveVertex[savevertcnt] = new Vector3(WmZ + cu, DmZ + su, 0.0f);
SaveVertex[savevertcnt+threeqtrverts] = new Vector3(WmZ + su, ZmD - cu, 0.0f);
savevertcnt++;
}
}
savevertcnt = 1 + oneqtrverts;
for ( int i = 0; i < nsides - 1; i++ )
{
float u = (float)(i + 1) * sang;
float cu = Dr * Mathf.Cos(u);
float su = Dr * Mathf.Sin(u);
SaveVertex[savevertcnt] = new Vector3(LeftCenter - su, cu, 0.0f);
savevertcnt++;
}
}
else
{
SaveVertex[savevertcnt] = new Vector3(Wr, Dr, 0.0f);
savevertcnt++;
SaveVertex[savevertcnt] = new Vector3(LeftCenter, Dr, 0.0f);
savevertcnt++;
for ( int i = 0; i < nsides - 1; i++ )
{
float u = (float)(i + 1) * sang;
float cu = Dr * Mathf.Cos(u);
float su = Dr * Mathf.Sin(u);
SaveVertex[savevertcnt] = new Vector3(LeftCenter - su, cu, 0.0f);
savevertcnt++;
}
SaveVertex[savevertcnt] = new Vector3(LeftCenter, -Dr, 0.0f);
savevertcnt++;
SaveVertex[savevertcnt] = new Vector3(Wr, -Dr, 0.0f);
savevertcnt++;
}
SaveVertex[SaveVertex.Length - 1] = SaveVertex[0];
}
}
// UVs
float dist = 0.0f;
Vector3 last = Vector3.zero;
for ( int i = 0; i < NvertsPerRing; i++ )
{
if ( i > 0 )
dist += (SaveVertex[i] - last).magnitude;
SaveUV[i] = new Vector2(0.0f, dist * uvscale.y);
last = SaveVertex[i];
}
for ( int i = 0; i < NvertsPerRing; i++ )
SaveUV[i].y /= dist;
float rotangle = 0.0f;
switch ( wtype )
{
case MegaHoseType.Round: rotangle = rndrot; break;
case MegaHoseType.Rectangle: rotangle = rectrotangle; break;
case MegaHoseType.DSection: rotangle = dsecrotangle; break;
}
if ( rotangle != 0.0f )
{
rotangle *= Mathf.Deg2Rad;
float cosu = Mathf.Cos(rotangle);
float sinu = Mathf.Sin(rotangle);
for ( int m = 0; m < NvertsPerRing; m++ )
{
float tempx = SaveVertex[m].x * cosu - SaveVertex[m].y * sinu;
float tempy = SaveVertex[m].x * sinu + SaveVertex[m].y * cosu;
SaveVertex[m].x = tempx;
SaveVertex[m].y = tempy;
}
}
// Normals
if ( calcnormals )
{
for ( int i = 0; i < NvertsPerRing; i++ )
{
int ii = (i + 1) % NvertsPerRing;
Vector3 delta = (SaveVertex[ii] - SaveVertex[i]).normalized;
SaveNormals[i] = new Vector3(delta.y, -delta.x, 0.0f);
}
}
}
void FixHoseFillet()
{
float width = rectwidth;
float height = rectdepth;
float fillet = rectfillet;
float hh = 0.5f * Mathf.Abs(height);
float ww = 0.5f * Mathf.Abs(width);
float maxf = (hh > ww ? ww : hh);
if ( fillet > maxf )
rectfillet = maxf;
}
float RND11()
{
float num = Random.Range(0.0f, 32768.0f) - HalfIntMax;
return (num / HalfIntMax);
}
void Mult1X3(Vector3 A, Matrix4x4 B, ref Vector3 C)
{
C[0] = A[0] * B[0, 0] + A[1] * B[0, 1] + A[2] * B[0, 2];
C[1] = A[0] * B[1, 0] + A[1] * B[1, 1] + A[2] * B[1, 2];
C[2] = A[0] * B[2, 0] + A[1] * B[2, 1] + A[2] * B[2, 2];
}
void Mult1X4(Vector4 A, Matrix4x4 B, ref Vector4 C)
{
C[0] = A[0] * B[0, 0] + A[1] * B[0, 1] + A[2] * B[0, 2] + A[3] * B[0, 3];
C[1] = A[0] * B[1, 0] + A[1] * B[1, 1] + A[2] * B[1, 2] + A[3] * B[1, 3];
C[2] = A[0] * B[2, 0] + A[1] * B[2, 1] + A[2] * B[2, 2] + A[3] * B[2, 3];
C[3] = A[0] * B[3, 0] + A[1] * B[3, 1] + A[2] * B[3, 2] + A[3] * B[3, 3];
}
void SetUpRotation(Vector3 Q, Vector3 W, float Theta, ref Matrix4x4 Rq)
{
float ww1,ww2,ww3,w12,w13,w23,CosTheta,SinTheta,MinCosTheta;
Vector3 temp = Vector3.zero;
Matrix4x4 R = Matrix4x4.identity;
ww1 = W[0] * W[0];
ww2 = W[1] * W[1];
ww3 = W[2] * W[2];
w12 = W[0] * W[1];
w13 = W[0] * W[2];
w23 = W[1] * W[2];
CosTheta = Mathf.Cos(Theta);
MinCosTheta = 1.0f - CosTheta;
SinTheta = Mathf.Sin(Theta);
R[0, 0] = ww1 + (1.0f - ww1) * CosTheta;
R[1, 0] = w12 * MinCosTheta + W[2] * SinTheta;
R[2, 0] = w13 * MinCosTheta - W[1] * SinTheta;
R[0, 1] = w12 * MinCosTheta - W[2] * SinTheta;
R[1, 1] = ww2 + (1.0f - ww2) * CosTheta;
R[2, 1] = w23 * MinCosTheta + W[0] * SinTheta;
R[0, 2] = w13 * MinCosTheta + W[1] * SinTheta;
R[1, 2] = w23 * MinCosTheta - W[0] * SinTheta;
R[2, 2] = ww3 + (1.0f - ww3) * CosTheta;
Mult1X3(Q, R, ref temp);
Rq.SetColumn(0, R.GetColumn(0));
Rq.SetColumn(1, R.GetColumn(1));
Rq.SetColumn(2, R.GetColumn(2));
Rq[0, 3] = Q[0] - temp.x;
Rq[1, 3] = Q[1] - temp.y;
Rq[2, 3] = Q[2] - temp.z;
Rq[3, 0] = Rq[3, 1] = Rq[3, 2] = 0.0f;
Rq[3, 3] = 1.0f;
}
void RotateOnePoint(ref Vector3 Pin, Vector3 Q, Vector3 W, float Theta)
{
Matrix4x4 Rq = Matrix4x4.identity;
Vector4 Pout = Vector3.zero;
Vector4 Pby4;
SetUpRotation(Q, W, Theta, ref Rq);
Pby4 = Pin;
Pby4[3] = 1.0f;
Mult1X4(Pby4, Rq, ref Pout);
Pin = Pout;
}
Vector3 endp1 = Vector3.zero;
Vector3 endp2 = Vector3.zero;
Vector3 endr1 = Vector3.zero;
Vector3 endr2 = Vector3.zero;
public Vector3[] SaveVertex;
public Vector2[] SaveUV;
public Vector3[] SaveNormals;
public bool rebuildcross = true;
public int NvertsPerRing = 0;
public int Nverts = 0;
void Update()
{
if ( animatebulge )
{
if ( Application.isPlaying )
bulgeoffset += bulgespeed * Time.deltaTime;
if ( bulgeoffset > maxbulge )
bulgeoffset -= maxbulge - minbulge;
if ( bulgeoffset < minbulge )
bulgeoffset += maxbulge - minbulge;
updatemesh = true;
}
if ( custnode )
{
if ( custnode.transform.position != endp1 )
{
endp1 = custnode.transform.position;
updatemesh = true;
}
if ( custnode.transform.eulerAngles != endr1 )
{
endr1 = custnode.transform.eulerAngles;
updatemesh = true;
}
}
if ( custnode2 )
{
if ( custnode2.transform.position != endp2 )
{
endp1 = custnode2.transform.position;
updatemesh = true;
}
if ( custnode2.transform.eulerAngles != endr2 )
{
endr2 = custnode2.transform.eulerAngles;
updatemesh = true;
}
}
if ( !dolateupdate )
{
if ( visible || InvisibleUpdate )
{
// Check transforms so we dont update unless we have to
if ( updatemesh ) //|| Application.isEditor )
{
updatemesh = false;
BuildMesh();
}
}
}
}
void LateUpdate()
{
if ( dolateupdate )
{
if ( visible || InvisibleUpdate )
{
// Check transforms so we dont update unless we have to
if ( updatemesh ) //|| Application.isEditor )
{
updatemesh = false;
BuildMesh();
}
}
}
}
public Vector3 up = Vector3.up;
Vector3 starty = Vector3.zero;
public Matrix4x4 Tlocal = Matrix4x4.identity;
void CalcSpline()
{
Vector3 startvec, endvec, startpoint, endpoint; //, endy;
starty = custnode.transform.up; //TlocalInvNT.MultiplyPoint(starty);
Quaternion rot1 = custnode.transform.rotation * Quaternion.Euler(rotate);
Quaternion rot2 = custnode2.transform.rotation * Quaternion.Euler(rotate1);
startvec = tension1 * (rot1 * Vector3.forward);
endvec = tension2 * (rot2 * Vector3.forward);
startpoint = transform.worldToLocalMatrix.MultiplyPoint3x4(custnode.transform.position + custnode.transform.TransformDirection(offset)); //Vector3.zero;
endpoint = transform.worldToLocalMatrix.MultiplyPoint3x4(custnode2.transform.position + custnode2.transform.TransformDirection(offset1));
hosespline.knots[0].p = startpoint;
hosespline.knots[0].invec = startpoint - startvec;
hosespline.knots[0].outvec = startpoint + startvec;
hosespline.knots[1].p = endpoint;
hosespline.knots[1].invec = endpoint + endvec;
hosespline.knots[1].outvec = endpoint - endvec;
hosespline.CalcLength(); //10);
}
Matrix4x4 wtm1;
public Matrix4x4 GetSplineMat(MegaSpline spline, float alpha, bool interp, ref Vector3 lastup)
{
int k = -1;
Vector3 ps = spline.InterpCurve3D(alpha, interp, ref k);
alpha += 0.01f; // TODO: Tangent value
if ( spline.closed )
alpha = alpha % 1.0f;
Vector3 ps1 = spline.InterpCurve3D(alpha, interp, ref k);
Vector3 ps2;
ps1.x = ps2.x = ps1.x - ps.x;
ps1.y = ps2.y = ps1.y - ps.y;
ps1.z = ps2.z = ps1.z - ps.z;
MegaMatrix.SetTR(ref wtm1, ps, Quaternion.LookRotation(ps1, lastup)); //locup));
// calc new up value
ps2 = ps2.normalized;
Vector3 cross = Vector3.Cross(ps2, lastup);
lastup = Vector3.Cross(cross, ps2);
return wtm1;
}
// we only need to build the savevertex and uvs if mesh def changes, else we can keep the uvs
void BuildMesh()
{
if ( !mesh )
{
mesh = GetComponent<MeshFilter>().sharedMesh;
if ( mesh == null )
{
updatemesh = true;
return;
}
}
if ( hosespline.knots.Count == 0 )
{
hosespline.AddKnot(Vector3.zero, Vector3.zero, Vector3.zero);
hosespline.AddKnot(Vector3.zero, Vector3.zero, Vector3.zero);
}
FixHoseFillet();
bool createfree = freecreate;
if ( (!createfree) && ((!custnode) || (!custnode2)) )
createfree = true;
if ( custnode && custnode2 )
createfree = false;
float Lf = 0.0f;
Tlocal = Matrix4x4.identity;
starty = Vector3.zero;
if ( createfree )
Lf = noreflength;
else
{
starty = custnode.transform.up; //Vector3.up;
CalcSpline();
Lf = Vector3.Distance(custnode.transform.position, custnode2.transform.position);
}
MegaHoseType wtype = wiretype;
int Segs = segments;
if ( Segs < 3 )
Segs = 3;
if ( rebuildcross )
{
rebuildcross = false;
int nfillets = 0;
int nsides = 0;
if ( wtype == MegaHoseType.Round )
{
NvertsPerRing = rndsides;
if ( NvertsPerRing < 3 )
NvertsPerRing = 3;
}
else
{
if ( wtype == MegaHoseType.Rectangle )
{
nfillets = rectfilletsides;
if ( nfillets < 0 )
nfillets = 0;
if ( smooth == MegaHoseSmooth.SMOOTHNONE )
NvertsPerRing = (nfillets > 0 ? 8 + 4 * (nfillets - 1) : 8);
else
NvertsPerRing = (nfillets > 0 ? 8 + 4 * (nfillets - 1) : 4); //4);
}
else
{
nfillets = dsecfilletsides;
if ( nfillets < 0 )
nfillets = 0;
nsides = dsecrndsides;
if ( nsides < 2 )
nsides = 2;
int nsm1 = nsides - 1;
NvertsPerRing = (nfillets > 0 ? 6 + nsm1 + 2 * (nfillets - 1): 4 + nsm1);
}
}
NvertsPerRing++;
int NfacesPerEnd,NfacesPerRing,Nfaces = 0;
//MegaHoseSmooth SMOOTH = smooth;
Nverts = (Segs + 1) * (NvertsPerRing + 1); // + 2;
if ( capends )
Nverts += 2;
NfacesPerEnd = NvertsPerRing;
NfacesPerRing = 6 * NvertsPerRing;
Nfaces = Segs * NfacesPerRing; // + 2 * NfacesPerEnd;
if ( capends )
{
Nfaces += 2 * NfacesPerEnd;
}
if ( SaveVertex == null || SaveVertex.Length != NvertsPerRing )
{
SaveVertex = new Vector3[NvertsPerRing];
SaveUV = new Vector2[NvertsPerRing];
}
if ( calcnormals )
{
if ( SaveNormals == null || SaveNormals.Length != NvertsPerRing )
SaveNormals = new Vector3[NvertsPerRing];
}
MakeSaveVertex(NvertsPerRing, nfillets, nsides, wtype);
if ( verts == null || verts.Length != Nverts )
{
verts = new Vector3[Nverts];
uvs = new Vector2[Nverts];
faces = new int[Nfaces * 3];
}
if ( calcnormals && (normals == null || normals.Length != Nverts) )
normals = new Vector3[Nverts];
}
if ( Nverts == 0 )
return;
bool mapmenow = mapmemapme;
int thisvert = 0;
int last = Nverts - 1;
int last2 = last - 1;
int lastvpr = NvertsPerRing; // - 1;
int maxseg = Segs + 1;
float flexhere;
float dadjust;
float flexlen;
float flex1 = flexstart;
float flex2 = flexstop;
int flexn = flexcycles;
float flexd = flexdiameter;
Vector3 ThisPosition;
Vector2 uv = Vector2.zero;
Matrix4x4 RingTM = Matrix4x4.identity;
Matrix4x4 invRingTM = Matrix4x4.identity;
Vector3 lastup = starty;
float sizeadj = 1.0f;
for ( int i = 0; i < maxseg; i++ )
{
float incr = (float)i / (float)Segs;
if ( createfree )
ThisPosition = new Vector3(0.0f, 0.0f, Lf * incr);
else
{
int k = 0;
ThisPosition = hosespline.InterpCurve3D(incr, true, ref k);
}
RingTM = GetSplineMat(hosespline, incr, true, ref lastup);
if ( !createfree )
RingTM = Tlocal * RingTM;
if ( calcnormals )
{
invRingTM = RingTM;
MegaMatrix.NoTrans(ref invRingTM);
}
if ( (incr > flex1) && (incr < flex2) && flexon )
{
flexlen = flex2 - flex1;
if ( flexlen < 0.01f )
flexlen = 0.01f;
flexhere = (incr - flex1) / flexlen;
float ang = (float)flexn * flexhere * (Mathf.PI * 2.0f) + PIover2;
dadjust = 1.0f + flexd * (1.0f - Mathf.Sin(ang)); //(float)flexn * flexhere * (Mathf.PI * 2.0f) + PIover2));
}
else
dadjust = 0.0f;
if ( usebulgecurve )
{
if ( dadjust == 0.0f )
dadjust = 1.0f + (bulge.Evaluate(incr + bulgeoffset) * bulgeamount);
else
dadjust += bulge.Evaluate(incr + bulgeoffset) * bulgeamount;
}
if ( usesizecurve )
{
sizeadj = size.Evaluate(incr);
}
uv.x = 0.999999f * incr * uvscale.x;
for ( int j = 0; j < NvertsPerRing; j++ )
{
int jj = j; // % NvertsPerRing;
if ( mapmenow )
{
uv.y = SaveUV[jj].y;
uvs[thisvert] = uv; //new Vector2(0.999999f * incr * uvscale.x, SaveUV[jj].y);
}
if ( dadjust != 0.0f )
verts[thisvert] = RingTM.MultiplyPoint(sizeadj * dadjust * SaveVertex[jj]);
else
verts[thisvert] = RingTM.MultiplyPoint(sizeadj * SaveVertex[jj]);
if ( calcnormals )
normals[thisvert] = invRingTM.MultiplyPoint(SaveNormals[jj]).normalized; //.MultiplyPoint(-SaveNormals[jj]);
thisvert++;
}
if ( mapmenow )
{
//uvs[Nverts + i] = new Vector2(0.999999f * incr, 0.999f);
}
if ( capends )
{
if ( i == 0 )
{
verts[last2] = (createfree ? ThisPosition : Tlocal.MultiplyPoint(ThisPosition));
if ( mapmenow )
uvs[last2] = Vector3.zero;
}
else
{
if ( i == Segs )
{
verts[last] = createfree ? ThisPosition : Tlocal.MultiplyPoint(ThisPosition);
if ( mapmenow )
{
uvs[last] = Vector3.zero;
}
}
}
}
}
// Now, set up the faces
int thisface = 0, v1, v2, v3, v4;
v3 = last2;
if ( capends )
{
for ( int i = 0; i < NvertsPerRing - 1; i++ )
{
v1 = i;
v2 = (i < lastvpr ? v1 + 1 : v1 - lastvpr);
//v5 = (i < lastvpr ? v2 : Nverts);
faces[thisface++] = v2;
faces[thisface++] = v1;
faces[thisface++] = v3;
}
}
int ringnum = NvertsPerRing; // + 1;
for ( int i = 0; i < Segs; i++ )
{
for ( int j = 0; j < NvertsPerRing - 1; j++ )
{
v1 = i * ringnum + j;
v2 = v1 + 1; //(j < lastvpr? v1 + 1 : v1 - lastvpr);
v4 = v1 + ringnum;
v3 = v2 + ringnum;
faces[thisface++] = v1;
faces[thisface++] = v2;
faces[thisface++] = v3;
faces[thisface++] = v1;
faces[thisface++] = v3;
faces[thisface++] = v4;
}
}
int basevert = Segs * ringnum; //NvertsPerRing;
v3 = Nverts - 1;
if ( capends )
{
for ( int i = 0; i < NvertsPerRing - 1; i++ )
{
v1 = i + basevert;
v2 = (i < lastvpr? v1 + 1 : v1 - lastvpr);
//v5 = (i < lastvpr? v2 : Nverts + Segs);
faces[thisface++] = v1;
faces[thisface++] = v2;
faces[thisface++] = v3;
}
}
mesh.Clear();
mesh.subMeshCount = 1;
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = faces;
if ( calcnormals )
mesh.normals = normals;
else
mesh.RecalculateNormals();
mesh.RecalculateBounds();
#if UNITY_5_5 || UNITY_5_6 || UNITY_2017
#else
if ( optimize )
mesh.Optimize();
#endif
if ( calctangents )
{
MegaUtils.BuildTangents(mesh);
}
if ( recalcCollider )
{
if ( meshCol == null )
meshCol = GetComponent<MeshCollider>();
if ( meshCol != null )
{
meshCol.sharedMesh = null;
meshCol.sharedMesh = mesh;
//bool con = meshCol.convex;
//meshCol.convex = con;
}
}
}
public void CalcMatrix(ref Matrix4x4 mat, float incr)
{
mat = Tlocal; // * RingTM;
}
MeshCollider meshCol;
static float findmappos(float curpos)
{
float mappos;
return (mappos = ((mappos = curpos) < 0.0f ? 0.0f : (mappos > 1.0f ? 1.0f : mappos)));
}
void DisplayNormals()
{
}
public Vector3 GetPosition(float alpha)
{
Matrix4x4 RingTM = transform.localToWorldMatrix * Tlocal;
int k = 0;
return RingTM.MultiplyPoint(hosespline.InterpCurve3D(alpha, true, ref k));
}
}
| |
using System;
using System.Linq;
using System.Threading;
using CIAPI.DTO;
using CIAPI.RecordedTests.Infrastructure;
using CIAPI.Rpc;
using NUnit.Framework;
namespace CIAPI.RecordedTests
{
[TestFixture, MocumentModeOverride(MocumentMode.Play),Category("APIBUG")]
public class MarketFixture : CIAPIRecordingFixtureBase
{
[Test]
public void CanGetMarketTags()
{
var rpcClient = BuildRpcClient("CanGetMarketTags");
//Markets are grouped into a collection of tags.
//You can get a list of available tags from TagLookup
var tagResponse = rpcClient.Market.TagLookup();
Assert.IsTrue(tagResponse.Tags.Length > 0, "No tags have been defined for your user's account operator");
Console.WriteLine(tagResponse.ToStringWithValues());
/* Gives something like:
* MarketInformationTagLookupResponseDTO:
Tags=ApiPrimaryMarketTagDTO:
Children=ApiMarketTagDTO:
MarketTagId=8 Name=FX Majors Type=2
ApiMarketTagDTO:
MarketTagId=9 Name=FX Minors Type=2
ApiMarketTagDTO:
MarketTagId=14 Name=Euro Crosses Type=2
ApiMarketTagDTO:
MarketTagId=15 Name=Sterling Crosses Type=2
MarketTagId=7 Name=Currencies Type=1
ApiPrimaryMarketTagDTO:
Children=ApiMarketTagDTO:
MarketTagId=17 Name=Popular Type=2
MarketTagId=16 Name=FX Type=1
*/
}
[Test]
public void CanSearchWithTags()
{
var rpcClient = BuildRpcClient("CanSearchWithTags");
var tagResponse = rpcClient.Market.TagLookup();
Assert.IsTrue(tagResponse.Tags.Length > 0, "No tags have been defined for your user's account operator");
//Once you have a tag, you can search for all markets associated with that tag
int tagId = tagResponse.Tags.First(t => t.Name.Contains("FX")).MarketTagId;
var allMarketsInTag = rpcClient.Market.SearchWithTags("", tagId, true, true, true, true, true, true, 100, false);
Console.WriteLine(allMarketsInTag.ToStringWithValues());
/* Gives something like:
* MarketInformationSearchWithTagsResponseDTO:
Markets=ApiMarketDTO:
MarketId=400481134 Name=EUR/USD
ApiMarketDTO:
MarketId=400481136 Name=GBP/AUD
ApiMarketDTO:
MarketId=400481139 Name=GBP/JPY
ApiMarketDTO:
MarketId=400481142 Name=GBP/USD
Tags=ApiMarketTagDTO:
MarketTagId=8 Name=FX Majors Type=2
ApiMarketTagDTO:
MarketTagId=9 Name=FX Minors Type=2
ApiMarketTagDTO:
MarketTagId=14 Name=Euro Crosses Type=2
ApiMarketTagDTO:
MarketTagId=15 Name=Sterling Crosses Type=2
*/
//Or, you can search for all markets in that tag that start with a specific string
var allMarketsInTagContainingGBP = rpcClient.Market.SearchWithTags("GBP", tagId, true, true, true, true, true, true, 100, false);
Console.WriteLine(allMarketsInTagContainingGBP.ToStringWithValues());
/* Gives something like:
* MarketInformationSearchWithTagsResponseDTO:
Markets=ApiMarketDTO:
MarketId=400481136 Name=GBP/AUD
ApiMarketDTO:
MarketId=400481139 Name=GBP/JPY
ApiMarketDTO:
MarketId=400481142 Name=GBP/USD
*/
}
[Test]
public void CanListMarketInformation()
{
var rpcClient = BuildRpcClient("CanListMarketInformation");
var marketList = GetAvailableCFDMarkets(rpcClient);
var response = rpcClient.Market.ListMarketInformation(
new ListMarketInformationRequestDTO
{
MarketIds = marketList.ToList().Select(m => m.MarketId).ToArray()
}
);
Assert.AreEqual(marketList.Length, response.MarketInformation.Length);
rpcClient.LogOut();
}
[Test]
public void ListMarketInformationSearchQueryIsValidated()
{
var rpcClient = BuildRpcClient("ListMarketInformationSearchQueryIsValidated");
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, "/", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, "\\", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, @"\", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, @"GBP \ USD", 100, false);
rpcClient.Market.ListMarketInformationSearch(false, true, true, false, false, true, @"GBP \\ USD", 100, false);
var gate = new AutoResetEvent(false);
rpcClient.Market.BeginListMarketInformationSearch(false, true, true, false, false, true, @"\", 100, false, ar =>
{
var response = rpcClient.Market.EndListMarketInformationSearch(ar);
gate.Set();
}, null);
if (!gate.WaitOne(10000))
{
throw new TimeoutException();
}
rpcClient.LogOut();
}
[Test]
public void CanListMarketInformationSearch()
{
var rpcClient = BuildRpcClient("CanListMarketInformationSearch");
var response = rpcClient.Market.ListMarketInformationSearch(false, true, false, true, false, true, "GBP", 10, false);
Assert.Greater(response.MarketInformation.Length, 1);
rpcClient.LogOut();
}
/// <summary>
/// Test showing issue #167 - https://github.com/cityindex/CIAPI.CS/issues/167 -
/// has stopped occuring
/// </summary>
[Test, Ignore("Long running")]
public void MultipleRequestsToCanGetMarketInformationShouldNotThrowAnyExceptions()
{
var rpcClient = BuildRpcClient("MultipleRequestsToCanGetMarketInformationShouldNotThrowAnyExceptions");
for (var i = 0; i < 100; i++)
{
var response = rpcClient.Market.GetMarketInformation("154303");
Assert.That(response.MarketInformation.Name.Length, Is.GreaterThan(1));
Thread.Sleep(1100);
}
rpcClient.LogOut();
}
//
[Test]
public void CanGetMarketInformationWithPathChar()
{
var rpcClient = BuildRpcClient("CanGetMarketInformationWithPathChar");
var account = rpcClient.AccountInformation.GetClientAndTradingAccount();
var response = rpcClient.SpreadMarkets.ListSpreadMarkets("GBP/CAD", null, account.ClientAccountId, 19, false);
Assert.That(response.Markets.Length, Is.GreaterThan(1));
rpcClient.LogOut();
}
[Test]
public void CanGetMarketInformation()
{
var rpcClient = BuildRpcClient("CanGetMarketInformation");
var marketList = GetAvailableCFDMarkets(rpcClient);
var response = rpcClient.Market.GetMarketInformation(marketList[0].MarketId.ToString());
string stringWithValues = response.MarketInformation.ToStringWithValues();
Console.WriteLine(stringWithValues);
/* Returns data like the following (2012/04/27)
ApiMarketInformationDTO:
MarketId=154291 Name=GBP/AUD (per 0.0001) CFD MarginFactor=1.00000000 MinMarginFactor=NULL
MaxMarginFactor=NULL MarginFactorUnits=26 MinDistance=0.00 WebMinSize=1.00000000
MaxSize=2200.00000000 Market24H=True PriceDecimalPlaces=5 DefaultQuoteLength=180 TradeOnWeb=True
LimitUp=False LimitDown=False LongPositionOnly=False CloseOnly=False MarketEod=
PriceTolerance=10.00000000 ConvertPriceToPipsMultiplier=10000 MarketSettingsTypeId=2
MarketSettingsType=CFD MobileShortName=GBP/AUD CentralClearingType=No
CentralClearingTypeDescription=None MarketCurrencyId=1 PhoneMinSize=5.00000000
DailyFinancingAppliedAtUtc=26/04/2012 21:00:00 NextMarketEodTimeUtc=26/04/2012 21:00:00
TradingStartTimeUtc=NULL TradingEndTimeUtc=NULL
MarketPricingTimes=ApiTradingDayTimesDTO:
DayOfWeek=1 StartTimeUtc=26/04/2012 11:00:00 +00:00 EndTimeUtc=NULL
ApiTradingDayTimesDTO:
DayOfWeek=5 StartTimeUtc=NULL EndTimeUtc=28/04/2012 00:15:00 +00:00
MarketBreakTimes=
MarketSpreads=ApiMarketSpreadDTO:
SpreadTimeUtc=NULL Spread=0.00067000 SpreadUnits=27
GuaranteedOrderPremium=8.00 GuaranteedOrderPremiumUnits=1 GuaranteedOrderMinDistance=75.00 GuaranteedOrderMinDistanceUnits=27
*/
Assert.That(response.MarketInformation.Name.Length, Is.GreaterThan(1));
rpcClient.LogOut();
}
[Test]
public void CanSaveMarketInformation()
{
var rpcClient = BuildRpcClient("CanSaveMarketInformation");
var clientAccount = rpcClient.AccountInformation.GetClientAndTradingAccount();
var marketList = GetAvailableCFDMarkets(rpcClient);
var tolerances = new[]
{
new ApiMarketInformationSaveDTO
{
MarketId = marketList[0].MarketId,
PriceTolerance = 10
}
};
var saveMarketInfoRespnse = rpcClient.Market.SaveMarketInformation(new SaveMarketInformationRequestDTO()
{
MarketInformation = tolerances,
TradingAccountId = clientAccount.CFDAccount.TradingAccountId
});
// ApiSaveMarketInformationResponseDTO is devoid of properties, nothing to check as long as the call succeeds
}
public static ApiMarketInformationDTO[] GetAvailableCFDMarkets(Client rpcClient)
{
var marketList = rpcClient.Market.ListMarketInformationSearch(false, true, false, true, false, true, "GBP", 10, false);
Assert.That(marketList.MarketInformation.Length, Is.GreaterThanOrEqualTo(1), "There should be at least 1 CFD market availbe");
return marketList.MarketInformation;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
#if FLEXHTMLHELPER_MVC
using System.Web.Mvc;
using System;
#else
using System.Web.WebPages;
#endif
namespace FlexHtmlHelper
{
public class DefaultRender : IFlexRender
{
public virtual string Name
{
get
{
return "Default";
}
}
#region Helper
public virtual FlexTagBuilder LabelHelper(FlexTagBuilder tagBuilder, string @for, string text, IDictionary<string, object> htmlAttributes = null)
{
FlexTagBuilder tag = new FlexTagBuilder("label");
tag.TagAttributes.Add("for", @for);
tag.AddText(text);
tag.MergeAttributes(htmlAttributes, replaceExisting: true);
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder FormHelper(FlexTagBuilder tagBuilder, string tagName, string formAction, string formMethod, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("form");
tag.MergeAttributes(htmlAttributes);
// action is implicitly generated, so htmlAttributes take precedence.
tag.MergeAttribute("action", formAction);
// method is an explicit parameter, so it takes precedence over the htmlAttributes.
tag.MergeAttribute("method", formMethod, true);
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder CheckBoxHelper(FlexTagBuilder tagBuilder, string name, string @checked, string value, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("input");
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("type", "checkbox");
tag.MergeAttribute("name", name, true);
if (!string.IsNullOrEmpty(@checked))
{
tag.MergeAttribute(@checked, null);
}
tag.MergeAttribute("value", value, false);
tag.GenerateId(name);
tagBuilder.AddTag(tag);
FlexTagBuilder hiddenInput = new FlexTagBuilder("input");
hiddenInput.MergeAttribute("type", "hidden");
hiddenInput.MergeAttribute("name", name);
hiddenInput.MergeAttribute("value", "false");
tagBuilder.AddTag(hiddenInput);
return tagBuilder;
}
public virtual FlexTagBuilder HiddenHelper(FlexTagBuilder tagBuilder, string name, string value, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("input");
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("type", "hidden");
tag.MergeAttribute("name", name, true);
tag.MergeAttribute("value", value, true);
tag.GenerateId(name);
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder PasswordHelper(FlexTagBuilder tagBuilder, string name, string value, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("input");
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("type", "password");
tag.MergeAttribute("name", name, true);
if (value != null)
{
tag.MergeAttribute("value", value, true);
}
tag.GenerateId(name);
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder RadioHelper(FlexTagBuilder tagBuilder, string name, string @checked, string value, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("input");
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("type", "radio");
tag.MergeAttribute("name", name, true);
if (!string.IsNullOrEmpty(@checked))
{
tag.MergeAttribute(@checked, null);
}
tag.MergeAttribute("value", value, true);
tag.GenerateId(name);
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder TextBoxHelper(FlexTagBuilder tagBuilder, string name, string value, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("input");
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("type", "text");
tag.MergeAttribute("name", name, true);
tag.MergeAttribute("value", value, true);
tag.GenerateId(name);
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder StaticHelper(FlexTagBuilder tagBuilder, string name, string value, IDictionary<string, object> htmlAttributes)
{
return tagBuilder;
}
public virtual FlexTagBuilder ValidationMessageHelper(FlexTagBuilder tagBuilder, string validationMessage, bool isValid, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("span");
tag.MergeAttributes(htmlAttributes);
if (validationMessage != null)
{
tag.AddText(validationMessage);
}
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder ValidationSummaryHelper(FlexTagBuilder tagBuilder, string validationMessage, IEnumerable<string> errorMessages, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("div");
tag.MergeAttributes(htmlAttributes);
if (string.IsNullOrEmpty(validationMessage))
{
FlexTagBuilder messageSpan = tag.AddTag("span");
messageSpan.AddText(validationMessage);
}
FlexTagBuilder errorList = tag.AddTag("ul");
if (errorMessages.Count() > 0)
{
foreach (var m in errorMessages)
{
errorList.AddTag("li").AddText(m);
}
}
else
{
errorList.AddTag("li").MergeAttribute("display", "none;");
}
tagBuilder.AddTag(tag);
return tag;
}
public virtual FlexTagBuilder FormGroupHelper(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder labelTag, FlexTagBuilder inputTag, FlexTagBuilder validationMessageTag)
{
return tagBuilder;
}
protected FlexTagBuilder ListItemToOption(SelectListItemEx item)
{
FlexTagBuilder tag = new FlexTagBuilder("option");
tag.AddText(item.Text);
if (item.Value != null)
{
tag.MergeAttribute("value", item.Value);
}
if (!string.IsNullOrEmpty(item.Selected))
{
tag.MergeAttribute(item.Selected, null);
}
return tag;
}
public virtual FlexTagBuilder SelectHelper(FlexTagBuilder tagBuilder, string optionLabel, string name, IEnumerable<SelectListItemEx> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("select");
// Make optionLabel the first item that gets rendered.
if (optionLabel != null)
{
tag.AddTag(ListItemToOption(new SelectListItemEx() { Text = optionLabel, Value = String.Empty, Selected = null }));
}
foreach (var item in selectList)
{
tag.AddTag(ListItemToOption(item));
}
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("name", name, true /* replaceExisting */);
tag.GenerateId(name);
if (allowMultiple)
{
tag.MergeAttribute("multiple", "multiple");
}
tagBuilder.AddTag(tag);
return tagBuilder;
}
public virtual FlexTagBuilder TextAreaHelper(FlexTagBuilder tagBuilder, string name, string value, IDictionary<string, object> rowsAndColumns, IDictionary<string, object> htmlAttributes, string innerHtmlPrefix = null)
{
FlexTagBuilder tag = new FlexTagBuilder("textarea");
tag.GenerateId(name);
tag.MergeAttributes(htmlAttributes, true);
tag.MergeAttributes(rowsAndColumns, true);
tag.MergeAttribute("name", name, true);
tag.AddText( (innerHtmlPrefix ?? Environment.NewLine) + value);
tagBuilder.AddTag(tag);
return tagBuilder;
}
public virtual FlexTagBuilder LinkHelper(FlexTagBuilder tagBuilder, string linkText, string url, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("a");
tag.AddText(linkText);
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("href", url);
tagBuilder.AddTag(tag);
return tagBuilder;
}
public virtual FlexTagBuilder ButtonHelper(FlexTagBuilder tagBuilder, string type, string text, string value, string name, IDictionary<string, object> htmlAttributes)
{
FlexTagBuilder tag = new FlexTagBuilder("button");
tag.AddText(text);
tag.MergeAttributes(htmlAttributes);
tag.MergeAttribute("type", type);
tag.MergeAttribute("value", value);
tag.MergeAttribute("name", name);
tagBuilder.AddTag(tag);
return tagBuilder;
}
public virtual FlexTagBuilder LinkButtonHelper(FlexTagBuilder tagBuilder)
{
return tagBuilder;
}
public virtual FlexTagBuilder PagingLinkHelper(FlexTagBuilder tagBuilder, int totalItemCount, int pageNumber, int pageSize, int maxPagingLinks, Func<int, string> pagingUrlResolver, IDictionary<string, object> htmlAttributes)
{
return tagBuilder;
}
public virtual FlexTagBuilder IconHelper(FlexTagBuilder tagBuilder, string name, IDictionary<string, object> htmlAttributes)
{
return tagBuilder;
}
public virtual FlexTagBuilder ModalHelper(FlexTagBuilder tagBuilder, string title, IDictionary<string, object> htmlAttributes)
{
return tagBuilder;
}
public virtual FlexTagBuilder ModalHeaderHelper(FlexTagBuilder tagBuilder, FlexTagBuilder header)
{
return tagBuilder;
}
public virtual FlexTagBuilder ModalBodyHelper(FlexTagBuilder tagBuilder, FlexTagBuilder body)
{
return tagBuilder;
}
public virtual FlexTagBuilder ModalFooterHelper(FlexTagBuilder tagBuilder, FlexTagBuilder footer)
{
return tagBuilder;
}
#endregion
#region Grid System
public virtual FlexTagBuilder GridRow(FlexTagBuilder tagBuilder)
{
return tagBuilder;
}
public virtual FlexTagBuilder GridColumns(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
return tagBuilder;
}
public virtual FlexTagBuilder GridColumnOffset(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
return tagBuilder;
}
public virtual FlexTagBuilder GridColumnPush(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
return tagBuilder;
}
public virtual FlexTagBuilder GridColumnPull(FlexTagBuilder tagBuilder, GridStyle style, int columns)
{
return tagBuilder;
}
public virtual FlexTagBuilder GridColumnVisible(FlexTagBuilder tagBuilder, GridStyle style, bool visible)
{
return tagBuilder;
}
#endregion
#region Form
public virtual FlexTagBuilder FormLayout(FlexTagBuilder tagBuilder, FormLayoutStyle layout)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupHelpText(FlexTagBuilder tagBuilder, string text)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupLabelText(FlexTagBuilder tagBuilder, string text)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupValidationState(FlexTagBuilder tagBuilder, ValidationState state)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupAddInput(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder labelTag, FlexTagBuilder inputTag)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupInputGridColumns(FlexTagBuilder tagBuilder, FlexFormContext formContext, GridStyle style, int columns)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupButton(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder buttonTag)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupAddButton(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder buttonTag)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupHeight(FlexTagBuilder tagBuilder, FormGroupHeightStyle size)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupLink(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder linkTag)
{
return tagBuilder;
}
public virtual FlexTagBuilder FormGroupAddLink(FlexTagBuilder tagBuilder, FlexFormContext formContext, FlexTagBuilder linkTag)
{
return tagBuilder;
}
#endregion
#region Input
public virtual FlexTagBuilder InputPlaceholder(FlexTagBuilder tagBuilder, string text)
{
tagBuilder.TagAttributes["placeholder"] = text;
return tagBuilder;
}
public virtual FlexTagBuilder InputFocus(FlexTagBuilder tagBuilder)
{
tagBuilder.TagAttributes["autofocus"] = "";
return tagBuilder;
}
public virtual FlexTagBuilder InputHeight(FlexTagBuilder tagBuilder, InputHeightStyle size)
{
return tagBuilder;
}
#endregion
#region Element
public virtual FlexTagBuilder Disabled(FlexTagBuilder tagBuilder)
{
tagBuilder.TagAttributes["disabled"] = "";
return tagBuilder;
}
public virtual FlexTagBuilder Active(FlexTagBuilder tagBuilder)
{
tagBuilder.AddCssClass("active");
return tagBuilder;
}
public virtual FlexTagBuilder Id(FlexTagBuilder tagBuilder, string id)
{
tagBuilder.TagAttributes["id"] = id;
return tagBuilder;
}
public virtual FlexTagBuilder Collapse(FlexTagBuilder tagBuilder, string target)
{
return tagBuilder;
}
public virtual FlexTagBuilder Collapsible(FlexTagBuilder tagBuilder, bool show = false)
{
return tagBuilder;
}
#endregion
#region Text Helper
public virtual FlexTagBuilder TextAlignment(FlexTagBuilder tagBuilder, TextAlignment textAlignment)
{
return tagBuilder;
}
public virtual FlexTagBuilder TextTransformation(FlexTagBuilder tagBuilder, TextTransformation textTransformation)
{
return tagBuilder;
}
public virtual FlexTagBuilder TextContextualColor(FlexTagBuilder tagBuilder, TextContextualColor textContextualColor)
{
return tagBuilder;
}
public virtual FlexTagBuilder ContextualBackground(FlexTagBuilder tagBuilder, ContextualBackground contextualBackground)
{
return tagBuilder;
}
#endregion
#region Button
public virtual FlexTagBuilder ButtonSize(FlexTagBuilder tagBuilder, ButtonSizeStyle size)
{
return tagBuilder;
}
public virtual FlexTagBuilder ButtonStyle(FlexTagBuilder tagBuilder, ButtonOptionStyle style)
{
return tagBuilder;
}
public virtual FlexTagBuilder ButtonBlock(FlexTagBuilder tagBuilder)
{
return tagBuilder;
}
#endregion
#region Link
public virtual FlexTagBuilder PagingLinkSize(FlexTagBuilder tagBuilder, PagingLinkSizeStyle size)
{
return tagBuilder;
}
#endregion
#region Modal
public virtual FlexTagBuilder ModalSize(FlexTagBuilder tagBuilder, ModalSizeStyle size)
{
return tagBuilder;
}
public virtual FlexTagBuilder ModalOption(FlexTagBuilder tagBuilder, string name, string value)
{
return tagBuilder;
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Sql.ServerActiveDirectoryAdministrator.Model;
using Microsoft.Azure.Commands.Sql.Services;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Microsoft.Azure.Graph.RBAC.Version1_6.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Azure.Commands.Sql.ServerActiveDirectoryAdministrator.Services
{
/// <summary>
/// Adapter for Azure SQL Server Active Directory administrator operations
/// </summary>
public class AzureSqlServerActiveDirectoryAdministratorAdapter
{
/// <summary>
/// Gets or sets the AzureSqlServerActiveDirectoryAdministratorCommunicator which has all the needed management clients
/// </summary>
private AzureSqlServerActiveDirectoryAdministratorCommunicator Communicator { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
/// <summary>
/// Gets or sets the Azure Subscription
/// </summary>
private IAzureSubscription _subscription { get; set; }
/// <summary>
/// A private instance of ActiveDirectoryClient
/// </summary>
private ActiveDirectoryClient _activeDirectoryClient;
/// <summary>
/// Gets or sets the Azure ActiveDirectoryClient instance
/// </summary>
public ActiveDirectoryClient ActiveDirectoryClient
{
get
{
if (_activeDirectoryClient == null)
{
_activeDirectoryClient = new ActiveDirectoryClient(Context);
if (!Context.Environment.IsEndpointSet(AzureEnvironment.Endpoint.Graph))
{
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidGraphEndpoint));
}
_activeDirectoryClient = new ActiveDirectoryClient(Context);
}
return this._activeDirectoryClient;
}
set { this._activeDirectoryClient = value; }
}
/// <summary>
/// Constructs a Azure SQL Server Active Directory administrator adapter
/// </summary>
/// <param name="profile">The current azure profile</param>
/// <param name="subscription">The current azure subscription</param>
public AzureSqlServerActiveDirectoryAdministratorAdapter(IAzureContext context)
{
Context = context;
_subscription = context.Subscription;
Communicator = new AzureSqlServerActiveDirectoryAdministratorCommunicator(Context);
}
/// <summary>
/// Gets an Azure SQL Server Active Directory administrator by name.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure SQL Server that contains the Azure Active Directory administrator</param>
/// <returns>The Azure Sql ServerActiveDirectoryAdministrator object</returns>
internal AzureSqlServerActiveDirectoryAdministratorModel GetServerActiveDirectoryAdministrator(string resourceGroupName, string serverName)
{
var resp = Communicator.Get(resourceGroupName, serverName);
return CreateServerActiveDirectoryAdministratorModelFromResponse(resourceGroupName, serverName, resp);
}
/// <summary>
/// Gets a list of Azure SQL Server Active Directory administrators.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group</param>
/// <param name="serverName">The name of the Azure SQL Server that contains the Azure Active Directory administrator</param>
/// <returns>A list of Azure SQL Server Active Directory administrators objects</returns>
internal ICollection<AzureSqlServerActiveDirectoryAdministratorModel> ListServerActiveDirectoryAdministrators(string resourceGroupName, string serverName)
{
var resp = Communicator.List(resourceGroupName, serverName);
return resp.Select((activeDirectoryAdmin) =>
{
return CreateServerActiveDirectoryAdministratorModelFromResponse(resourceGroupName, serverName, activeDirectoryAdmin);
}).ToList();
}
/// <summary>
/// Creates or updates an Azure SQL Server Active Directory administrator.
/// </summary>
/// <param name="resourceGroup">The name of the resource group</param>
/// <param name="serverName">The name of the Azure Sql ServerActiveDirectoryAdministrator Server</param>
/// <param name="model">The input parameters for the create/update operation</param>
/// <returns>The upserted Azure SQL Server Active Directory administrator</returns>
internal AzureSqlServerActiveDirectoryAdministratorModel UpsertServerActiveDirectoryAdministrator(string resourceGroup, string serverName, AzureSqlServerActiveDirectoryAdministratorModel model)
{
var resp = Communicator.CreateOrUpdate(resourceGroup, serverName, new ServerAdministratorCreateOrUpdateParameters()
{
Properties = GetActiveDirectoryInformation(model.DisplayName, model.ObjectId)
});
return CreateServerActiveDirectoryAdministratorModelFromResponse(resourceGroup, serverName, resp);
}
/// <summary>
/// Deletes a Azure SQL Server Active Directory administrator
/// </summary>
/// <param name="resourceGroupName">The resource group the server is in</param>
/// <param name="serverName">The name of the Azure Sql ServerActiveDirectoryAdministrator Server</param>
public void RemoveServerActiveDirectoryAdministrator(string resourceGroupName, string serverName)
{
Communicator.Remove(resourceGroupName, serverName);
}
/// <summary>
/// Converts the response from the service to a powershell database object
/// </summary>
/// <param name="resourceGroupName">The resource group the server is in</param>
/// <param name="serverName">The name of the Azure Sql ServerActiveDirectoryAdministrator Server</param>
/// <param name="admin">The service response</param>
/// <returns>The converted model</returns>
public static AzureSqlServerActiveDirectoryAdministratorModel CreateServerActiveDirectoryAdministratorModelFromResponse(string resourceGroup, string serverName, Management.Sql.LegacySdk.Models.ServerAdministrator admin)
{
AzureSqlServerActiveDirectoryAdministratorModel model = new AzureSqlServerActiveDirectoryAdministratorModel();
model.ResourceGroupName = resourceGroup;
model.ServerName = serverName;
model.DisplayName = admin.Properties.Login;
model.ObjectId = admin.Properties.Sid;
return model;
}
/// <summary>
/// Verifies that the Azure Active Directory user or group exists, and will get the object id if it is not set.
/// </summary>
/// <param name="displayName">Azure Active Directory user or group display name</param>
/// <param name="objectId">Azure Active Directory user or group object id</param>
/// <returns></returns>
protected ServerAdministratorCreateOrUpdateProperties GetActiveDirectoryInformation(string displayName, Guid objectId)
{
// Gets the default Tenant id for the subscriptions
Guid tenantId = GetTenantId();
// Check for a Azure Active Directory group. Recommended to always use group.
IEnumerable<PSADGroup> groupList = null;
var filter = new ADObjectFilterOptions()
{
Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
SearchString = displayName,
Paging = true,
};
// Get a list of groups from Azure Active Directory
groupList = ActiveDirectoryClient.FilterGroups(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase));
if (groupList.Count() > 1)
{
// More than one group was found with that display name.
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADGroupMoreThanOneFound, displayName));
}
else if (groupList.Count() == 1)
{
// Only one group was found. Get the group display name and object id
var group = groupList.First();
// Only support Security Groups
if (group.SecurityEnabled.HasValue && !group.SecurityEnabled.Value)
{
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidADGroupNotSecurity, displayName));
}
return new ServerAdministratorCreateOrUpdateProperties()
{
Login = group.DisplayName,
Sid = group.Id,
TenantId = tenantId,
};
}
// No group was found. Check for a user
filter = new ADObjectFilterOptions()
{
Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
SearchString = displayName,
Paging = true,
};
// Get a list of user from Azure Active Directory
var userList = ActiveDirectoryClient.FilterUsers(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase));
// No user was found. Check if the display name is a UPN
if (userList == null || userList.Count() == 0)
{
// Check if the display name is the UPN
filter = new ADObjectFilterOptions()
{
Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null,
UPN = displayName,
Paging = true,
};
userList = ActiveDirectoryClient.FilterUsers(filter).Where(gr => string.Equals(gr.UserPrincipalName, displayName, StringComparison.OrdinalIgnoreCase));
}
// No user was found
if (userList == null || userList.Count() == 0)
{
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADObjectNotFound, displayName));
}
else if (userList.Count() > 1)
{
// More than one user was found.
throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADUserMoreThanOneFound, displayName));
}
else
{
// Only one user was found. Get the user display name and object id
var obj = userList.First();
return new ServerAdministratorCreateOrUpdateProperties()
{
Login = displayName,
Sid = obj.Id,
TenantId = tenantId,
};
}
}
/// <summary>
/// Get the default tenantId for the current subscription
/// </summary>
/// <returns></returns>
protected Guid GetTenantId()
{
var tenantIdStr = Context.Tenant.Id.ToString();
string adTenant = Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.AdTenant);
string graph = Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.Graph);
var tenantIdGuid = Guid.Empty;
if (string.IsNullOrWhiteSpace(tenantIdStr) || !Guid.TryParse(tenantIdStr, out tenantIdGuid))
{
throw new InvalidOperationException(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidTenantId);
}
return tenantIdGuid;
}
}
}
| |
//------------------------------------------------------------------------------
// TrackRoamerBehaviorsTypes.cs
//
// This code was generated by the DssNewService tool.
//
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Ccr.Core;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.Attributes;
using dssp = Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
using W3C.Soap;
using TrackRoamer.Robotics.LibMapping;
using TrackRoamer.Robotics.LibBehavior;
using bumper = Microsoft.Robotics.Services.ContactSensor.Proxy;
using drive = Microsoft.Robotics.Services.Drive.Proxy;
using sicklrf = Microsoft.Robotics.Services.Sensors.SickLRF.Proxy;
using encoder = Microsoft.Robotics.Services.Encoder.Proxy;
using proxibrick = TrackRoamer.Robotics.Services.TrackRoamerBrickProximityBoard.Proxy;
using trackroamerbehaviors = TrackRoamer.Robotics.Services.TrackRoamerBehaviors;
namespace TrackRoamer.Robotics.Services.TrackRoamerBehaviors
{
/// <summary>
/// Track Roamer Behaviors State
/// </summary>
[DataContract()]
public class TrackRoamerBehaviorsState
{
public TrackRoamerBehaviorsState()
{
Init();
}
public void Init()
{
Dropping = false;
IsTurning = false;
LastTurnStarted = DateTime.MinValue;
LastTurnCompleted = DateTime.MinValue;
if (WheelsEncoderState == null)
{
WheelsEncoderState = new WheelsEncoderState();
}
if (collisionState == null)
{
collisionState = new CollisionState();
}
if (gpsState == null)
{
gpsState = new GpsState();
}
if (MostRecentAnalogValues == null)
{
MostRecentAnalogValues = new proxibrick.AnalogDataDssSerializable() { TimeStamp = DateTime.MinValue };
}
MostRecentLaserTimeStamp = DateTime.Now;
if (VoiceCommandState == null)
{
VoiceCommandState = new VoiceCommandState();
}
int MAX_HUMANS_TO_TRACK = 7; // FrameProcessor preallocates 7
HumanInteractionStates = new HumanInteractionState[MAX_HUMANS_TO_TRACK];
for (int i = 0; i < HumanInteractionStates.Length; i++)
{
HumanInteractionStates[i] = new HumanInteractionState();
}
if (followDirectionPidControllerAngularSpeed == null)
{
followDirectionPidControllerAngularSpeed = new PIDController()
{
Name = "AngularSpeed",
MaxIntegralError = 180.0d, // degrees; anything more causes controller reset (error too large)
MaxUpdateIntervalSec = 10.0d, // ms; anything more causes controller reset (interval too long)
MaxPidValue = 100.0d, // pid factor upper limit
MinPidValue = 0.0d, // pid factor lower limit
Kp = PIDController.ProportionalGainDefault, // Proportional constant, 3.0
Ki = PIDController.IntegralGainDefault, // Integral constant, 0.1
Kd = PIDController.DerivativeGainDefault // Derivative constant, 0.5
};
}
if (followDirectionPidControllerLinearSpeed == null)
{
followDirectionPidControllerLinearSpeed = new PIDController()
{
Name = "LinearSpeed",
MaxIntegralError = 2000.0d, // mm/sec; anything more causes controller reset (error too large)
MaxUpdateIntervalSec = 10.0d, // ms; anything more causes controller reset (interval too long)
MaxPidValue = 1000.0d, // pid factor upper limit
MinPidValue = 0.0d, // pid factor lower limit
Kp = PIDController.ProportionalGainDefault, // Proportional constant, 3.0
Ki = PIDController.IntegralGainDefault, // Integral constant, 0.1
Kd = PIDController.DerivativeGainDefault // Derivative constant, 0.5
};
}
if (PowerScale == 0.0d)
{
PowerScale = 0.5d;
}
}
#region data members
[DataMember(IsRequired = false)]
public drive.DriveDifferentialTwoWheelState DriveState { get; set; }
//[DataMember(IsRequired = false)]
//public encoder.EncoderState EncoderStateLeft { get; set; }
//[DataMember(IsRequired = false)]
//public encoder.EncoderState EncoderStateRight { get; set; }
[DataMember]
public WheelsEncoderState WheelsEncoderState { get; set; }
[DataMember]
public bool IsTurning { get; set; }
[DataMember]
public DateTime LastTurnStarted { get; set; }
[DataMember]
public DateTime LastTurnCompleted { get; set; }
[DataMember]
public int Countdown { get; set; }
[Browsable(false)]
[DataMember]
public bool Dropping { get; set; }
[DataMember]
public MovingState MovingState { get; set; }
[DataMember]
public string MovingStateDetail { get; set; }
[DataMember]
public int NewHeading { get; set; }
[DataMember]
public double Velocity { get; set; } // the vehicle velocity in m/s
[DataMember]
public sicklrf.State South { get; set; }
[DataMember]
public bool Mapped { get; set; }
[DataMember]
public DateTime MostRecentLaserTimeStamp { get; set; }
[DataMember]
public HumanInteractionState[] HumanInteractionStates { get; set; }
// Speech Recognizer Command related (only recognized and accepted commands make it here):
[DataMember]
public VoiceCommandState VoiceCommandState { get; set; }
// these sound direction values have not passed Voice Command recognition criteria, but were registered:
[DataMember]
public int SoundBeamDirection { get; set; }
[DataMember]
public DateTime SoundBeamTimeStamp { get; set; }
[DataMember]
public int AnySpeechDirection { get; set; }
[DataMember]
public DateTime AnySpeechTimeStamp { get; set; }
// data coming from Proximity Board:
/// <summary>
/// Last compass reading.
/// </summary>
[DataMember, Browsable(true)]
public proxibrick.DirectionDataDssSerializable MostRecentDirection { get; set; }
/// <summary>
/// Last Accelerometer reading.
/// </summary>
[DataMember, Browsable(true)]
public proxibrick.AccelerometerDataDssSerializable MostRecentAccelerometer { get; set; }
/// <summary>
/// Last IR Directed (Proximity) sensors reading.
/// </summary>
[DataMember, Browsable(true)]
public proxibrick.ProximityDataDssSerializable MostRecentProximity { get; set; }
/// <summary>
/// Last whiskers reading.
/// </summary>
[DataMember, Browsable(true)]
public bool MostRecentWhiskerLeft { get; set; }
[DataMember, Browsable(true)]
public bool MostRecentWhiskerRight { get; set; }
/// <summary>
/// Last Parking Sensors reading.
/// </summary>
[DataMember, Browsable(true)]
public proxibrick.ParkingSensorDataDssSerializable MostRecentParkingSensor { get; set; }
/// <summary>
/// Last Pot (pin 2 AN0 of PIC 4550) and other analog data reading.
/// </summary>
[DataMember, Browsable(true)]
public proxibrick.AnalogDataDssSerializable MostRecentAnalogValues { get; set; }
[DataMember, Browsable(true)]
public double currentTiltKinect = 0.0d; // Degrees, upwards positive
[DataMember, Browsable(true)]
public double currentPanKinect = 0.0d; // Degrees, right positive
[DataMember, Browsable(true)]
public CollisionState collisionState; // compute it in computeCollisionState(), do not replace
[DataMember, Browsable(true)]
public GpsState gpsState;
[DataMember, Browsable(true)]
public PIDController followDirectionPidControllerAngularSpeed;
[DataMember, Browsable(true)]
public PIDController followDirectionPidControllerLinearSpeed;
[DataMember, Browsable(true)]
public double PowerScale; // all above power and speed are multiplied by PowerScale
// also see MotorPowerScalingFactor=100 in the TrackRoamerDriveTypes.cs
#endregion
#region internal helper accessors for meta states - IsMapping, IsUnknown, IsMoving, IsActive
#if OBSOLETE_PLANANDAVOID_LOGIC
// robot is busy performing a part of mapping sequence
internal bool IsMapping
{
get
{
return
MovingState == MovingState.RandomTurn ||
//MovingState == MovingState.MapNorth ||
//MovingState == MovingState.MapSouth ||
//MovingState == MovingState.MapSurroundings ||
MovingState == MovingState.Recovering;
}
}
#endif // OBSOLETE_PLANANDAVOID_LOGIC
// robot is likely to use Decide() to figure out what to do next
internal bool IsUnknown
{
get
{
return MovingState == MovingState.Unknown;
}
}
// robot is doing something not in place (like mapping is an in-place sequence).
// all transitional sequences and backing up means it is moving too.
internal bool IsMoving
{
get
{
return IsActive; // && !IsMapping;
}
}
// robot is doing something, likely a step of some task
internal bool IsActive
{
get
{
return !IsUnknown;
}
}
#endregion
}
/// <summary>
/// Speech Recognizer Command related (only recognized and accepted commands make it here):
/// </summary>
[DataContract()]
public class VoiceCommandState
{
public VoiceCommandState()
{
TimeStamp = DateTime.MinValue;
}
[DataMember]
public DateTime TimeStamp { get; set; }
[DataMember]
public string Text { get; set; }
[DataMember]
public string Semantics { get; set; }
[DataMember]
public int Direction { get; set; }
[DataMember]
public int ConfidencePercent { get; set; }
}
[DataContract()]
public class HumanInteractionState
{
public HumanInteractionState()
{
TimeStamp = DateTime.MinValue;
}
[DataMember]
public bool IsTracked { get; set; }
/// <summary>
/// a number maintained by Kinect. See http://msdn.microsoft.com/en-us/library/jj131025.aspx#Active_User_Tracking
/// </summary>
[DataMember]
public int TrackingId { get; set; }
[DataMember]
public bool IsMain { get; set; }
[DataMember]
public DateTime TimeStamp { get; set; }
[DataMember]
public double DirectionPan { get; set; }
[DataMember]
public double DirectionTilt { get; set; }
[DataMember]
public double DistanceMeters { get; set; }
}
[DataContract]
public enum MovingState
{
Unknown, // not doing anything, should begin planning next action based on situation. Typical after recovering.
Unable, // cannot move where it wanted to, collision state prohibits executing current plan, no good secondary plans either.
FreeForwards, // rolling forwards, constantly adjusting wheels' speed (normally using PID controller and SetDrivePower)
InTransition, // performing a direct Differential Drive move, like a turn by degrees or Translate.
//AdjustHeading,
Recovering,
LayingDown,
// almost obsolete:
BumpedBackingUp,
//RandomTurn
// obsolete:
//MapSurroundings,
//MapNorth,
//MapSouth,
}
public enum SensorEventSource
{
Orientation,
Compass,
Gps,
LaserScanning,
SonarDirected,
IrDirected,
Bumper,
Whiskers,
Kinect
}
}
| |
// Copyright 2016, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Vision.V1
{
/// <summary>
/// Settings for a <see cref="ImageAnnotatorClient"/>.
/// </summary>
public sealed partial class ImageAnnotatorSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ImageAnnotatorSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="ImageAnnotatorSettings"/>.
/// </returns>
public static ImageAnnotatorSettings GetDefault() => new ImageAnnotatorSettings();
/// <summary>
/// Constructs a new <see cref="ImageAnnotatorSettings"/> object with default settings.
/// </summary>
public ImageAnnotatorSettings() { }
private ImageAnnotatorSettings(ImageAnnotatorSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
BatchAnnotateImagesSettings = existing.BatchAnnotateImagesSettings;
}
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="ImageAnnotatorClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="ImageAnnotatorClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="ImageAnnotatorClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="ImageAnnotatorClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="ImageAnnotatorClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="ImageAnnotatorClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="ImageAnnotatorClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="ImageAnnotatorClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 60000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(60000),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ImageAnnotatorClient.BatchAnnotateImages</c> and <c>ImageAnnotatorClient.BatchAnnotateImagesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ImageAnnotatorClient.BatchAnnotateImages</c> and
/// <c>ImageAnnotatorClient.BatchAnnotateImagesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings BatchAnnotateImagesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="ImageAnnotatorSettings"/> object.</returns>
public ImageAnnotatorSettings Clone() => new ImageAnnotatorSettings(this);
}
/// <summary>
/// ImageAnnotator client wrapper, for convenient use.
/// </summary>
public abstract partial class ImageAnnotatorClient
{
/// <summary>
/// The default endpoint for the ImageAnnotator service, which is a host of "vision.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("vision.googleapis.com", 443);
/// <summary>
/// The default ImageAnnotator scopes.
/// </summary>
/// <remarks>
/// The default ImageAnnotator scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="ImageAnnotatorClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ImageAnnotatorSettings"/>.</param>
/// <returns>The task representing the created <see cref="ImageAnnotatorClient"/>.</returns>
public static async Task<ImageAnnotatorClient> CreateAsync(ServiceEndpoint endpoint = null, ImageAnnotatorSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="ImageAnnotatorClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ImageAnnotatorSettings"/>.</param>
/// <returns>The created <see cref="ImageAnnotatorClient"/>.</returns>
public static ImageAnnotatorClient Create(ServiceEndpoint endpoint = null, ImageAnnotatorSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="ImageAnnotatorClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="ImageAnnotatorSettings"/>.</param>
/// <returns>The created <see cref="ImageAnnotatorClient"/>.</returns>
public static ImageAnnotatorClient Create(Channel channel, ImageAnnotatorSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
ImageAnnotator.ImageAnnotatorClient grpcClient = new ImageAnnotator.ImageAnnotatorClient(channel);
return new ImageAnnotatorClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ImageAnnotatorSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ImageAnnotatorSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ImageAnnotatorSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ImageAnnotatorSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC ImageAnnotator client.
/// </summary>
public virtual ImageAnnotator.ImageAnnotatorClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Run image detection and annotation for a batch of images.
/// </summary>
/// <param name="requests">
/// Individual image annotation requests for this batch.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<BatchAnnotateImagesResponse> BatchAnnotateImagesAsync(
IEnumerable<AnnotateImageRequest> requests,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Run image detection and annotation for a batch of images.
/// </summary>
/// <param name="requests">
/// Individual image annotation requests for this batch.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<BatchAnnotateImagesResponse> BatchAnnotateImagesAsync(
IEnumerable<AnnotateImageRequest> requests,
CancellationToken cancellationToken) => BatchAnnotateImagesAsync(
requests,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Run image detection and annotation for a batch of images.
/// </summary>
/// <param name="requests">
/// Individual image annotation requests for this batch.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual BatchAnnotateImagesResponse BatchAnnotateImages(
IEnumerable<AnnotateImageRequest> requests,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// ImageAnnotator client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class ImageAnnotatorClientImpl : ImageAnnotatorClient
{
private readonly ClientHelper _clientHelper;
private readonly ApiCall<BatchAnnotateImagesRequest, BatchAnnotateImagesResponse> _callBatchAnnotateImages;
/// <summary>
/// Constructs a client wrapper for the ImageAnnotator service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ImageAnnotatorSettings"/> used within this client </param>
public ImageAnnotatorClientImpl(ImageAnnotator.ImageAnnotatorClient grpcClient, ImageAnnotatorSettings settings)
{
this.GrpcClient = grpcClient;
ImageAnnotatorSettings effectiveSettings = settings ?? ImageAnnotatorSettings.GetDefault();
_clientHelper = new ClientHelper(effectiveSettings);
_callBatchAnnotateImages = _clientHelper.BuildApiCall<BatchAnnotateImagesRequest, BatchAnnotateImagesResponse>(
GrpcClient.BatchAnnotateImagesAsync, GrpcClient.BatchAnnotateImages, effectiveSettings.BatchAnnotateImagesSettings);
}
/// <summary>
/// The underlying gRPC ImageAnnotator client.
/// </summary>
public override ImageAnnotator.ImageAnnotatorClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_BatchAnnotateImagesRequest(ref BatchAnnotateImagesRequest request, ref CallSettings settings);
/// <summary>
/// Run image detection and annotation for a batch of images.
/// </summary>
/// <param name="requests">
/// Individual image annotation requests for this batch.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<BatchAnnotateImagesResponse> BatchAnnotateImagesAsync(
IEnumerable<AnnotateImageRequest> requests,
CallSettings callSettings = null)
{
BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest
{
Requests = { requests },
};
Modify_BatchAnnotateImagesRequest(ref request, ref callSettings);
return _callBatchAnnotateImages.Async(request, callSettings);
}
/// <summary>
/// Run image detection and annotation for a batch of images.
/// </summary>
/// <param name="requests">
/// Individual image annotation requests for this batch.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override BatchAnnotateImagesResponse BatchAnnotateImages(
IEnumerable<AnnotateImageRequest> requests,
CallSettings callSettings = null)
{
BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest
{
Requests = { requests },
};
Modify_BatchAnnotateImagesRequest(ref request, ref callSettings);
return _callBatchAnnotateImages.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
/*
* 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 elasticmapreduce-2009-03-31.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.ElasticMapReduce.Model
{
/// <summary>
/// The detailed description of the cluster.
/// </summary>
public partial class Cluster
{
private List<Application> _applications = new List<Application>();
private bool? _autoTerminate;
private List<Configuration> _configurations = new List<Configuration>();
private Ec2InstanceAttributes _ec2InstanceAttributes;
private string _id;
private string _logUri;
private string _masterPublicDnsName;
private string _name;
private int? _normalizedInstanceHours;
private string _releaseLabel;
private string _requestedAmiVersion;
private string _runningAmiVersion;
private string _serviceRole;
private ClusterStatus _status;
private List<Tag> _tags = new List<Tag>();
private bool? _terminationProtected;
private bool? _visibleToAllUsers;
/// <summary>
/// Gets and sets the property Applications.
/// <para>
/// The applications installed on this cluster.
/// </para>
/// </summary>
public List<Application> Applications
{
get { return this._applications; }
set { this._applications = value; }
}
// Check to see if Applications property is set
internal bool IsSetApplications()
{
return this._applications != null && this._applications.Count > 0;
}
/// <summary>
/// Gets and sets the property AutoTerminate.
/// <para>
/// Specifies whether the cluster should terminate after completing all steps.
/// </para>
/// </summary>
public bool AutoTerminate
{
get { return this._autoTerminate.GetValueOrDefault(); }
set { this._autoTerminate = value; }
}
// Check to see if AutoTerminate property is set
internal bool IsSetAutoTerminate()
{
return this._autoTerminate.HasValue;
}
/// <summary>
/// Gets and sets the property Configurations. <note>
/// <para>
/// Amazon EMR releases 4.x or later.
/// </para>
/// </note>
/// <para>
/// The list of Configurations supplied to the EMR cluster.
/// </para>
/// </summary>
public List<Configuration> Configurations
{
get { return this._configurations; }
set { this._configurations = value; }
}
// Check to see if Configurations property is set
internal bool IsSetConfigurations()
{
return this._configurations != null && this._configurations.Count > 0;
}
/// <summary>
/// Gets and sets the property Ec2InstanceAttributes.
/// </summary>
public Ec2InstanceAttributes Ec2InstanceAttributes
{
get { return this._ec2InstanceAttributes; }
set { this._ec2InstanceAttributes = value; }
}
// Check to see if Ec2InstanceAttributes property is set
internal bool IsSetEc2InstanceAttributes()
{
return this._ec2InstanceAttributes != null;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The unique identifier for the cluster.
/// </para>
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property LogUri.
/// <para>
/// The path to the Amazon S3 location where logs for this cluster are stored.
/// </para>
/// </summary>
public string LogUri
{
get { return this._logUri; }
set { this._logUri = value; }
}
// Check to see if LogUri property is set
internal bool IsSetLogUri()
{
return this._logUri != null;
}
/// <summary>
/// Gets and sets the property MasterPublicDnsName.
/// <para>
/// The public DNS name of the master EC2 instance.
/// </para>
/// </summary>
public string MasterPublicDnsName
{
get { return this._masterPublicDnsName; }
set { this._masterPublicDnsName = value; }
}
// Check to see if MasterPublicDnsName property is set
internal bool IsSetMasterPublicDnsName()
{
return this._masterPublicDnsName != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the cluster.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property NormalizedInstanceHours.
/// <para>
/// An approximation of the cost of the job flow, represented in m1.small/hours. This
/// value is incremented one time for every hour an m1.small instance runs. Larger instances
/// are weighted more, so an EC2 instance that is roughly four times more expensive would
/// result in the normalized instance hours being incremented by four. This result is
/// only an approximation and does not reflect the actual billing rate.
/// </para>
/// </summary>
public int NormalizedInstanceHours
{
get { return this._normalizedInstanceHours.GetValueOrDefault(); }
set { this._normalizedInstanceHours = value; }
}
// Check to see if NormalizedInstanceHours property is set
internal bool IsSetNormalizedInstanceHours()
{
return this._normalizedInstanceHours.HasValue;
}
/// <summary>
/// Gets and sets the property ReleaseLabel.
/// <para>
/// The release label for the Amazon EMR release. For Amazon EMR 3.x and 2.x AMIs, use
/// amiVersion instead instead of ReleaseLabel.
/// </para>
/// </summary>
public string ReleaseLabel
{
get { return this._releaseLabel; }
set { this._releaseLabel = value; }
}
// Check to see if ReleaseLabel property is set
internal bool IsSetReleaseLabel()
{
return this._releaseLabel != null;
}
/// <summary>
/// Gets and sets the property RequestedAmiVersion.
/// <para>
/// The AMI version requested for this cluster.
/// </para>
/// </summary>
public string RequestedAmiVersion
{
get { return this._requestedAmiVersion; }
set { this._requestedAmiVersion = value; }
}
// Check to see if RequestedAmiVersion property is set
internal bool IsSetRequestedAmiVersion()
{
return this._requestedAmiVersion != null;
}
/// <summary>
/// Gets and sets the property RunningAmiVersion.
/// <para>
/// The AMI version running on this cluster.
/// </para>
/// </summary>
public string RunningAmiVersion
{
get { return this._runningAmiVersion; }
set { this._runningAmiVersion = value; }
}
// Check to see if RunningAmiVersion property is set
internal bool IsSetRunningAmiVersion()
{
return this._runningAmiVersion != null;
}
/// <summary>
/// Gets and sets the property ServiceRole.
/// <para>
/// The IAM role that will be assumed by the Amazon EMR service to access AWS resources
/// on your behalf.
/// </para>
/// </summary>
public string ServiceRole
{
get { return this._serviceRole; }
set { this._serviceRole = value; }
}
// Check to see if ServiceRole property is set
internal bool IsSetServiceRole()
{
return this._serviceRole != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The current status details about the cluster.
/// </para>
/// </summary>
public ClusterStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A list of tags associated with a cluster.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property TerminationProtected.
/// <para>
/// Indicates whether Amazon EMR will lock the cluster to prevent the EC2 instances from
/// being terminated by an API call or user intervention, or in the event of a cluster
/// error.
/// </para>
/// </summary>
public bool TerminationProtected
{
get { return this._terminationProtected.GetValueOrDefault(); }
set { this._terminationProtected = value; }
}
// Check to see if TerminationProtected property is set
internal bool IsSetTerminationProtected()
{
return this._terminationProtected.HasValue;
}
/// <summary>
/// Gets and sets the property VisibleToAllUsers.
/// <para>
/// Indicates whether the job flow is visible to all IAM users of the AWS account associated
/// with the job flow. If this value is set to <code>true</code>, all IAM users of that
/// AWS account can view and manage the job flow if they have the proper policy permissions
/// set. If this value is <code>false</code>, only the IAM user that created the cluster
/// can view and manage it. This value can be changed using the <a>SetVisibleToAllUsers</a>
/// action.
/// </para>
/// </summary>
public bool VisibleToAllUsers
{
get { return this._visibleToAllUsers.GetValueOrDefault(); }
set { this._visibleToAllUsers = value; }
}
// Check to see if VisibleToAllUsers property is set
internal bool IsSetVisibleToAllUsers()
{
return this._visibleToAllUsers.HasValue;
}
}
}
| |
namespace groupmanager
{
partial class frmGroupInfo
{
/// <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.tabs = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.labelInsigniaProgress = new System.Windows.Forms.Label();
this.grpPreferences = new System.Windows.Forms.GroupBox();
this.chkMature = new System.Windows.Forms.CheckBox();
this.numFee = new System.Windows.Forms.NumericUpDown();
this.chkGroupNotices = new System.Windows.Forms.CheckBox();
this.chkFee = new System.Windows.Forms.CheckBox();
this.chkOpenEnrollment = new System.Windows.Forms.CheckBox();
this.chkPublish = new System.Windows.Forms.CheckBox();
this.chkShow = new System.Windows.Forms.CheckBox();
this.lstMembers = new System.Windows.Forms.ListView();
this.colName = new System.Windows.Forms.ColumnHeader();
this.colTitle = new System.Windows.Forms.ColumnHeader();
this.colLasLogin = new System.Windows.Forms.ColumnHeader();
this.txtCharter = new System.Windows.Forms.TextBox();
this.lblFoundedBy = new System.Windows.Forms.Label();
this.lblGroupName = new System.Windows.Forms.Label();
this.picInsignia = new System.Windows.Forms.PictureBox();
this.tabMembersRoles = new System.Windows.Forms.TabPage();
this.tabsMRA = new System.Windows.Forms.TabControl();
this.tabMembers = new System.Windows.Forms.TabPage();
this.cmdEject = new System.Windows.Forms.Button();
this.lstMembers2 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.chkListRoles = new System.Windows.Forms.CheckedListBox();
this.treeAbilities = new System.Windows.Forms.TreeView();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tabRoles = new System.Windows.Forms.TabPage();
this.tabAbilities = new System.Windows.Forms.TabPage();
this.tabNotices = new System.Windows.Forms.TabPage();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.cmdRefreshNotices = new System.Windows.Forms.Button();
this.lstNotices = new System.Windows.Forms.ListView();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.columnHeader5 = new System.Windows.Forms.ColumnHeader();
this.columnHeader6 = new System.Windows.Forms.ColumnHeader();
this.tabProposals = new System.Windows.Forms.TabPage();
this.tabLand = new System.Windows.Forms.TabPage();
this.tabsMoney = new System.Windows.Forms.TabControl();
this.tabPlanning = new System.Windows.Forms.TabPage();
this.txtPlanning = new System.Windows.Forms.TextBox();
this.tabDetails = new System.Windows.Forms.TabPage();
this.txtDetails = new System.Windows.Forms.TextBox();
this.tabSales = new System.Windows.Forms.TabPage();
this.txtSales = new System.Windows.Forms.TextBox();
this.txtContribution = new System.Windows.Forms.TextBox();
this.lblLandAvailable = new System.Windows.Forms.Label();
this.lblLandInUse = new System.Windows.Forms.Label();
this.lblTotalContribution = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lstLand = new System.Windows.Forms.ListView();
this.columnHeader7 = new System.Windows.Forms.ColumnHeader();
this.columnHeader8 = new System.Windows.Forms.ColumnHeader();
this.columnHeader9 = new System.Windows.Forms.ColumnHeader();
this.cmdApply = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdOK = new System.Windows.Forms.Button();
this.cmdRefresh = new System.Windows.Forms.Button();
this.tabs.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.grpPreferences.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numFee)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picInsignia)).BeginInit();
this.tabMembersRoles.SuspendLayout();
this.tabsMRA.SuspendLayout();
this.tabMembers.SuspendLayout();
this.tabNotices.SuspendLayout();
this.tabLand.SuspendLayout();
this.tabsMoney.SuspendLayout();
this.tabPlanning.SuspendLayout();
this.tabDetails.SuspendLayout();
this.tabSales.SuspendLayout();
this.SuspendLayout();
//
// tabs
//
this.tabs.Controls.Add(this.tabGeneral);
this.tabs.Controls.Add(this.tabMembersRoles);
this.tabs.Controls.Add(this.tabNotices);
this.tabs.Controls.Add(this.tabProposals);
this.tabs.Controls.Add(this.tabLand);
this.tabs.Location = new System.Drawing.Point(6, 7);
this.tabs.Name = "tabs";
this.tabs.SelectedIndex = 0;
this.tabs.Size = new System.Drawing.Size(417, 507);
this.tabs.TabIndex = 9;
//
// tabGeneral
//
this.tabGeneral.Controls.Add(this.labelInsigniaProgress);
this.tabGeneral.Controls.Add(this.grpPreferences);
this.tabGeneral.Controls.Add(this.lstMembers);
this.tabGeneral.Controls.Add(this.txtCharter);
this.tabGeneral.Controls.Add(this.lblFoundedBy);
this.tabGeneral.Controls.Add(this.lblGroupName);
this.tabGeneral.Controls.Add(this.picInsignia);
this.tabGeneral.Location = new System.Drawing.Point(4, 22);
this.tabGeneral.Name = "tabGeneral";
this.tabGeneral.Padding = new System.Windows.Forms.Padding(3);
this.tabGeneral.Size = new System.Drawing.Size(409, 481);
this.tabGeneral.TabIndex = 0;
this.tabGeneral.Text = "General";
this.tabGeneral.UseVisualStyleBackColor = true;
//
// labelInsigniaProgress
//
this.labelInsigniaProgress.AutoSize = true;
this.labelInsigniaProgress.Location = new System.Drawing.Point(23, 149);
this.labelInsigniaProgress.Name = "labelInsigniaProgress";
this.labelInsigniaProgress.Size = new System.Drawing.Size(54, 13);
this.labelInsigniaProgress.TabIndex = 7;
this.labelInsigniaProgress.Text = "Loading...";
//
// grpPreferences
//
this.grpPreferences.Controls.Add(this.chkMature);
this.grpPreferences.Controls.Add(this.numFee);
this.grpPreferences.Controls.Add(this.chkGroupNotices);
this.grpPreferences.Controls.Add(this.chkFee);
this.grpPreferences.Controls.Add(this.chkOpenEnrollment);
this.grpPreferences.Controls.Add(this.chkPublish);
this.grpPreferences.Controls.Add(this.chkShow);
this.grpPreferences.Location = new System.Drawing.Point(10, 353);
this.grpPreferences.Name = "grpPreferences";
this.grpPreferences.Size = new System.Drawing.Size(393, 122);
this.grpPreferences.TabIndex = 14;
this.grpPreferences.TabStop = false;
this.grpPreferences.Text = "Group Preferences";
//
// chkMature
//
this.chkMature.AutoSize = true;
this.chkMature.Location = new System.Drawing.Point(162, 19);
this.chkMature.Name = "chkMature";
this.chkMature.Size = new System.Drawing.Size(95, 17);
this.chkMature.TabIndex = 6;
this.chkMature.Text = "Mature publish";
this.chkMature.UseVisualStyleBackColor = true;
//
// numFee
//
this.numFee.Location = new System.Drawing.Point(162, 87);
this.numFee.Name = "numFee";
this.numFee.Size = new System.Drawing.Size(82, 20);
this.numFee.TabIndex = 5;
//
// chkGroupNotices
//
this.chkGroupNotices.AutoSize = true;
this.chkGroupNotices.Location = new System.Drawing.Point(250, 87);
this.chkGroupNotices.Name = "chkGroupNotices";
this.chkGroupNotices.Size = new System.Drawing.Size(137, 17);
this.chkGroupNotices.TabIndex = 4;
this.chkGroupNotices.Text = "Receive Group Notices";
this.chkGroupNotices.UseVisualStyleBackColor = true;
//
// chkFee
//
this.chkFee.AutoSize = true;
this.chkFee.Location = new System.Drawing.Point(36, 88);
this.chkFee.Name = "chkFee";
this.chkFee.Size = new System.Drawing.Size(114, 17);
this.chkFee.TabIndex = 3;
this.chkFee.Text = "Enrollment Fee: L$";
this.chkFee.UseVisualStyleBackColor = true;
//
// chkOpenEnrollment
//
this.chkOpenEnrollment.AutoSize = true;
this.chkOpenEnrollment.Location = new System.Drawing.Point(16, 65);
this.chkOpenEnrollment.Name = "chkOpenEnrollment";
this.chkOpenEnrollment.Size = new System.Drawing.Size(104, 17);
this.chkOpenEnrollment.TabIndex = 2;
this.chkOpenEnrollment.Text = "Open Enrollment";
this.chkOpenEnrollment.UseVisualStyleBackColor = true;
//
// chkPublish
//
this.chkPublish.AutoSize = true;
this.chkPublish.Location = new System.Drawing.Point(16, 42);
this.chkPublish.Name = "chkPublish";
this.chkPublish.Size = new System.Drawing.Size(116, 17);
this.chkPublish.TabIndex = 1;
this.chkPublish.Text = "Publish on the web";
this.chkPublish.UseVisualStyleBackColor = true;
//
// chkShow
//
this.chkShow.AutoSize = true;
this.chkShow.Location = new System.Drawing.Point(16, 19);
this.chkShow.Name = "chkShow";
this.chkShow.Size = new System.Drawing.Size(116, 17);
this.chkShow.TabIndex = 0;
this.chkShow.Text = "Show In Group List";
this.chkShow.UseVisualStyleBackColor = true;
//
// lstMembers
//
this.lstMembers.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colName,
this.colTitle,
this.colLasLogin});
this.lstMembers.Location = new System.Drawing.Point(7, 221);
this.lstMembers.Name = "lstMembers";
this.lstMembers.Size = new System.Drawing.Size(396, 126);
this.lstMembers.TabIndex = 13;
this.lstMembers.UseCompatibleStateImageBehavior = false;
this.lstMembers.View = System.Windows.Forms.View.Details;
//
// colName
//
this.colName.Text = "Member Name";
this.colName.Width = 166;
//
// colTitle
//
this.colTitle.Text = "Title";
this.colTitle.Width = 127;
//
// colLasLogin
//
this.colLasLogin.Text = "Last Login";
this.colLasLogin.Width = 95;
//
// txtCharter
//
this.txtCharter.Location = new System.Drawing.Point(146, 42);
this.txtCharter.Multiline = true;
this.txtCharter.Name = "txtCharter";
this.txtCharter.Size = new System.Drawing.Size(257, 173);
this.txtCharter.TabIndex = 12;
//
// lblFoundedBy
//
this.lblFoundedBy.AutoSize = true;
this.lblFoundedBy.Location = new System.Drawing.Point(7, 26);
this.lblFoundedBy.Name = "lblFoundedBy";
this.lblFoundedBy.Size = new System.Drawing.Size(137, 13);
this.lblFoundedBy.TabIndex = 11;
this.lblFoundedBy.Text = "Founded by Group Founder";
//
// lblGroupName
//
this.lblGroupName.AutoSize = true;
this.lblGroupName.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblGroupName.Location = new System.Drawing.Point(7, 6);
this.lblGroupName.Name = "lblGroupName";
this.lblGroupName.Size = new System.Drawing.Size(99, 17);
this.lblGroupName.TabIndex = 10;
this.lblGroupName.Text = "Group Name";
//
// picInsignia
//
this.picInsignia.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picInsignia.Location = new System.Drawing.Point(10, 42);
this.picInsignia.Name = "picInsignia";
this.picInsignia.Size = new System.Drawing.Size(130, 130);
this.picInsignia.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picInsignia.TabIndex = 9;
this.picInsignia.TabStop = false;
//
// tabMembersRoles
//
this.tabMembersRoles.Controls.Add(this.tabsMRA);
this.tabMembersRoles.Location = new System.Drawing.Point(4, 22);
this.tabMembersRoles.Name = "tabMembersRoles";
this.tabMembersRoles.Padding = new System.Windows.Forms.Padding(3);
this.tabMembersRoles.Size = new System.Drawing.Size(409, 481);
this.tabMembersRoles.TabIndex = 1;
this.tabMembersRoles.Text = "Members & Roles";
this.tabMembersRoles.UseVisualStyleBackColor = true;
//
// tabsMRA
//
this.tabsMRA.Controls.Add(this.tabMembers);
this.tabsMRA.Controls.Add(this.tabRoles);
this.tabsMRA.Controls.Add(this.tabAbilities);
this.tabsMRA.Location = new System.Drawing.Point(6, 6);
this.tabsMRA.Name = "tabsMRA";
this.tabsMRA.SelectedIndex = 0;
this.tabsMRA.Size = new System.Drawing.Size(400, 469);
this.tabsMRA.TabIndex = 0;
//
// tabMembers
//
this.tabMembers.Controls.Add(this.cmdEject);
this.tabMembers.Controls.Add(this.lstMembers2);
this.tabMembers.Controls.Add(this.chkListRoles);
this.tabMembers.Controls.Add(this.treeAbilities);
this.tabMembers.Controls.Add(this.label2);
this.tabMembers.Controls.Add(this.label1);
this.tabMembers.Location = new System.Drawing.Point(4, 22);
this.tabMembers.Name = "tabMembers";
this.tabMembers.Padding = new System.Windows.Forms.Padding(3);
this.tabMembers.Size = new System.Drawing.Size(392, 443);
this.tabMembers.TabIndex = 0;
this.tabMembers.Text = "Members";
this.tabMembers.UseVisualStyleBackColor = true;
//
// cmdEject
//
this.cmdEject.Location = new System.Drawing.Point(258, 152);
this.cmdEject.Name = "cmdEject";
this.cmdEject.Size = new System.Drawing.Size(128, 23);
this.cmdEject.TabIndex = 15;
this.cmdEject.Text = "Eject From Group";
this.cmdEject.UseVisualStyleBackColor = true;
//
// lstMembers2
//
this.lstMembers2.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3});
this.lstMembers2.Location = new System.Drawing.Point(6, 6);
this.lstMembers2.Name = "lstMembers2";
this.lstMembers2.Size = new System.Drawing.Size(380, 140);
this.lstMembers2.TabIndex = 14;
this.lstMembers2.UseCompatibleStateImageBehavior = false;
this.lstMembers2.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Member Name";
this.columnHeader1.Width = 152;
//
// columnHeader2
//
this.columnHeader2.Text = "Donated Tier";
this.columnHeader2.Width = 119;
//
// columnHeader3
//
this.columnHeader3.Text = "Last Login";
this.columnHeader3.Width = 96;
//
// chkListRoles
//
this.chkListRoles.FormattingEnabled = true;
this.chkListRoles.Location = new System.Drawing.Point(6, 196);
this.chkListRoles.Name = "chkListRoles";
this.chkListRoles.Size = new System.Drawing.Size(147, 244);
this.chkListRoles.TabIndex = 8;
//
// treeAbilities
//
this.treeAbilities.Location = new System.Drawing.Point(159, 196);
this.treeAbilities.Name = "treeAbilities";
this.treeAbilities.Size = new System.Drawing.Size(227, 244);
this.treeAbilities.TabIndex = 7;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(156, 180);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(82, 13);
this.label2.TabIndex = 6;
this.label2.Text = "Allowed Abilities";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 180);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Assigned Roles";
//
// tabRoles
//
this.tabRoles.Location = new System.Drawing.Point(4, 22);
this.tabRoles.Name = "tabRoles";
this.tabRoles.Padding = new System.Windows.Forms.Padding(3);
this.tabRoles.Size = new System.Drawing.Size(392, 443);
this.tabRoles.TabIndex = 1;
this.tabRoles.Text = "Roles";
this.tabRoles.UseVisualStyleBackColor = true;
//
// tabAbilities
//
this.tabAbilities.Location = new System.Drawing.Point(4, 22);
this.tabAbilities.Name = "tabAbilities";
this.tabAbilities.Size = new System.Drawing.Size(392, 443);
this.tabAbilities.TabIndex = 2;
this.tabAbilities.Text = "Abilities";
this.tabAbilities.UseVisualStyleBackColor = true;
//
// tabNotices
//
this.tabNotices.Controls.Add(this.textBox1);
this.tabNotices.Controls.Add(this.label3);
this.tabNotices.Controls.Add(this.cmdRefreshNotices);
this.tabNotices.Controls.Add(this.lstNotices);
this.tabNotices.Location = new System.Drawing.Point(4, 22);
this.tabNotices.Name = "tabNotices";
this.tabNotices.Size = new System.Drawing.Size(409, 481);
this.tabNotices.TabIndex = 2;
this.tabNotices.Text = "Notices";
this.tabNotices.UseVisualStyleBackColor = true;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(3, 239);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(403, 239);
this.textBox1.TabIndex = 18;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(3, 223);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(83, 13);
this.label3.TabIndex = 17;
this.label3.Text = "Archived Notice";
//
// cmdRefreshNotices
//
this.cmdRefreshNotices.Location = new System.Drawing.Point(289, 194);
this.cmdRefreshNotices.Name = "cmdRefreshNotices";
this.cmdRefreshNotices.Size = new System.Drawing.Size(117, 23);
this.cmdRefreshNotices.TabIndex = 16;
this.cmdRefreshNotices.Text = "Refresh List";
this.cmdRefreshNotices.UseVisualStyleBackColor = true;
//
// lstNotices
//
this.lstNotices.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader4,
this.columnHeader5,
this.columnHeader6});
this.lstNotices.Location = new System.Drawing.Point(3, 8);
this.lstNotices.Name = "lstNotices";
this.lstNotices.Size = new System.Drawing.Size(403, 180);
this.lstNotices.TabIndex = 15;
this.lstNotices.UseCompatibleStateImageBehavior = false;
this.lstNotices.View = System.Windows.Forms.View.Details;
//
// columnHeader4
//
this.columnHeader4.Text = "Subject";
this.columnHeader4.Width = 184;
//
// columnHeader5
//
this.columnHeader5.Text = "From";
this.columnHeader5.Width = 125;
//
// columnHeader6
//
this.columnHeader6.Text = "Date";
this.columnHeader6.Width = 87;
//
// tabProposals
//
this.tabProposals.Location = new System.Drawing.Point(4, 22);
this.tabProposals.Name = "tabProposals";
this.tabProposals.Size = new System.Drawing.Size(409, 481);
this.tabProposals.TabIndex = 3;
this.tabProposals.Text = "Proposals";
this.tabProposals.UseVisualStyleBackColor = true;
//
// tabLand
//
this.tabLand.Controls.Add(this.tabsMoney);
this.tabLand.Controls.Add(this.txtContribution);
this.tabLand.Controls.Add(this.lblLandAvailable);
this.tabLand.Controls.Add(this.lblLandInUse);
this.tabLand.Controls.Add(this.lblTotalContribution);
this.tabLand.Controls.Add(this.label7);
this.tabLand.Controls.Add(this.label6);
this.tabLand.Controls.Add(this.label5);
this.tabLand.Controls.Add(this.label4);
this.tabLand.Controls.Add(this.lstLand);
this.tabLand.Location = new System.Drawing.Point(4, 22);
this.tabLand.Name = "tabLand";
this.tabLand.Size = new System.Drawing.Size(409, 481);
this.tabLand.TabIndex = 4;
this.tabLand.Text = "Land & L$";
this.tabLand.UseVisualStyleBackColor = true;
//
// tabsMoney
//
this.tabsMoney.Controls.Add(this.tabPlanning);
this.tabsMoney.Controls.Add(this.tabDetails);
this.tabsMoney.Controls.Add(this.tabSales);
this.tabsMoney.Location = new System.Drawing.Point(3, 278);
this.tabsMoney.Name = "tabsMoney";
this.tabsMoney.SelectedIndex = 0;
this.tabsMoney.Size = new System.Drawing.Size(406, 200);
this.tabsMoney.TabIndex = 24;
//
// tabPlanning
//
this.tabPlanning.Controls.Add(this.txtPlanning);
this.tabPlanning.Location = new System.Drawing.Point(4, 22);
this.tabPlanning.Name = "tabPlanning";
this.tabPlanning.Padding = new System.Windows.Forms.Padding(3);
this.tabPlanning.Size = new System.Drawing.Size(398, 174);
this.tabPlanning.TabIndex = 0;
this.tabPlanning.Text = "Planning";
this.tabPlanning.UseVisualStyleBackColor = true;
//
// txtPlanning
//
this.txtPlanning.Location = new System.Drawing.Point(6, 5);
this.txtPlanning.Multiline = true;
this.txtPlanning.Name = "txtPlanning";
this.txtPlanning.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtPlanning.Size = new System.Drawing.Size(386, 163);
this.txtPlanning.TabIndex = 13;
//
// tabDetails
//
this.tabDetails.Controls.Add(this.txtDetails);
this.tabDetails.Location = new System.Drawing.Point(4, 22);
this.tabDetails.Name = "tabDetails";
this.tabDetails.Padding = new System.Windows.Forms.Padding(3);
this.tabDetails.Size = new System.Drawing.Size(398, 174);
this.tabDetails.TabIndex = 1;
this.tabDetails.Text = "Details";
this.tabDetails.UseVisualStyleBackColor = true;
//
// txtDetails
//
this.txtDetails.Location = new System.Drawing.Point(6, 6);
this.txtDetails.Multiline = true;
this.txtDetails.Name = "txtDetails";
this.txtDetails.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtDetails.Size = new System.Drawing.Size(386, 163);
this.txtDetails.TabIndex = 14;
//
// tabSales
//
this.tabSales.Controls.Add(this.txtSales);
this.tabSales.Location = new System.Drawing.Point(4, 22);
this.tabSales.Name = "tabSales";
this.tabSales.Size = new System.Drawing.Size(398, 174);
this.tabSales.TabIndex = 2;
this.tabSales.Text = "Sales";
this.tabSales.UseVisualStyleBackColor = true;
//
// txtSales
//
this.txtSales.Location = new System.Drawing.Point(6, 6);
this.txtSales.Multiline = true;
this.txtSales.Name = "txtSales";
this.txtSales.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtSales.Size = new System.Drawing.Size(386, 163);
this.txtSales.TabIndex = 14;
//
// txtContribution
//
this.txtContribution.Location = new System.Drawing.Point(157, 237);
this.txtContribution.Name = "txtContribution";
this.txtContribution.Size = new System.Drawing.Size(94, 20);
this.txtContribution.TabIndex = 23;
//
// lblLandAvailable
//
this.lblLandAvailable.AutoSize = true;
this.lblLandAvailable.Location = new System.Drawing.Point(154, 221);
this.lblLandAvailable.Name = "lblLandAvailable";
this.lblLandAvailable.Size = new System.Drawing.Size(13, 13);
this.lblLandAvailable.TabIndex = 22;
this.lblLandAvailable.Text = "0";
//
// lblLandInUse
//
this.lblLandInUse.AutoSize = true;
this.lblLandInUse.Location = new System.Drawing.Point(154, 199);
this.lblLandInUse.Name = "lblLandInUse";
this.lblLandInUse.Size = new System.Drawing.Size(13, 13);
this.lblLandInUse.TabIndex = 21;
this.lblLandInUse.Text = "0";
//
// lblTotalContribution
//
this.lblTotalContribution.AutoSize = true;
this.lblTotalContribution.Location = new System.Drawing.Point(154, 176);
this.lblTotalContribution.Name = "lblTotalContribution";
this.lblTotalContribution.Size = new System.Drawing.Size(13, 13);
this.lblTotalContribution.TabIndex = 20;
this.lblTotalContribution.Text = "0";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(57, 244);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(91, 13);
this.label7.TabIndex = 19;
this.label7.Text = "Your Contribution:";
this.label7.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(68, 221);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(80, 13);
this.label6.TabIndex = 18;
this.label6.Text = "Land Available:";
this.label6.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(53, 199);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(95, 13);
this.label5.TabIndex = 17;
this.label5.Text = "Total Land In Use:";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(55, 176);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(93, 13);
this.label4.TabIndex = 16;
this.label4.Text = "Total Contribution:";
this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// lstLand
//
this.lstLand.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader7,
this.columnHeader8,
this.columnHeader9});
this.lstLand.Location = new System.Drawing.Point(3, 3);
this.lstLand.Name = "lstLand";
this.lstLand.Size = new System.Drawing.Size(403, 140);
this.lstLand.TabIndex = 15;
this.lstLand.UseCompatibleStateImageBehavior = false;
this.lstLand.View = System.Windows.Forms.View.Details;
//
// columnHeader7
//
this.columnHeader7.Text = "Parcel Name";
this.columnHeader7.Width = 180;
//
// columnHeader8
//
this.columnHeader8.Text = "Region";
this.columnHeader8.Width = 119;
//
// columnHeader9
//
this.columnHeader9.Text = "Area";
this.columnHeader9.Width = 93;
//
// cmdApply
//
this.cmdApply.Location = new System.Drawing.Point(348, 520);
this.cmdApply.Name = "cmdApply";
this.cmdApply.Size = new System.Drawing.Size(75, 23);
this.cmdApply.TabIndex = 10;
this.cmdApply.Text = "Apply";
this.cmdApply.UseVisualStyleBackColor = true;
//
// cmdCancel
//
this.cmdCancel.Location = new System.Drawing.Point(267, 520);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(75, 23);
this.cmdCancel.TabIndex = 11;
this.cmdCancel.Text = "Cancel";
this.cmdCancel.UseVisualStyleBackColor = true;
//
// cmdOK
//
this.cmdOK.Location = new System.Drawing.Point(186, 520);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(75, 23);
this.cmdOK.TabIndex = 12;
this.cmdOK.Text = "OK";
this.cmdOK.UseVisualStyleBackColor = true;
//
// cmdRefresh
//
this.cmdRefresh.Location = new System.Drawing.Point(6, 520);
this.cmdRefresh.Name = "cmdRefresh";
this.cmdRefresh.Size = new System.Drawing.Size(121, 23);
this.cmdRefresh.TabIndex = 13;
this.cmdRefresh.Text = "Refresh from server";
this.cmdRefresh.UseVisualStyleBackColor = true;
//
// frmGroupInfo
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(431, 548);
this.Controls.Add(this.cmdRefresh);
this.Controls.Add(this.cmdOK);
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdApply);
this.Controls.Add(this.tabs);
this.MaximizeBox = false;
this.Name = "frmGroupInfo";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Group Information";
this.tabs.ResumeLayout(false);
this.tabGeneral.ResumeLayout(false);
this.tabGeneral.PerformLayout();
this.grpPreferences.ResumeLayout(false);
this.grpPreferences.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numFee)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picInsignia)).EndInit();
this.tabMembersRoles.ResumeLayout(false);
this.tabsMRA.ResumeLayout(false);
this.tabMembers.ResumeLayout(false);
this.tabMembers.PerformLayout();
this.tabNotices.ResumeLayout(false);
this.tabNotices.PerformLayout();
this.tabLand.ResumeLayout(false);
this.tabLand.PerformLayout();
this.tabsMoney.ResumeLayout(false);
this.tabPlanning.ResumeLayout(false);
this.tabPlanning.PerformLayout();
this.tabDetails.ResumeLayout(false);
this.tabDetails.PerformLayout();
this.tabSales.ResumeLayout(false);
this.tabSales.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabs;
private System.Windows.Forms.TabPage tabGeneral;
private System.Windows.Forms.GroupBox grpPreferences;
private System.Windows.Forms.CheckBox chkMature;
private System.Windows.Forms.NumericUpDown numFee;
private System.Windows.Forms.CheckBox chkGroupNotices;
private System.Windows.Forms.CheckBox chkFee;
private System.Windows.Forms.CheckBox chkOpenEnrollment;
private System.Windows.Forms.CheckBox chkPublish;
private System.Windows.Forms.CheckBox chkShow;
private System.Windows.Forms.ListView lstMembers;
private System.Windows.Forms.ColumnHeader colName;
private System.Windows.Forms.ColumnHeader colTitle;
private System.Windows.Forms.ColumnHeader colLasLogin;
private System.Windows.Forms.TextBox txtCharter;
private System.Windows.Forms.Label lblFoundedBy;
private System.Windows.Forms.Label lblGroupName;
private System.Windows.Forms.PictureBox picInsignia;
private System.Windows.Forms.TabPage tabMembersRoles;
private System.Windows.Forms.TabPage tabNotices;
private System.Windows.Forms.TabPage tabProposals;
private System.Windows.Forms.TabPage tabLand;
private System.Windows.Forms.Button cmdApply;
private System.Windows.Forms.Button cmdCancel;
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.Button cmdRefresh;
private System.Windows.Forms.TabControl tabsMRA;
private System.Windows.Forms.TabPage tabMembers;
private System.Windows.Forms.TabPage tabRoles;
private System.Windows.Forms.TabPage tabAbilities;
private System.Windows.Forms.ListView lstMembers2;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.CheckedListBox chkListRoles;
private System.Windows.Forms.TreeView treeAbilities;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button cmdEject;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button cmdRefreshNotices;
private System.Windows.Forms.ListView lstNotices;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.ColumnHeader columnHeader6;
private System.Windows.Forms.ListView lstLand;
private System.Windows.Forms.ColumnHeader columnHeader7;
private System.Windows.Forms.ColumnHeader columnHeader8;
private System.Windows.Forms.ColumnHeader columnHeader9;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TabControl tabsMoney;
private System.Windows.Forms.TabPage tabPlanning;
private System.Windows.Forms.TabPage tabDetails;
private System.Windows.Forms.TextBox txtContribution;
private System.Windows.Forms.Label lblLandAvailable;
private System.Windows.Forms.Label lblLandInUse;
private System.Windows.Forms.Label lblTotalContribution;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox txtPlanning;
private System.Windows.Forms.TextBox txtDetails;
private System.Windows.Forms.TabPage tabSales;
private System.Windows.Forms.TextBox txtSales;
private System.Windows.Forms.Label labelInsigniaProgress;
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
namespace ExcelDna.IntelliSense
{
// NOTE: We're using the COM wrapper (UIAComWrapper) approach to UI Automation, rather than using the old System.Automation in .NET BCL
// My understanding is from this post : https://social.msdn.microsoft.com/Forums/en-US/69cf1072-d57f-4aa1-a8ea-ea8a9a5da70a/using-uiautomation-via-com-interopuiautomationclientdll-causes-windows-explorer-to-crash?forum=windowsaccessibilityandautomation
// I think this is a sample of the new UI Automation 3.0 COM API: http://blogs.msdn.com/b/winuiautomation/archive/2012/03/06/windows-7-ui-automation-client-api-c-sample-e-mail-reader-version-1-0.aspx
// Really need to keep in mind the threading guidance from here: https://msdn.microsoft.com/en-us/library/windows/desktop/ee671692(v=vs.85).aspx
// NOTE: Check that the TextPattern is available where expected under Windows 7 (remember about CLSID_CUIAutomation8 class)
// NOTE: More ideas on tracking the current topmost window (using Application events): http://www.jkp-ads.com/Articles/keepuserformontop02.asp
// All the code in this class runs on the Automation thread, including events we handle from the WinEventHook.
class WindowWatcher : IDisposable
{
public class WindowChangedEventArgs : EventArgs
{
public enum ChangeType
{
Create = 1,
Destroy = 2,
Show = 3,
Hide = 4,
Focus = 5,
Unfocus = 6,
LocationChange = 7
}
public enum ChangeObjectId
{
Unknown = -1,
Self = 1,
Client = 2,
Caret = 3,
}
public readonly IntPtr WindowHandle;
public readonly ChangeType Type;
public readonly ChangeObjectId ObjectId;
internal WindowChangedEventArgs(IntPtr windowHandle, ChangeType changeType, ChangeObjectId objectId)
{
WindowHandle = windowHandle;
Type = changeType;
ObjectId = objectId;
}
internal WindowChangedEventArgs(IntPtr windowHandle, WinEventHook.WinEvent winEvent, WinEventHook.WinEventObjectId objectId)
{
WindowHandle = windowHandle;
switch (winEvent)
{
case WinEventHook.WinEvent.EVENT_OBJECT_CREATE:
Type = ChangeType.Create;
break;
case WinEventHook.WinEvent.EVENT_OBJECT_DESTROY:
Type = ChangeType.Destroy;
break;
case WinEventHook.WinEvent.EVENT_OBJECT_SHOW:
Type = ChangeType.Show;
break;
case WinEventHook.WinEvent.EVENT_OBJECT_HIDE:
Type = ChangeType.Hide;
break;
case WinEventHook.WinEvent.EVENT_OBJECT_FOCUS:
Type = ChangeType.Focus;
break;
case WinEventHook.WinEvent.EVENT_OBJECT_LOCATIONCHANGE:
Type = ChangeType.LocationChange;
break;
default:
// throw new ArgumentException("Unexpected WinEvent type", nameof(winEvent));
break;
}
switch (objectId)
{
case WinEventHook.WinEventObjectId.OBJID_SELF:
ObjectId = ChangeObjectId.Self;
break;
case WinEventHook.WinEventObjectId.OBJID_CLIENT:
ObjectId = ChangeObjectId.Client;
break;
case WinEventHook.WinEventObjectId.OBJID_CARET:
ObjectId = ChangeObjectId.Caret;
break;
default:
//Debug.Fail("Unexpected ObjectId");
ObjectId = ChangeObjectId.Unknown;
break;
}
}
}
const string _mainWindowClass = "XLMAIN";
const string _sheetWindowClass = "EXCEL7"; // This is the sheet portion (not top level) - we get some notifications from here?
const string _formulaBarClass = "EXCEL<";
const string _inCellEditClass = "EXCEL6";
const string _popupListClass = "__XLACOOUTER";
const string _excelToolTipClass = "XLToolTip";
const string _nuiDialogClass = "NUIDialog";
const string _selectDataSourceTitle = "Select Data Source"; // TODO: How does localization work?
WinEventHook _windowStateChangeHook;
// These track keyboard focus for Windows in the Excel process
// Used to synthesize the 'Unfocus' change events
IntPtr _focusedWindowHandle;
string _focusedWindowClassName;
// public IntPtr SelectDataSourceWindow { get; private set; }
// public bool IsSelectDataSourceWindowVisible { get; private set; }
// NOTE: The WindowWatcher raises all events on our Automation thread (via syncContextAuto passed into the constructor).
// Raised for every WinEvent related to window of the relevant class
public event EventHandler<WindowChangedEventArgs> FormulaBarWindowChanged;
public event EventHandler<WindowChangedEventArgs> InCellEditWindowChanged;
public event EventHandler<WindowChangedEventArgs> PopupListWindowChanged;
public event EventHandler<WindowChangedEventArgs> ExcelToolTipWindowChanged;
public event EventHandler FormulaEditLocationChanged;
// public event EventHandler<WindowChangedEventArgs> SelectDataSourceWindowChanged;
public WindowWatcher(SynchronizationContext syncContextAuto, SynchronizationContext syncContextMain)
{
#pragma warning disable CS0618 // Type or member is obsolete (GetCurrentThreadId) - But for debugging we want to monitor this anyway
// Debug.Print($"### WindowWatcher created on thread: Managed {Thread.CurrentThread.ManagedThreadId}, Native {AppDomain.GetCurrentThreadId()}");
#pragma warning restore CS0618 // Type or member is obsolete
// Using WinEvents instead of Automation so that we can watch top-level window changes, but only from the right (current Excel) process.
// TODO: We need to dramatically reduce the number of events we grab here...
_windowStateChangeHook = new WinEventHook(WinEventHook.WinEvent.EVENT_OBJECT_CREATE, WinEventHook.WinEvent.EVENT_OBJECT_LOCATIONCHANGE, syncContextAuto, syncContextMain, IntPtr.Zero);
// _windowStateChangeHook = new WinEventHook(WinEventHook.WinEvent.EVENT_OBJECT_CREATE, WinEventHook.WinEvent.EVENT_OBJECT_END, syncContextAuto, IntPtr.Zero);
// _windowStateChangeHook = new WinEventHook(WinEventHook.WinEvent.EVENT_MIN, WinEventHook.WinEvent.EVENT_AIA_END, syncContextAuto, IntPtr.Zero);
_windowStateChangeHook.WinEventReceived += _windowStateChangeHook_WinEventReceived;
}
// Runs on the Automation thread (before syncContextAuto starts pumping)
public void TryInitialize()
{
Debug.Print("### WindowWatcher TryInitialize on thread: " + Thread.CurrentThread.ManagedThreadId);
var focusedWindowHandle = Win32Helper.GetFocusedWindowHandle();
string className = null;
if (focusedWindowHandle != IntPtr.Zero)
className = Win32Helper.GetClassName(focusedWindowHandle);
UpdateFocus(focusedWindowHandle, className);
}
bool UpdateFocus(IntPtr windowHandle, string windowClassName)
{
if (windowHandle == _focusedWindowHandle && _focusedWindowClassName == windowClassName)
return false;
// We see a change in the WindowClassName often - handle that as a focus change too
Debug.Assert(_focusedWindowClassName != _excelToolTipClass); // We don't expect the ToolTip to ever get the focus
Logger.WindowWatcher.Verbose($"Focus lost by {_focusedWindowHandle} ({_focusedWindowClassName})");
// It has changed - raise an event for the old window
switch (_focusedWindowClassName)
{
case _popupListClass:
PopupListWindowChanged?.Invoke(this, new WindowChangedEventArgs(_focusedWindowHandle, WindowChangedEventArgs.ChangeType.Unfocus, WindowChangedEventArgs.ChangeObjectId.Self));
break;
case _inCellEditClass:
InCellEditWindowChanged?.Invoke(this, new WindowChangedEventArgs(_focusedWindowHandle, WindowChangedEventArgs.ChangeType.Unfocus, WindowChangedEventArgs.ChangeObjectId.Self));
break;
case _formulaBarClass:
FormulaBarWindowChanged?.Invoke(this, new WindowChangedEventArgs(_focusedWindowHandle, WindowChangedEventArgs.ChangeType.Unfocus, WindowChangedEventArgs.ChangeObjectId.Self));
break;
//case _nuiDialogClass:
default:
// Not one of our watched window, so we don't care
break;
}
// Set the new focus info
// Event will be raised by WinEventReceived handler itself
_focusedWindowHandle = windowHandle;
_focusedWindowClassName = windowClassName;
Logger.WindowWatcher.Verbose($"Focus changed to {windowHandle} ({windowClassName})");
return true;
}
// This runs on the Automation thread, via SyncContextAuto passed in to WinEventHook when we created this WindowWatcher
// CONSIDER: We would be able to run all the watcher updates from WinEvents, including Location and Selection changes,
// but since WinEvents have no hwnd filter, UIAutomation events might be more efficient.
// CONSIDER: Performance optimisation would keep a list of window handles we know about, preventing the class name check every time
// NOTE: We are not getting OBJID_CURSOR events here - that means we expect to have a valid WindowHandle except when destroyed
void _windowStateChangeHook_WinEventReceived(object sender, WinEventHook.WinEventArgs e)
{
if (e.WindowHandle == IntPtr.Zero)
{
Debug.Fail("WinEvent with window 0!?");
}
if (e.EventType == WinEventHook.WinEvent.EVENT_OBJECT_FOCUS)
{
// Might raise change event for Unfocus
if (!UpdateFocus(e.WindowHandle, e.WindowClassName))
{
// We already have the right focus
return;
}
}
// Debug.Print("### Thread receiving WindowStateChange: " + Thread.CurrentThread.ManagedThreadId);
switch (e.WindowClassName)
{
//case _sheetWindowClass:
// if (e.EventType == WinEventHook.WinEvent.EVENT_OBJECT_SHOW)
// {
// // Maybe a new workbook is on top...
// // Note that there is also an EVENT_OBJECT_PARENTCHANGE (which we are not subscribing to at the moment
// }
// break;
case _popupListClass:
PopupListWindowChanged?.Invoke(this, new WindowChangedEventArgs(e.WindowHandle, e.EventType, e.ObjectId));
break;
case _inCellEditClass:
InCellEditWindowChanged?.Invoke(this, new WindowChangedEventArgs(e.WindowHandle, e.EventType, e.ObjectId));
break;
case _formulaBarClass:
FormulaBarWindowChanged?.Invoke(this, new WindowChangedEventArgs(e.WindowHandle, e.EventType, e.ObjectId));
break;
case _excelToolTipClass:
ExcelToolTipWindowChanged?.Invoke(this, new WindowChangedEventArgs(e.WindowHandle, e.EventType, e.ObjectId));
break;
//case _nuiDialogClass:
// // Debug.Print($"SelectDataSource {_selectDataSourceClass} Window update: {e.WindowHandle:X}, EventType: {e.EventType}, idChild: {e.ChildId}");
// if (e.EventType == WinEventHook.WinEvent.EVENT_OBJECT_CREATE)
// {
// // Get the name of this window - maybe ours or some other NUIDialog
// var windowTitle = Win32Helper.GetText(e.WindowHandle);
// if (windowTitle.Equals(_selectDataSourceTitle, StringComparison.OrdinalIgnoreCase))
// {
// SelectDataSourceWindow = e.WindowHandle;
// SelectDataSourceWindowChanged?.Invoke(this,
// new WindowChangedEventArgs { Type = WindowChangedEventArgs.ChangeType.Create });
// }
// }
// else if (SelectDataSourceWindow == e.WindowHandle && e.EventType == WinEventHook.WinEvent.EVENT_OBJECT_SHOW)
// {
// IsSelectDataSourceWindowVisible = true;
// SelectDataSourceWindowChanged?.Invoke(this,
// new WindowChangedEventArgs { Type = WindowChangedEventArgs.ChangeType.Create });
// }
// else if (SelectDataSourceWindow == e.WindowHandle && e.EventType == WinEventHook.WinEvent.EVENT_OBJECT_HIDE)
// {
// IsSelectDataSourceWindowVisible = false;
// SelectDataSourceWindowChanged?.Invoke(this, new WindowChangedEventArgs { Type = WindowChangedEventArgs.ChangeType.Hide });
// }
// else if (SelectDataSourceWindow == e.WindowHandle && e.EventType == WinEventHook.WinEvent.EVENT_OBJECT_DESTROY)
// {
// IsSelectDataSourceWindowVisible = false;
// SelectDataSourceWindow = IntPtr.Zero;
// SelectDataSourceWindowChanged?.Invoke(this, new WindowChangedEventArgs { Type = WindowChangedEventArgs.ChangeType.Destroy });
// }
// break;
default:
//InCellEditWindowChanged(this, EventArgs.Empty);
break;
}
}
// Fired from the FormulaEditWatcher...
// CONSIDER: We might restructure the location watching, so that it happens here, rather than in the FormulaEdit
internal void OnFormulaEditLocationChanged()
{
FormulaEditLocationChanged?.Invoke(this, EventArgs.Empty);
}
// Must run on the main thread
public void Dispose()
{
Debug.Assert(Thread.CurrentThread.ManagedThreadId == 1);
if (_windowStateChangeHook != null)
{
_windowStateChangeHook.Dispose();
_windowStateChangeHook = null;
}
}
}
//class SelectDataSourceWatcher : IDisposable
//{
// SynchronizationContext _syncContextAuto;
// WindowWatcher _windowWatcher;
// public IntPtr SelectDataSourceWindow { get; private set; }
// public event EventHandler SelectDataSourceWindowChanged;
// public bool IsVisible { get; private set; }
// public event EventHandler IsVisibleChanged;
// public SelectDataSourceWatcher(WindowWatcher windowWatcher, SynchronizationContext syncContextAuto)
// {
// _syncContextAuto = syncContextAuto;
// _windowWatcher = windowWatcher;
// _windowWatcher.SelectDataSourceWindowChanged += _windowWatcher_SelectDataSourceWindowChanged;
// //_windowWatcher.MainWindowChanged += _windowWatcher_MainWindowChanged;
// //_windowWatcher.PopupListWindowChanged += _windowWatcher_PopupListWindowChanged;
// }
// void _windowWatcher_SelectDataSourceWindowChanged(object sender, WindowWatcher.WindowChangedEventArgs e)
// {
// }
// public void Dispose()
// {
// Debug.Print("Disposing SelectDataSourceWatcher");
// // CONSIDER: Do we need this?
// //_windowWatcher.MainWindowChanged -= _windowWatcher_MainWindowChanged;
// //_windowWatcher.PopupListWindowChanged -= _windowWatcher_PopupListWindowChanged;
// _windowWatcher.SelectDataSourceWindowChanged -= _windowWatcher_SelectDataSourceWindowChanged;
// _windowWatcher = null;
// _syncContextAuto.Post(delegate
// {
// Debug.Print("Disposing SelectDataSourceWatcher - In Automation context");
// }, null);
// }
//}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using System.Threading.Tasks;
using Zu.AsyncChromeDriver.Tests.Environment;
using Zu.AsyncWebDriver;
using Zu.WebBrowser.AsyncInteractions;
namespace Zu.AsyncChromeDriver.Tests
{
[TestFixture]
[Explicit("NotImplemented")]
public class WindowSwitchingTest : DriverTestFixture
{
[Test]
public async Task ShouldSwitchFocusToANewWindowWhenItIsOpenedAndNotStopFutureOperations()
{
await driver.GoToUrl(xhtmlTestPage);
String current = await driver.CurrentWindowHandle();
await driver.FindElement(By.LinkText("Open new window")).Click();
Assert.AreEqual("XHTML Test Page", await driver.Title());
await WaitFor(WindowCountToBe(2), "Window count was not 2");
await WaitFor(WindowWithName("result"), "Could not find window with name 'result'");
await WaitFor(async () => { return await driver.Title() == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'");
Assert.AreEqual("We Arrive Here", await driver.Title());
await driver.GoToUrl(iframesPage);
string handle = await driver.CurrentWindowHandle();
await driver.FindElement(By.Id("iframe_page_heading"));
await driver.SwitchTo().Frame("iframe1");
Assert.AreEqual(await driver.CurrentWindowHandle(), handle);
await driver.SwitchTo().DefaultContent();
await driver.Close();
await driver.SwitchTo().Window(current);
//Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public async Task ShouldThrowNoSuchWindowException()
{
await driver.GoToUrl(xhtmlTestPage);
String current = await driver.CurrentWindowHandle();
try {
await driver.SwitchTo().Window("invalid name");
} catch (NoSuchWindowException) {
// This is expected.
}
await driver.SwitchTo().Window(current);
}
[Test]
public async Task ShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle()
{
await driver.GoToUrl((xhtmlTestPage));
String current = await driver.CurrentWindowHandle();
var currentWindowHandles = await driver.WindowHandles().Count();
await driver.FindElement(By.LinkText("Open new window")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
Assert.AreEqual(2, await driver.WindowHandles().Count());
await WaitFor(WindowWithName("result"), "Could not find window with name 'result'");
await driver.SwitchTo().Window("result");
await driver.Close();
try {
string currentHandle = await driver.CurrentWindowHandle();
Assert.Fail("NoSuchWindowException expected");
} catch (NoSuchWindowException) {
// Expected.
} finally {
await driver.SwitchTo().Window(current);
}
}
[Test]
public async Task ShouldThrowNoSuchWindowExceptionOnAnyOperationIfAWindowIsClosed()
{
await driver.GoToUrl((xhtmlTestPage));
String current = await driver.CurrentWindowHandle();
int currentWindowHandles = await driver.WindowHandles().Count();
await driver.FindElement(By.LinkText("Open new window")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
Assert.AreEqual(2, await driver.WindowHandles().Count());
await WaitFor(WindowWithName("result"), "Could not find window with name 'result'");
await driver.SwitchTo().Window("result");
await driver.Close();
try {
try {
string title = await driver.Title();
Assert.Fail("NoSuchWindowException expected");
} catch (NoSuchWindowException) {
// Expected.
}
try {
await driver.FindElement(By.TagName("body"));
Assert.Fail("NoSuchWindowException expected");
} catch (NoSuchWindowException) {
// Expected.
}
} finally {
await driver.SwitchTo().Window(current);
}
}
[Test]
public async Task ShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIsClosed()
{
await driver.GoToUrl((xhtmlTestPage));
String current = await driver.CurrentWindowHandle();
int currentWindowHandles = await driver.WindowHandles().Count();
await driver.FindElement(By.LinkText("Open new window")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
Assert.AreEqual(2, await driver.WindowHandles().Count());
await WaitFor(WindowWithName("result"), "Could not find window with name 'result'");
await driver.SwitchTo().Window("result");
IWebElement body = await driver.FindElement(By.TagName("body"));
await driver.Close();
try {
string bodyText = await body.Text();
Assert.Fail("NoSuchWindowException expected");
} catch (NoSuchWindowException) {
// Expected.
} finally {
await driver.SwitchTo().Window(current);
}
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)]
public async Task ShouldBeAbleToIterateOverAllOpenWindows()
{
await driver.GoToUrl(xhtmlTestPage);
await driver.FindElement(By.Name("windowOne")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
await driver.FindElement(By.Name("windowTwo")).Click();
await WaitFor(WindowCountToBe(3), "Window count was not 3");
var allWindowHandles = await driver.WindowHandles();
// There should be three windows. We should also see each of the window titles at least once.
List<string> seenHandles = new List<string>();
foreach (string handle in allWindowHandles) {
Assert.That(seenHandles, Has.No.Member(handle));
await driver.SwitchTo().Window(handle);
seenHandles.Add(handle);
}
Assert.AreEqual(3, allWindowHandles.Count);
}
[Test]
public async Task ClickingOnAButtonThatClosesAnOpenWindowDoesNotCauseTheBrowserToHang()
{
await driver.GoToUrl(xhtmlTestPage);
String currentHandle = await driver.CurrentWindowHandle();
await driver.FindElement(By.Name("windowThree")).Click();
await driver.SwitchTo().Window("result");
try {
IWebElement closeElement = await WaitFor(() => driver.FindElement(By.Id("close")), "Could not find element with id 'close'");
await closeElement.Click();
// If we make it this far, we're all good.
} finally {
await driver.SwitchTo().Window(currentHandle);
await driver.FindElement(By.Id("linkId"));
}
}
[Test]
public async Task CanCallGetWindowHandlesAfterClosingAWindow()
{
await driver.GoToUrl(xhtmlTestPage);
String currentHandle = await driver.CurrentWindowHandle();
await driver.FindElement(By.Name("windowThree")).Click();
await driver.SwitchTo().Window("result");
try {
IWebElement closeElement = await WaitFor(() => driver.FindElement(By.Id("close")), "Could not find element with id 'close'");
await closeElement.Click();
var handles = await driver.WindowHandles();
// If we make it this far, we're all good.
} finally {
await driver.SwitchTo().Window(currentHandle);
}
}
[Test]
public async Task CanObtainAWindowHandle()
{
await driver.GoToUrl(xhtmlTestPage);
String currentHandle = await driver.CurrentWindowHandle();
Assert.That(currentHandle, Is.Not.Null);
}
[Test]
public async Task FailingToSwitchToAWindowLeavesTheCurrentWindowAsIs()
{
await driver.GoToUrl(xhtmlTestPage);
String current = await driver.CurrentWindowHandle();
try {
await driver.SwitchTo().Window("i will never exist");
Assert.Fail("Should not be ablt to change to a non-existant window");
} catch (NoSuchWindowException) {
// expected
}
String newHandle = await driver.CurrentWindowHandle();
Assert.AreEqual(current, newHandle);
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)]
public async Task CanCloseWindowWhenMultipleWindowsAreOpen()
{
await driver.GoToUrl(xhtmlTestPage);
await driver.FindElement(By.Name("windowOne")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
var allWindowHandles = await driver.WindowHandles();
// There should be two windows. We should also see each of the window titles at least once.
Assert.AreEqual(2, allWindowHandles.Count);
string handle1 = allWindowHandles[1];
await driver.SwitchTo().Window(handle1);
await driver.Close();
await WaitFor(WindowCountToBe(1), "Window count was not 1");
allWindowHandles = await driver.WindowHandles();
Assert.AreEqual(1, allWindowHandles.Count);
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)]
public async Task CanCloseWindowAndSwitchBackToMainWindow()
{
await driver.GoToUrl(xhtmlTestPage);
var currentWindowHandles = await driver.WindowHandles();
string mainHandle = await driver.CurrentWindowHandle();
await driver.FindElement(By.Name("windowOne")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
var allWindowHandles = await driver.WindowHandles();
// There should be two windows. We should also see each of the window titles at least once.
Assert.AreEqual(2, allWindowHandles.Count);
foreach (string handle in allWindowHandles) {
if (handle != mainHandle) {
await driver.SwitchTo().Window(handle);
await driver.Close();
}
}
await driver.SwitchTo().Window(mainHandle);
string newHandle = await driver.CurrentWindowHandle();
Assert.AreEqual(mainHandle, newHandle);
Assert.AreEqual(1, await driver.WindowHandles().Count());
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)]
public async Task ClosingOnlyWindowShouldNotCauseTheBrowserToHang()
{
await driver.GoToUrl(xhtmlTestPage);
await driver.Close();
}
[Test]
[NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)]
public async Task ShouldFocusOnTheTopMostFrameAfterSwitchingToAWindow()
{
await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("window_switching_tests/page_with_frame.html"));
var currentWindowHandles = await driver.WindowHandles();
string mainWindow = await driver.CurrentWindowHandle();
await driver.FindElement(By.Id("a-link-that-opens-a-new-window")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
await driver.SwitchTo().Frame("myframe");
await driver.SwitchTo().Window("newWindow");
await driver.Close();
await driver.SwitchTo().Window(mainWindow);
await driver.FindElement(By.Name("myframe"));
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public async Task ShouldGetBrowserHandles()
{
await driver.GoToUrl(xhtmlTestPage);
await driver.FindElement(By.LinkText("Open new window")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
string handle1, handle2;
handle1 = await driver.CurrentWindowHandle();
System.Threading.Thread.Sleep(1000);
await driver.SwitchTo().Window("result");
handle2 = await driver.CurrentWindowHandle();
var handles = await driver.WindowHandles();
// At least the two handles we want should be there.
Assert.Contains(handle1, handles, "Should have contained current handle");
Assert.Contains(handle2, handles, "Should have contained result handle");
// Some (semi-)clean up..
await driver.SwitchTo().Window(handle2);
await driver.Close();
await driver.SwitchTo().Window(handle1);
await driver.GoToUrl(macbethPage);
}
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
public async Task CloseShouldCloseCurrentHandleOnly()
{
await driver.GoToUrl(xhtmlTestPage);
await driver.FindElement(By.LinkText("Open new window")).Click();
await WaitFor(WindowCountToBe(2), "Window count was not 2");
string handle1, handle2;
handle1 = await driver.CurrentWindowHandle();
await driver.SwitchTo().Window("result");
handle2 = await driver.CurrentWindowHandle();
await driver.Close();
SleepBecauseWindowsTakeTimeToOpen();
var handles = await driver.WindowHandles();
Assert.That(handles, Has.No.Member(handle2), "Invalid handle still in handle list");
Assert.That(handles, Contains.Item(handle1), "Valid handle not in handle list");
}
private void SleepBecauseWindowsTakeTimeToOpen()
{
try {
System.Threading.Thread.Sleep(1000);
} catch (Exception) {
Assert.Fail("Interrupted");
}
}
private Func<Task<bool>> WindowCountToBe(int desiredCount)
{
return async () => await driver.WindowHandles().Count() == desiredCount;
}
private Func<Task<bool>> WindowWithName(string name)
{
return async () => {
try {
await driver.SwitchTo().Window(name);
return true;
} catch (NoSuchWindowException) {
}
return false;
};
}
private Func<Task<IAlert>> AlertToBePresent()
{
return async () => {
IAlert alert = null;
try {
alert = await driver.SwitchTo().Alert();
} catch (NoAlertPresentException) {
}
return alert;
};
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
/// <summary>
/// Top-level ast for all Python code. Typically represents a module but could also
/// be exec or eval code.
/// </summary>
public sealed class PythonAst : ScopeStatement {
private Statement _body;
private CompilationMode _mode;
private readonly bool _isModule;
private readonly bool _printExpressions;
private ModuleOptions _languageFeatures;
private readonly CompilerContext _compilerContext;
private readonly MSAst.SymbolDocumentInfo _document;
private readonly string/*!*/ _name;
internal int[] _lineLocations;
private PythonVariable _docVariable, _nameVariable, _fileVariable;
private ModuleContext _modContext;
private readonly bool _onDiskProxy;
internal MSAst.Expression _arrayExpression;
private CompilationMode.ConstantInfo _contextInfo;
private Dictionary<PythonVariable, MSAst.Expression> _globalVariables = new Dictionary<PythonVariable, MSAst.Expression>();
internal readonly Profiler _profiler; // captures timing data if profiling
internal const string GlobalContextName = "$globalContext";
internal static MSAst.ParameterExpression _functionCode = Ast.Variable(typeof(FunctionCode), "$functionCode");
internal readonly static MSAst.ParameterExpression/*!*/ _globalArray = Ast.Parameter(typeof(PythonGlobal[]), "$globalArray");
internal static readonly MSAst.ParameterExpression/*!*/ _globalContext = Ast.Parameter(typeof(CodeContext), GlobalContextName);
internal static readonly ReadOnlyCollection<MSAst.ParameterExpression> _arrayFuncParams = new ReadOnlyCollectionBuilder<MSAst.ParameterExpression>(new[] { _globalContext, _functionCode }).ToReadOnlyCollection();
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions) {
ContractUtils.RequiresNotNull(body, "body");
_body = body;
_isModule = isModule;
_printExpressions = printExpressions;
_languageFeatures = languageFeatures;
}
public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context, int[] lineLocations) :
this(isModule, languageFeatures, printExpressions, context) {
ContractUtils.RequiresNotNull(body, "body");
_body = body;
_lineLocations = lineLocations;
}
/// <summary>
/// Creates a new PythonAst without a body. ParsingFinished should be called afterwards to set
/// the body.
/// </summary>
public PythonAst(bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context) {
_isModule = isModule;
_printExpressions = printExpressions;
_languageFeatures = languageFeatures;
_mode = ((PythonCompilerOptions)context.Options).CompilationMode ?? GetCompilationMode(context);
_compilerContext = context;
FuncCodeExpr = _functionCode;
PythonCompilerOptions pco = context.Options as PythonCompilerOptions;
Debug.Assert(pco != null);
string name;
if (!context.SourceUnit.HasPath || (pco.Module & ModuleOptions.ExecOrEvalCode) != 0) {
name = "<module>";
} else {
name = context.SourceUnit.Path;
}
_name = name;
Debug.Assert(_name != null);
PythonOptions po = ((PythonContext)context.SourceUnit.LanguageContext).PythonOptions;
if (po.EnableProfiler
#if FEATURE_REFEMIT
&& _mode != CompilationMode.ToDisk
#endif
) {
_profiler = Profiler.GetProfiler(PyContext);
}
_document = context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid);
}
internal PythonAst(CompilerContext context)
: this(new EmptyStatement(),
true,
ModuleOptions.None,
false,
context,
null) {
_onDiskProxy = true;
}
/// <summary>
/// Called when parsing is complete, the body is built, the line mapping and language features are known.
///
/// This is used in conjunction with the constructor which does not take a body. It enables creating
/// the outer most PythonAst first so that nodes can always have a global parent. This lets an un-bound
/// tree to still provide it's line information immediately after parsing. When we set the location
/// of each node during construction we also set the global parent. When we name bind the global
/// parent gets replaced with the real parent ScopeStatement.
/// </summary>
/// <param name="lineLocations">a mapping of where each line begins</param>
/// <param name="body">The body of code</param>
/// <param name="languageFeatures">The language features which were set during parsing.</param>
public void ParsingFinished(int[] lineLocations, Statement body, ModuleOptions languageFeatures) {
ContractUtils.RequiresNotNull(body, "body");
if (_body != null) {
throw new InvalidOperationException("cannot set body twice");
}
_body = body;
_lineLocations = lineLocations;
_languageFeatures = languageFeatures;
}
/// <summary>
/// Binds an AST and makes it capable of being reduced and compiled. Before calling Bind an AST cannot successfully
/// be reduced.
/// </summary>
public void Bind() {
PythonNameBinder.BindAst(this, _compilerContext);
}
public override string Name {
get {
return "<module>";
}
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_body != null) {
_body.Walk(walker);
}
}
walker.PostWalk(this);
}
#region Name Binding Support
internal override bool ExposesLocalVariable(PythonVariable variable) {
return true;
}
internal override void FinishBind(PythonNameBinder binder) {
_contextInfo = CompilationMode.GetContext();
// create global variables for compiler context.
PythonGlobal[] globalArray = new PythonGlobal[Variables == null ? 0 : Variables.Count];
Dictionary<string, PythonGlobal> globals = new Dictionary<string, PythonGlobal>();
GlobalDictionaryStorage storage = new GlobalDictionaryStorage(globals, globalArray);
var modContext = _modContext = new ModuleContext(new PythonDictionary(storage), PyContext);
#if FEATURE_REFEMIT
if (_mode == CompilationMode.ToDisk) {
_arrayExpression = _globalArray;
} else
#endif
{
var newArray = new ConstantExpression(globalArray);
newArray.Parent = this;
_arrayExpression = newArray;
}
if (Variables != null) {
int globalIndex = 0;
foreach (PythonVariable variable in Variables.Values) {
PythonGlobal global = new PythonGlobal(modContext.GlobalContext, variable.Name);
_globalVariables[variable] = CompilationMode.GetGlobal(GetGlobalContext(), globals.Count, variable, global);
globalArray[globalIndex++] = globals[variable.Name] = global;
}
}
CompilationMode.PublishContext(modContext.GlobalContext, _contextInfo);
}
internal override MSAst.Expression LocalContext {
get {
return GetGlobalContext();
}
}
internal override PythonVariable BindReference(PythonNameBinder binder, PythonReference reference) {
return EnsureVariable(reference.Name);
}
internal override bool TryBindOuter(ScopeStatement from, PythonReference reference, out PythonVariable variable) {
// Unbound variable
from.AddReferencedGlobal(reference.Name);
if (from.HasLateBoundVariableSets) {
// If the context contains unqualified exec, new locals can be introduced
// Therefore we need to turn this into a fully late-bound lookup which
// happens when we don't have a PythonVariable.
variable = null;
return false;
} else {
// Create a global variable to bind to.
variable = EnsureGlobalVariable(reference.Name);
return true;
}
}
internal override bool IsGlobal {
get { return true; }
}
internal PythonVariable DocVariable {
get { return _docVariable; }
set { _docVariable = value; }
}
internal PythonVariable NameVariable {
get { return _nameVariable; }
set { _nameVariable = value; }
}
internal PythonVariable FileVariable {
get { return _fileVariable; }
set { _fileVariable = value; }
}
internal CompilerContext CompilerContext {
get {
return _compilerContext;
}
}
internal MSAst.Expression GlobalArrayInstance {
get {
return _arrayExpression;
}
}
internal MSAst.SymbolDocumentInfo Document {
get {
return _document;
}
}
internal Dictionary<PythonVariable, MSAst.Expression> ModuleVariables {
get {
return _globalVariables;
}
}
internal ModuleContext ModuleContext {
get {
return _modContext;
}
}
/// <summary>
/// Creates a variable at the global level. Called for known globals (e.g. __name__),
/// for variables explicitly declared global by the user, and names accessed
/// but not defined in the lexical scope.
/// </summary>
internal PythonVariable/*!*/ EnsureGlobalVariable(string name) {
PythonVariable variable;
if (!TryGetVariable(name, out variable)) {
variable = CreateVariable(name, VariableKind.Global);
}
return variable;
}
#endregion
#region MSASt.Expression Overrides
public override Type Type {
get {
return CompilationMode.DelegateType;
}
}
/// <summary>
/// Reduces the PythonAst to a LambdaExpression of type Type.
/// </summary>
public override MSAst.Expression Reduce() {
return GetLambda();
}
internal override Microsoft.Scripting.Ast.LightLambdaExpression GetLambda() {
string name = ((PythonCompilerOptions)_compilerContext.Options).ModuleName ?? "<unnamed>";
return CompilationMode.ReduceAst(this, name);
}
#endregion
#region Public API
/// <summary>
/// True division is enabled in this AST.
/// </summary>
public bool TrueDivision {
get { return (_languageFeatures & ModuleOptions.TrueDivision) != 0; }
}
/// <summary>
/// True if the with statement is enabled in this AST.
/// </summary>
public bool AllowWithStatement {
get {
return (_languageFeatures & ModuleOptions.WithStatement) != 0;
}
}
/// <summary>
/// True if absolute imports are enabled
/// </summary>
public bool AbsoluteImports {
get {
return (_languageFeatures & ModuleOptions.AbsoluteImports) != 0;
}
}
internal PythonDivisionOptions DivisionOptions {
get {
return PyContext.PythonOptions.DivisionOptions;
}
}
public Statement Body {
get { return _body; }
}
public bool Module {
get { return _isModule; }
}
#endregion
#region Transformation
/// <summary>
/// Returns a ScriptCode object for this PythonAst. The ScriptCode object
/// can then be used to execute the code against it's closed over scope or
/// to execute it against a different scope.
/// </summary>
internal ScriptCode ToScriptCode() {
return CompilationMode.MakeScriptCode(this);
}
internal MSAst.Expression ReduceWorker() {
var retStmt = _body as ReturnStatement;
if (retStmt != null &&
(_languageFeatures == ModuleOptions.None ||
_languageFeatures == (ModuleOptions.ExecOrEvalCode | ModuleOptions.Interpret) ||
_languageFeatures == (ModuleOptions.ExecOrEvalCode | ModuleOptions.Interpret | ModuleOptions.LightThrow))) {
// for simple eval's we can construct a simple tree which just
// leaves the value on the stack. Return's can't exist in modules
// so this is always safe.
Debug.Assert(!_isModule);
var ret = (ReturnStatement)_body;
Ast simpleBody;
if ((_languageFeatures & ModuleOptions.LightThrow) != 0) {
simpleBody = LightExceptions.Rewrite(retStmt.Expression.Reduce());
} else {
simpleBody = retStmt.Expression.Reduce();
}
var start = IndexToLocation(ret.Expression.StartIndex);
var end = IndexToLocation(ret.Expression.EndIndex);
return Ast.Block(
Ast.DebugInfo(
_document,
start.Line,
start.Column,
end.Line,
end.Column
),
AstUtils.Convert(simpleBody, typeof(object))
);
}
ReadOnlyCollectionBuilder<MSAst.Expression> block = new ReadOnlyCollectionBuilder<MSAst.Expression>();
AddInitialiation(block);
if (_isModule) {
block.Add(AssignValue(GetVariableExpression(_docVariable), Ast.Constant(GetDocumentation(_body))));
}
if (!(_body is SuiteStatement) && _body.CanThrow) {
// we only initialize line numbers in suite statements but if we don't generate a SuiteStatement
// at the top level we can miss some line number updates.
block.Add(UpdateLineNumber(_body.Start.Line));
}
block.Add(_body);
MSAst.Expression body = Ast.Block(block.ToReadOnlyCollection());
body = WrapScopeStatements(body, Body.CanThrow); // new ComboActionRewriter().VisitNode(Transform(ag))
body = AddModulePublishing(body);
body = AddProfiling(body);
if ((((PythonCompilerOptions)_compilerContext.Options).Module & ModuleOptions.LightThrow) != 0) {
body = LightExceptions.Rewrite(body);
}
body = Ast.Label(FunctionDefinition._returnLabel, AstUtils.Convert(body, typeof(object)));
if (body.Type == typeof(void)) {
body = Ast.Block(body, Ast.Constant(null));
}
return body;
}
private void AddInitialiation(ReadOnlyCollectionBuilder<MSAst.Expression> block) {
if (_isModule) {
block.Add(AssignValue(GetVariableExpression(_fileVariable), Ast.Constant(ModuleFileName)));
block.Add(AssignValue(GetVariableExpression(_nameVariable), Ast.Constant(ModuleName)));
}
if (_languageFeatures != ModuleOptions.None || _isModule) {
block.Add(
Ast.Call(
AstMethods.ModuleStarted,
LocalContext,
AstUtils.Constant(_languageFeatures)
)
);
}
}
internal override bool PrintExpressions {
get {
return _printExpressions;
}
}
private MSAst.Expression AddModulePublishing(MSAst.Expression body) {
if (_isModule) {
PythonCompilerOptions pco = _compilerContext.Options as PythonCompilerOptions;
string moduleName = ModuleName;
if ((pco.Module & ModuleOptions.Initialize) != 0) {
var tmp = Ast.Variable(typeof(object), "$originalModule");
// TODO: Should be try/fault
body = Ast.Block(
new[] { tmp },
AstUtils.Try(
Ast.Assign(tmp, Ast.Call(AstMethods.PublishModule, LocalContext, Ast.Constant(moduleName))),
body
).Catch(
typeof(Exception),
Ast.Call(AstMethods.RemoveModule, LocalContext, Ast.Constant(moduleName), tmp),
Ast.Rethrow(body.Type)
)
);
}
}
return body;
}
private string ModuleFileName {
get {
return _name;
}
}
private string ModuleName {
get {
PythonCompilerOptions pco = _compilerContext.Options as PythonCompilerOptions;
string moduleName = pco.ModuleName;
if (moduleName == null) {
#if FEATURE_GETINVALIDFILENAMECHARS
if (_compilerContext.SourceUnit.HasPath && _compilerContext.SourceUnit.Path.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) {
moduleName = Path.GetFileNameWithoutExtension(_compilerContext.SourceUnit.Path);
#else
if (_compilerContext.SourceUnit.HasPath) {
moduleName = _compilerContext.SourceUnit.Path;
#endif
} else {
moduleName = "<module>";
}
}
return moduleName;
}
}
internal override FunctionAttributes Flags {
get {
ModuleOptions features = ((PythonCompilerOptions)_compilerContext.Options).Module;
FunctionAttributes funcAttrs = 0;
if ((features & ModuleOptions.TrueDivision) != 0) {
funcAttrs |= FunctionAttributes.FutureDivision;
}
return funcAttrs;
}
}
internal SourceUnit SourceUnit {
get {
if (_compilerContext == null) {
return null;
}
return _compilerContext.SourceUnit;
}
}
internal string[] GetNames() {
string[] res = new string[Variables.Count];
int i = 0;
foreach (var variable in Variables.Values) {
res[i++] = variable.Name;
}
return res;
}
#endregion
#region Compilation Mode (TODO: Factor out)
private static Compiler.CompilationMode GetCompilationMode(CompilerContext context) {
PythonCompilerOptions options = (PythonCompilerOptions)context.Options;
if ((options.Module & ModuleOptions.ExecOrEvalCode) != 0) {
return CompilationMode.Lookup;
}
#if FEATURE_REFEMIT
PythonContext pc = ((PythonContext)context.SourceUnit.LanguageContext);
return ((pc.PythonOptions.Optimize || options.Optimized) && !pc.PythonOptions.LightweightScopes) ?
CompilationMode.Uncollectable :
CompilationMode.Collectable;
#else
return CompilationMode.Collectable;
#endif
}
internal CompilationMode CompilationMode {
get {
return _mode;
}
}
private MSAst.Expression GetGlobalContext() {
if (_contextInfo != null) {
return _contextInfo.Expression;
}
return _globalContext;
}
internal void PrepareScope(ReadOnlyCollectionBuilder<MSAst.ParameterExpression> locals, List<MSAst.Expression> init) {
CompilationMode.PrepareScope(this, locals, init);
}
internal new MSAst.Expression Constant(object value) {
return new PythonConstantExpression(CompilationMode, value);
}
#endregion
#region Binder Factories
internal MSAst.Expression/*!*/ Convert(Type/*!*/ type, ConversionResultKind resultKind, MSAst.Expression/*!*/ target) {
if (resultKind == ConversionResultKind.ExplicitCast) {
return new DynamicConvertExpression(
PyContext.Convert(
type,
resultKind
),
CompilationMode,
target
);
}
return CompilationMode.Dynamic(
PyContext.Convert(
type,
resultKind
),
type,
target
);
}
internal MSAst.Expression/*!*/ Operation(Type/*!*/ resultType, PythonOperationKind operation, MSAst.Expression arg0) {
if (resultType == typeof(object)) {
return new PythonDynamicExpression1(
Binders.UnaryOperationBinder(
PyContext,
operation
),
CompilationMode,
arg0
);
}
return CompilationMode.Dynamic(
Binders.UnaryOperationBinder(
PyContext,
operation
),
resultType,
arg0
);
}
internal MSAst.Expression/*!*/ Operation(Type/*!*/ resultType, PythonOperationKind operation, MSAst.Expression arg0, MSAst.Expression arg1) {
if (resultType == typeof(object)) {
return new PythonDynamicExpression2(
Binders.BinaryOperationBinder(
PyContext,
operation
),
_mode,
arg0,
arg1
);
}
return CompilationMode.Dynamic(
Binders.BinaryOperationBinder(
PyContext,
operation
),
resultType,
arg0,
arg1
);
}
internal MSAst.Expression/*!*/ Set(string/*!*/ name, MSAst.Expression/*!*/ target, MSAst.Expression/*!*/ value) {
return new PythonDynamicExpression2(
PyContext.SetMember(
name
),
CompilationMode,
target,
value
);
}
internal MSAst.Expression/*!*/ Get(string/*!*/ name, MSAst.Expression/*!*/ target) {
return new DynamicGetMemberExpression(PyContext.GetMember(name), _mode, target, LocalContext);
}
internal MSAst.Expression/*!*/ Delete(Type/*!*/ resultType, string/*!*/ name, MSAst.Expression/*!*/ target) {
return CompilationMode.Dynamic(
PyContext.DeleteMember(
name
),
resultType,
target
);
}
internal MSAst.Expression/*!*/ GetIndex(MSAst.Expression/*!*/[]/*!*/ expressions) {
return new PythonDynamicExpressionN(
PyContext.GetIndex(
expressions.Length
),
CompilationMode,
expressions
);
}
internal MSAst.Expression/*!*/ GetSlice(MSAst.Expression/*!*/[]/*!*/ expressions) {
return new PythonDynamicExpressionN(
PyContext.GetSlice,
CompilationMode,
expressions
);
}
internal MSAst.Expression/*!*/ SetIndex(MSAst.Expression/*!*/[]/*!*/ expressions) {
return new PythonDynamicExpressionN(
PyContext.SetIndex(
expressions.Length - 1
),
CompilationMode,
expressions
);
}
internal MSAst.Expression/*!*/ SetSlice(MSAst.Expression/*!*/[]/*!*/ expressions) {
return new PythonDynamicExpressionN(
PyContext.SetSliceBinder,
CompilationMode,
expressions
);
}
internal MSAst.Expression/*!*/ DeleteIndex(MSAst.Expression/*!*/[]/*!*/ expressions) {
return CompilationMode.Dynamic(
PyContext.DeleteIndex(
expressions.Length
),
typeof(void),
expressions
);
}
internal MSAst.Expression/*!*/ DeleteSlice(MSAst.Expression/*!*/[]/*!*/ expressions) {
return new PythonDynamicExpressionN(
PyContext.DeleteSlice,
CompilationMode,
expressions
);
}
#endregion
#region Lookup Rewriting
/// <summary>
/// Rewrites the tree for performing lookups against globals instead of being bound
/// against the optimized scope. This is used if the user compiles optimied code and then
/// runs it against a different scope.
/// </summary>
internal PythonAst MakeLookupCode() {
PythonAst res = (PythonAst)MemberwiseClone();
res._mode = CompilationMode.Lookup;
res._contextInfo = null;
// update the top-level globals for class/funcs accessing __name__, __file__, etc...
Dictionary<PythonVariable, MSAst.Expression> newGlobals = new Dictionary<PythonVariable, MSAst.Expression>();
foreach (var v in _globalVariables) {
newGlobals[v.Key] = CompilationMode.Lookup.GetGlobal(_globalContext, -1, v.Key, null);
}
res._globalVariables = newGlobals;
res._body = new RewrittenBodyStatement(_body, new LookupVisitor(res, GetGlobalContext()).Visit(_body));
return res;
}
internal class LookupVisitor : MSAst.ExpressionVisitor {
private readonly MSAst.Expression _globalContext;
private ScopeStatement _curScope;
public LookupVisitor(PythonAst ast, MSAst.Expression globalContext) {
_globalContext = globalContext;
_curScope = ast;
}
protected override MSAst.Expression VisitMember(MSAst.MemberExpression node) {
if (node == _globalContext) {
return PythonAst._globalContext;
}
return base.VisitMember(node);
}
protected override MSAst.Expression VisitExtension(MSAst.Expression node) {
if (node == _globalContext) {
return PythonAst._globalContext;
}
// we need to re-write nested scoeps
ScopeStatement scope = node as ScopeStatement;
if (scope != null) {
return base.VisitExtension(VisitScope(scope));
}
LambdaExpression lambda = node as LambdaExpression;
if (lambda != null) {
return base.VisitExtension(new LambdaExpression((FunctionDefinition)VisitScope(lambda.Function)));
}
GeneratorExpression generator = node as GeneratorExpression;
if (generator != null) {
return base.VisitExtension(new GeneratorExpression((FunctionDefinition)VisitScope(generator.Function), generator.Iterable));
}
// update the global get/set/raw gets variables
PythonGlobalVariableExpression global = node as PythonGlobalVariableExpression;
if (global != null) {
return new LookupGlobalVariable(
_curScope == null ? PythonAst._globalContext : _curScope.LocalContext,
global.Variable.Name,
global.Variable.Kind == VariableKind.Local
);
}
// set covers sets and deletes
var setGlobal = node as PythonSetGlobalVariableExpression;
if (setGlobal != null) {
if (setGlobal.Value == PythonGlobalVariableExpression.Uninitialized) {
return new LookupGlobalVariable(
_curScope == null ? PythonAst._globalContext : _curScope.LocalContext,
setGlobal.Global.Variable.Name,
setGlobal.Global.Variable.Kind == VariableKind.Local
).Delete();
} else {
return new LookupGlobalVariable(
_curScope == null ? PythonAst._globalContext : _curScope.LocalContext,
setGlobal.Global.Variable.Name,
setGlobal.Global.Variable.Kind == VariableKind.Local
).Assign(Visit(setGlobal.Value));
}
}
var rawValue = node as PythonRawGlobalValueExpression;
if (rawValue != null) {
return new LookupGlobalVariable(
_curScope == null ? PythonAst._globalContext : _curScope.LocalContext,
rawValue.Global.Variable.Name,
rawValue.Global.Variable.Kind == VariableKind.Local
);
}
return base.VisitExtension(node);
}
private ScopeStatement VisitScope(ScopeStatement scope) {
var newScope = scope.CopyForRewrite();
ScopeStatement prevScope = _curScope;
try {
// rewrite the method body
_curScope = newScope;
newScope.Parent = prevScope;
newScope.RewriteBody(this);
} finally {
_curScope = prevScope;
}
return newScope;
}
}
#endregion
internal override string ProfilerName {
get {
if (_mode == CompilationMode.Lookup) {
return NameForExec;
}
if (_name.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0) {
return "module " + _name;
} else {
return "module " + System.IO.Path.GetFileNameWithoutExtension(_name);
}
}
}
internal new bool EmitDebugSymbols {
get {
return PyContext.EmitDebugSymbols(SourceUnit);
}
}
/// <summary>
/// True if this is on-disk code which we don't really have an AST for.
/// </summary>
internal bool OnDiskProxy {
get {
return _onDiskProxy;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Microsoft.CSharp.RuntimeBinder
{
internal static class BinderHelper
{
private static MethodInfo s_DoubleIsNaN;
private static MethodInfo s_SingleIsNaN;
internal static DynamicMetaObject Bind(
DynamicMetaObjectBinder action,
RuntimeBinder binder,
DynamicMetaObject[] args,
IEnumerable<CSharpArgumentInfo> arginfos,
DynamicMetaObject onBindingError)
{
Expression[] parameters = new Expression[args.Length];
BindingRestrictions restrictions = BindingRestrictions.Empty;
ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder;
ParameterExpression tempForIncrement = null;
IEnumerator<CSharpArgumentInfo> arginfosEnum = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator();
for (int index = 0; index < args.Length; ++index)
{
DynamicMetaObject o = args[index];
// Our contract with the DLR is such that we will not enter a bind unless we have
// values for the meta-objects involved.
if (!o.HasValue)
{
Debug.Assert(false, "The runtime binder is being asked to bind a metaobject without a value");
throw Error.InternalCompilerError();
}
CSharpArgumentInfo info = arginfosEnum.MoveNext() ? arginfosEnum.Current : null;
if (index == 0 && IsIncrementOrDecrementActionOnLocal(action))
{
// We have an inc or a dec operation. Insert the temp local instead.
//
// We need to do this because for value types, the object will come
// in boxed, and we'd need to unbox it to get the original type in order
// to increment. The only way to do that is to create a new temporary.
object value = o.Value;
tempForIncrement = Expression.Variable(value != null ? value.GetType() : typeof(object), "t0");
parameters[0] = tempForIncrement;
}
else
{
parameters[index] = o.Expression;
}
BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info);
restrictions = restrictions.Merge(r);
// Here we check the argument info. If the argument info shows that the current argument
// is a literal constant, then we also add an instance restriction on the value of
// the constant.
if (info != null && info.LiteralConstant)
{
if (o.Value is double && double.IsNaN((double)o.Value))
{
MethodInfo isNaN = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN"));
Expression e = Expression.Call(null, isNaN, o.Expression);
restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
}
else if (o.Value is float && float.IsNaN((float)o.Value))
{
MethodInfo isNaN = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN"));
Expression e = Expression.Call(null, isNaN, o.Expression);
restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
}
else
{
Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type));
r = BindingRestrictions.GetExpressionRestriction(e);
restrictions = restrictions.Merge(r);
}
}
}
// Get the bound expression.
try
{
DynamicMetaObject deferredBinding;
Expression expression = binder.Bind(action, parameters, args, out deferredBinding);
if (deferredBinding != null)
{
expression = ConvertResult(deferredBinding.Expression, action);
restrictions = deferredBinding.Restrictions.Merge(restrictions);
return new DynamicMetaObject(expression, restrictions);
}
if (tempForIncrement != null)
{
// If we have a ++ or -- payload, we need to do some temp rewriting.
// We rewrite to the following:
//
// temp = (type)o;
// temp++;
// o = temp;
// return o;
DynamicMetaObject arg0 = args[0];
expression = Expression.Block(
new[] {tempForIncrement},
Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())),
expression,
Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type)));
}
expression = ConvertResult(expression, action);
return new DynamicMetaObject(expression, restrictions);
}
catch (RuntimeBinderException e)
{
if (onBindingError != null)
{
return onBindingError;
}
return new DynamicMetaObject(
Expression.Throw(
Expression.New(
typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }),
Expression.Constant(e.Message)
),
GetTypeForErrorMetaObject(action, args.Length == 0 ? null : args[0])
),
restrictions
);
}
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsTypeOfStaticCall(
int parameterIndex,
ICSharpInvokeOrInvokeMemberBinder callPayload)
{
return parameterIndex == 0 && callPayload != null && callPayload.StaticCall;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsComObject(object obj)
{
return obj != null && Marshal.IsComObject(obj);
}
#if ENABLECOMBINDER
/////////////////////////////////////////////////////////////////////////////////
// Try to determine if this object represents a WindowsRuntime object - i.e. it either
// is coming from a WinMD file or is derived from a class coming from a WinMD.
// The logic here matches the CLR's logic of finding a WinRT object.
internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj)
{
Type curType = obj?.RuntimeType;
while (curType != null)
{
TypeAttributes attributes = curType.Attributes;
if ((attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime)
{
// Found a WinRT COM object
return true;
}
if ((attributes & TypeAttributes.Import) == TypeAttributes.Import)
{
// Found a class that is actually imported from COM but not WinRT
// this is definitely a non-WinRT COM object
return false;
}
curType = curType.BaseType;
}
return false;
}
#endif
/////////////////////////////////////////////////////////////////////////////////
private static bool IsTransparentProxy(object obj)
{
// In the full framework, this checks:
// return obj != null && RemotingServices.IsTransparentProxy(obj);
// but transparent proxies don't exist in .NET Core.
return false;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info)
{
// This detects situations where, although the argument has a value with
// a given type, that type is insufficient to determine, statically, the
// set of reference conversions that are going to exist at bind time for
// different values. For instance, one __ComObject may allow a conversion
// to IFoo while another does not.
bool isDynamicObject =
info != null &&
!info.UseCompileTimeType &&
(IsComObject(argument.Value) || IsTransparentProxy(argument.Value));
return isDynamicObject;
}
/////////////////////////////////////////////////////////////////////////////////
private static BindingRestrictions DeduceArgumentRestriction(
int parameterIndex,
ICSharpInvokeOrInvokeMemberBinder callPayload,
DynamicMetaObject argument,
CSharpArgumentInfo info)
{
// Here we deduce what predicates the DLR can apply to future calls in order to
// determine whether to use the previously-computed-and-cached delegate, or
// whether we need to bind the site again. Ideally we would like the
// predicate to be as broad as is possible; if we can re-use analysis based
// solely on the type of the argument, that is preferable to re-using analysis
// based on object identity with a previously-analyzed argument.
// The times when we need to restrict re-use to a particular instance, rather
// than its type, are:
//
// * if the argument is a null reference then we have no type information.
//
// * if we are making a static call then the first argument is
// going to be a Type object. In this scenario we should always check
// for a specific Type object rather than restricting to the Type type.
//
// * if the argument was dynamic at compile time and it is a dynamic proxy
// object that the runtime manages, such as COM RCWs and transparent
// proxies.
//
// ** there is also a case for constant values (such as literals) to use
// something like value restrictions, and that is accomplished in Bind().
bool useValueRestriction =
argument.Value == null ||
IsTypeOfStaticCall(parameterIndex, callPayload) ||
IsDynamicallyTypedRuntimeProxy(argument, info);
return useValueRestriction ?
BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) :
BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType);
}
/////////////////////////////////////////////////////////////////////////////////
private static Expression ConvertResult(Expression binding, DynamicMetaObjectBinder action)
{
// Need to handle the following cases:
// (1) Call to a constructor: no conversions.
// (2) Call to a void-returning method: return null iff result is discarded.
// (3) Call to a value-type returning method: box to object.
//
// In all other cases, binding.Type should be equivalent or
// reference assignable to resultType.
var invokeConstructor = action as CSharpInvokeConstructorBinder;
if (invokeConstructor != null)
{
// No conversions needed, the call site has the correct type.
return binding;
}
if (binding.Type == typeof(void))
{
var invoke = action as ICSharpInvokeOrInvokeMemberBinder;
if (invoke != null && invoke.ResultDiscarded)
{
Debug.Assert(action.ReturnType == typeof(object));
return Expression.Block(binding, Expression.Default(action.ReturnType));
}
else
{
throw Error.BindToVoidMethodButExpectResult();
}
}
if (binding.Type.IsValueType && !action.ReturnType.IsValueType)
{
Debug.Assert(action.ReturnType == typeof(object));
return Expression.Convert(binding, action.ReturnType);
}
return binding;
}
/////////////////////////////////////////////////////////////////////////////////
private static Type GetTypeForErrorMetaObject(DynamicMetaObjectBinder action, DynamicMetaObject arg0)
{
// This is similar to ConvertResult but has fewer things to worry about.
var invokeConstructor = action as CSharpInvokeConstructorBinder;
if (invokeConstructor != null)
{
Type result = arg0.Value as Type;
if (result == null)
{
Debug.Assert(false);
return typeof(object);
}
return result;
}
return action.ReturnType;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsIncrementOrDecrementActionOnLocal(DynamicMetaObjectBinder action)
{
CSharpUnaryOperationBinder operatorPayload = action as CSharpUnaryOperationBinder;
return operatorPayload != null &&
(operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement);
}
/////////////////////////////////////////////////////////////////////////////////
internal static T[] Cons<T>(T sourceHead, T[] sourceTail)
{
if (sourceTail?.Length != 0)
{
T[] array = new T[sourceTail.Length + 1];
array[0] = sourceHead;
sourceTail.CopyTo(array, 1);
return array;
}
return new[] { sourceHead };
}
internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast)
{
if (sourceMiddle?.Length != 0)
{
T[] array = new T[sourceMiddle.Length + 2];
array[0] = sourceHead;
array[array.Length - 1] = sourceLast;
sourceMiddle.CopyTo(array, 1);
return array;
}
return new[] {sourceHead, sourceLast};
}
/////////////////////////////////////////////////////////////////////////////////
internal static List<T> ToList<T>(IEnumerable<T> source)
{
if (source == null)
{
return new List<T>();
}
return source.ToList();
}
/////////////////////////////////////////////////////////////////////////////////
internal static CallInfo CreateCallInfo(IEnumerable<CSharpArgumentInfo> argInfos, int discard)
{
// This function converts the C# Binder's notion of argument information to the
// DLR's notion. The DLR counts arguments differently than C#. Here are some
// examples:
// Expression Binder C# ArgInfos DLR CallInfo
//
// d.M(1, 2, 3); CSharpInvokeMemberBinder 4 3
// d(1, 2, 3); CSharpInvokeBinder 4 3
// d[1, 2] = 3; CSharpSetIndexBinder 4 2
// d[1, 2, 3] CSharpGetIndexBinder 4 3
//
// The "discard" parameter tells this function how many of the C# arg infos it
// should not count as DLR arguments.
int argCount = 0;
List<string> argNames = new List<string>();
foreach (CSharpArgumentInfo info in argInfos)
{
if (info.NamedArgument)
{
argNames.Add(info.Name);
}
++argCount;
}
Debug.Assert(discard <= argCount);
Debug.Assert(argNames.Count <= argCount - discard);
return new CallInfo(argCount - discard, argNames);
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* Uwe Lesta (SbsSW.SwiPlCs classes)
* E-mail: logicmoo@gmail.com
* WWW: http://www.logicmoo.com
* Copyright (C): 2008, Uwe Lesta SBS-Softwaresysteme GmbH,
* 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using SbsSW.DesignByContract;
using Swicli.Library;
// Exception implementation
// SecurityPermissionAttribute for GetObjectData
namespace SbsSW.SwiPlCs.Exceptions
{
#region namspace documentation
/// <summary>
/// <para>These are the namespace comments for <b>SbsSW.SwiPlCs.Exceptions</b>.</para>
/// <para>The namespace SbsSW.SwiPlCs.Exceptions provides the Exception classes to catch a prolog exception
/// see <see href="http://gollem.science.uva.nl/SWI-Prolog/Manual/exception.html">SWI-Prolog Manual - 4.9 ISO compliant Exception handling</see>
/// </para>
/// <para>Prolog exceptions are mapped to C# exceptions using the subclass PlException of <see cref="Exception"/>
/// to represent the Prolog exception term.</para>
/// <para>All type-conversion functions of the interface raise Prolog-compliant exceptions,
/// providing decent error-handling support at no extra work for the programmer.</para>
/// <para>For some commonly used exceptions, subclasses of PlException have been created to exploit
/// both their constructors for easy creation of these exceptions as well as selective trapping in C#.</para>
/// <para>Currently, these are <see cref="PlTypeException"/> and <see cref="PlDomainException"/>.</para>
/// </summary>
/// <remarks>
/// </remarks>
/// <todo>To throw an exception, create an instance of PlException and use throw() or cppThrow(). The latter refines the C# exception class according to the represented Prolog exception before calling throw().
/// </todo>
[System.Runtime.CompilerServices.CompilerGenerated()]
class NamespaceDoc
{
}
#endregion namspace documentation
#region class PlLibException
/// <summary>This exception is thrown if something in the interface went wrong.</summary>
[Serializable]
public class PlLibException : Exception, ISerializable
{
/// <inheritdoc />
public PlLibException()
: base()
{
BP();
}
static private void BP()
{
libpl.PL_open_foreign_frame();
PrologCLR.BP();
return;
}
/// <inheritdoc />
public PlLibException(string message)
: base(message)
{
BP();
}
/// <inheritdoc />
public PlLibException(string message, Exception innerException)
: base(message, innerException)
{
BP();
}
#region implementation of ISerializable
// ISerializable Constructor
/// <inheritdoc />
protected PlLibException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
BP();
}
// see http://msdnwiki.microsoft.com/en-us/mtpswiki/f1d0010b-14fb-402f-974f-16318f0bc19f.aspx
/// <inheritdoc />
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
}
#endregion implementation of ISerializable
}
#endregion class PlLibException
#region class PlException
/// <inheritdoc />
/// <summary>
/// <para>This class is the base class to catch exceptions thrown by prolog in C#.</para>
/// </summary>
/// <example>
/// <code source="..\..\TestSwiPl\PlException.cs" region="prolog_exception_sample_doc" />
/// </example>
/// <seealso cref="PlTypeException"/>
/// <seealso href="http://gollem.science.uva.nl/SWI-Prolog/Manual/exception.html">SWI-Prolog Manual - 4.9 ISO compliant Exception handling</seealso>
[Serializable]
public class PlException : Exception, ISerializable
{
private string _messagePl;
private PlTerm _exTerm;
/// <summary>provide somtimes some additional information about the exceptions reason.</summary>
public string MessagePl { get { return _messagePl; } }
/// <inheritdoc />
public PlException()
: base()
{
EnsureExFrame();
_exTerm = PlTerm.PlVar();
}
/// <inheritdoc />
public PlException(string message)
: base(message)
{
EnsureExFrame();
_messagePl = message;
_exTerm = PlTerm.PlAtom(message);
//_exTerm = new PlTerm(message);
}
/// <inheritdoc />
public PlException(string message, Exception innerException)
: base(message, innerException)
{
EnsureExFrame();
_messagePl = message + "; innerExeption:" + innerException.Message;
_exTerm = PlTerm.PlAtom(message);
//_exTerm = new PlTerm(message);
}
#region implementation of ISerializable
// ISerializable Constructor
/// <inheritdoc />
protected PlException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
EnsureExFrame();
if (info == null)
throw new ArgumentNullException("info");
_messagePl = (string)info.GetValue("_messagePl", typeof(string));
_exTerm = (PlTerm)info.GetValue("_exTerm", typeof(PlTerm));
}
// see http://msdnwiki.microsoft.com/en-us/mtpswiki/f1d0010b-14fb-402f-974f-16318f0bc19f.aspx
/// <inheritdoc />
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue("_messagePl", _messagePl);
info.AddValue("_exTerm", this._exTerm);
}
#endregion implementation of ISerializable
/// <summary>
/// <para>To catch a exception thrown by prolog</para>
/// <para>For a example see <see cref="PlException"/>.</para>
/// </summary>
/// <param name="term">A PlTerm containing the Prolog exception</param>
/// <see cref="PlException"/>
public PlException(PlTerm term)
{
EnsureExFrame();
Check.Require(term.TermRefIntern != 0);
_exTerm = new PlTerm(term.TermRef); // If this line is deleted -> update comment in PlTern(term_ref)
_messagePl = "" + _exTerm;
}
private void EnsureExFrame()
{
libpl.PL_open_foreign_frame();
PrologCLR.BP();
}
/// <summary>
/// Get the <see cref="PlTerm"/> of this exception.
/// </summary>
public PlTerm Term { get { return _exTerm; } }
/// <inheritdoc />
public override string Message
{
get { return this.ToString(); }
}
//operator char *(void);
/// <inheritdoc />
/// <summary>
/// The exception is translated into a message as produced by print_message/2. The character data is stored in a ring.
/// </summary>
/// <returns></returns>
override public string ToString()
{
if (_messagePl != null) return GetType() + ": " + _messagePl;
if (!PlEngine.IsInitialized)
return "A PlException was thrown but it can't formatted because PlEngine is not Initialized.";
string strRet = "[ERROR: Failed to generate message. Internal error]\n";
if (libpl.NoToString) return "[ERROR: Failed to generate message. NoToString presently]\n";
using (PlFrame fr = new PlFrame())
{
#if USE_PRINT_MESSAGE
PlTermV av = new PlTermV(2);
av[0] = PlTerm.PlCompound("print_message", new PlTermV(new PlTerm("error"), new PlTerm( _exTerm.TermRef)));
PlQuery q = new PlQuery("$write_on_string", av);
if ( q.NextSolution() )
strRet = (string)av[1];
q.Free();
#else
PlTermV av = new PlTermV(2);
av[0] = new PlTerm(_exTerm.TermRef);
PlQuery q = new PlQuery("$messages", "message_to_string", av);
if (q.NextSolution())
strRet = av[1].ToString();
//q.Free();
return strRet;
q.Dispose();
#endif
}
return strRet;
}
/// <summary>
/// TODO
/// </summary>
/// <remarks>Used in the PREDICATE() wrapper to pass the exception to Prolog. See PL_raise_exeption().</remarks>
/// <returns></returns>
public int PlThrow()
{
return libpl.PL_raise_exception(_exTerm.TermRef);
}
/// <summary>
/// TODO
/// </summary>
/// <remarks>see <see href="http://www.swi-prolog.org/packages/pl2cpp.html#cppThrow()"/></remarks>
public void Throw()
{
// term_t
uint a = libpl.PL_new_term_ref();
// atom_t
uint name = 0;
int arity = 0;
if (0 != libpl.PL_get_arg(1, _exTerm.TermRef, a) && 0 != libpl.PL_get_name_arity(a, ref name, ref arity))
{
string str = libpl.PL_atom_chars(name);
if (str == "type_error")
throw new PlTypeException(_exTerm);
else if (str == "domain_error")
throw new PlDomainException(_exTerm);
}
this._messagePl = this.Message;
throw this;
}
} // class PlException
#endregion
#region class PlTypeException
/// <inheritdoc />
/// <summary>
/// A type error expresses that a term does not satisfy the expected basic Prolog type.
/// </summary>
/// <example>
/// This sample demonstrate how to catch a PlTypeException in C# that is thrown somewhere int the prolog code.
/// <code source="..\..\TestSwiPl\PlException.cs" region="prolog_type_exception_sample_doc" />
/// </example>
[Serializable]
public class PlTypeException : PlException
{
/// <inheritdoc />
public PlTypeException()
: base()
{
}
/// <inheritdoc />
public PlTypeException(string message)
: base(message)
{
}
/// <inheritdoc />
public PlTypeException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <inheritdoc />
protected PlTypeException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <inheritdoc />
public PlTypeException(PlTerm term)
: base(term)
{
}
/// <summary>
/// Creates an ISO standard Prolog error term expressing the expected type and actual term that does not satisfy this type.
/// </summary>
/// <param name="expected">The type which was expected</param>
/// <param name="actual">The actual term</param>
public PlTypeException(string expected, PlTerm actual)
: base(
PlTerm.PlCompound("error",
new PlTermV(PlTerm.PlCompound("type_error",
new PlTermV(new PlTerm(expected), actual)),
PlTerm.PlVar())
))
{
}
} // class PlTypeException
#endregion class PlTypeException
#region class PlDomainException
/// <summary>
/// A domain exception expresses that a term satisfies the basic Prolog type expected, but is unacceptable
/// to the restricted domain expected by some operation.
/// </summary>
/// <example>
/// For example, the standard Prolog open/3 call expect an IO-Mode (read, write, append, ...).
/// If an integer is provided, this is a type error, if an atom other than one of the defined IO-modes is provided it is a domain error.
/// <code source="..\..\TestSwiPl\PlException.cs" region="prolog_domain_exception_sample_doc" />
/// </example>
[Serializable]
internal class PlDomainException : PlException
{
/// <inheritdoc cref="PlException" />
public PlDomainException()
: base()
{ }
/*
public PlDomainException(string message)
: base(message)
{
}
public PlDomainException(string message, Exception innerException)
: base(message, innerException)
{
}
*/
/// <inheritdoc cref="PlException" />
protected PlDomainException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
/// <inheritdoc cref="PlException" />
public PlDomainException(PlTerm t)
: base(t)
{ }
/*
PlDomainException(string expected, PlTerm actual)
:
base(new PlCompound("error",
new PlTermV(new PlCompound("domain_error",
new PlTermV(new PlTerm(expected), actual)),
PlTerm.PlVar())
)
)
{ }
*/
}
#endregion class PlDomainException
} // namespace SbsSW.SwiPlCs
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IServiceTypeApi
{
#region Synchronous Operations
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ServiceType</returns>
ServiceType GetServiceTypeById (string serviceTypeId);
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ApiResponse of ServiceType</returns>
ApiResponse<ServiceType> GetServiceTypeByIdWithHttpInfo (string serviceTypeId);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ServiceType></returns>
List<ServiceType> GetServiceTypeBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ServiceType></returns>
ApiResponse<List<ServiceType>> GetServiceTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ServiceType</returns>
System.Threading.Tasks.Task<ServiceType> GetServiceTypeByIdAsync (string serviceTypeId);
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ApiResponse (ServiceType)</returns>
System.Threading.Tasks.Task<ApiResponse<ServiceType>> GetServiceTypeByIdAsyncWithHttpInfo (string serviceTypeId);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ServiceType></returns>
System.Threading.Tasks.Task<List<ServiceType>> GetServiceTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ServiceType>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ServiceType>>> GetServiceTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class ServiceTypeApi : IServiceTypeApi
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceTypeApi"/> class.
/// </summary>
/// <returns></returns>
public ServiceTypeApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceTypeApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ServiceTypeApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ServiceType</returns>
public ServiceType GetServiceTypeById (string serviceTypeId)
{
ApiResponse<ServiceType> localVarResponse = GetServiceTypeByIdWithHttpInfo(serviceTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ApiResponse of ServiceType</returns>
public ApiResponse< ServiceType > GetServiceTypeByIdWithHttpInfo (string serviceTypeId)
{
// verify the required parameter 'serviceTypeId' is set
if (serviceTypeId == null)
throw new ApiException(400, "Missing required parameter 'serviceTypeId' when calling ServiceTypeApi->GetServiceTypeById");
var localVarPath = "/beta/serviceType/{serviceTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (serviceTypeId != null) localVarPathParams.Add("serviceTypeId", Configuration.ApiClient.ParameterToString(serviceTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<ServiceType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ServiceType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ServiceType)));
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ServiceType</returns>
public async System.Threading.Tasks.Task<ServiceType> GetServiceTypeByIdAsync (string serviceTypeId)
{
ApiResponse<ServiceType> localVarResponse = await GetServiceTypeByIdAsyncWithHttpInfo(serviceTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ApiResponse (ServiceType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ServiceType>> GetServiceTypeByIdAsyncWithHttpInfo (string serviceTypeId)
{
// verify the required parameter 'serviceTypeId' is set
if (serviceTypeId == null) throw new ApiException(400, "Missing required parameter 'serviceTypeId' when calling GetServiceTypeById");
var localVarPath = "/beta/serviceType/{serviceTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (serviceTypeId != null) localVarPathParams.Add("serviceTypeId", Configuration.ApiClient.ParameterToString(serviceTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<ServiceType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ServiceType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ServiceType)));
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ServiceType></returns>
public List<ServiceType> GetServiceTypeBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ServiceType>> localVarResponse = GetServiceTypeBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ServiceType></returns>
public ApiResponse< List<ServiceType> > GetServiceTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/serviceType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<ServiceType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ServiceType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ServiceType>)));
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ServiceType></returns>
public async System.Threading.Tasks.Task<List<ServiceType>> GetServiceTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ServiceType>> localVarResponse = await GetServiceTypeBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ServiceType>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ServiceType>>> GetServiceTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/serviceType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetServiceTypeBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<ServiceType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ServiceType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ServiceType>)));
}
}
}
| |
using System.ComponentModel;
using System.Data;
using System.Drawing.Printing;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using EIDSS.Reports.BaseControls.BaseDataSetTableAdapters;
namespace EIDSS.Reports.BaseControls.Report
{
partial class BaseReport
{
/// <summary>
/// Required designer variable.
/// </summary>
protected IContainer components;
/// <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 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()
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(BaseReport));
this.Detail = new DetailBand();
this.PageHeader = new PageHeaderBand();
this.PageFooter = new PageFooterBand();
this.xrPageInfo1 = new XRPageInfo();
this.formattingRule1 = new FormattingRule();
this.baseDataSet1 = new BaseDataSet();
this.ReportHeader = new ReportHeaderBand();
this.tableBaseHeader = new XRTable();
this.rowReportName = new XRTableRow();
this.cellBaseLeftHeader = new XRTableCell();
this.tableBaseInnerHeader = new XRTable();
this.rowBaseDate = new XRTableRow();
this.cellDateHeader = new XRTableCell();
this.cellDate = new XRTableCell();
this.rowBaseTime = new XRTableRow();
this.cellTimeHeader = new XRTableCell();
this.cellTime = new XRTableCell();
this.rowBaseLanguage = new XRTableRow();
this.cellLanguageHeader = new XRTableCell();
this.cellLanguage = new XRTableCell();
this.cellReportHeader = new XRTableCell();
this.lblReportName = new XRLabel();
this.rowBaseCountrySite = new XRTableRow();
this.cellBaseCountry = new XRTableCell();
this.cellBaseSite = new XRTableCell();
this.sp_rep_BaseParametersTableAdapter = new sprepGetBaseParametersTableAdapter();
this.topMarginBand1 = new TopMarginBand();
this.bottomMarginBand1 = new BottomMarginBand();
((ISupportInitialize)(this.baseDataSet1)).BeginInit();
((ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((ISupportInitialize)(this.tableBaseInnerHeader)).BeginInit();
((ISupportInitialize)(this)).BeginInit();
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new PaddingInfo(0, 2, 0, 2, 100F);
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new PaddingInfo(2, 2, 2, 2, 100F);
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.Borders = ((BorderSide)((((BorderSide.Left | BorderSide.Top)
| BorderSide.Right)
| BorderSide.Bottom)));
this.PageFooter.Controls.AddRange(new XRControl[] {
this.xrPageInfo1});
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new PaddingInfo(0, 0, 0, 0, 100F);
this.PageFooter.StylePriority.UseBorders = false;
//
// xrPageInfo1
//
this.xrPageInfo1.Borders = BorderSide.None;
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.Name = "xrPageInfo1";
this.xrPageInfo1.Padding = new PaddingInfo(2, 2, 0, 0, 100F);
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// formattingRule1
//
this.formattingRule1.DataSource = this.baseDataSet1;
this.formattingRule1.Name = "formattingRule1";
//
// baseDataSet1
//
this.baseDataSet1.DataSetName = "BaseDataSet";
this.baseDataSet1.SchemaSerializationMode = SchemaSerializationMode.IncludeSchema;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new XRControl[] {
this.tableBaseHeader});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
//
// tableBaseHeader
//
this.tableBaseHeader.Borders = ((BorderSide)((((BorderSide.Left | BorderSide.Top)
| BorderSide.Right)
| BorderSide.Bottom)));
this.tableBaseHeader.BorderWidth = 2;
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.Name = "tableBaseHeader";
this.tableBaseHeader.Padding = new PaddingInfo(2, 2, 0, 0, 100F);
this.tableBaseHeader.Rows.AddRange(new XRTableRow[] {
this.rowReportName,
this.rowBaseCountrySite});
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// rowReportName
//
this.rowReportName.Cells.AddRange(new XRTableCell[] {
this.cellBaseLeftHeader,
this.cellReportHeader});
resources.ApplyResources(this.rowReportName, "rowReportName");
this.rowReportName.Name = "rowReportName";
this.rowReportName.Weight = 3.0454320987654322;
//
// cellBaseLeftHeader
//
this.cellBaseLeftHeader.Controls.AddRange(new XRControl[] {
this.tableBaseInnerHeader});
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
this.cellBaseLeftHeader.Name = "cellBaseLeftHeader";
this.cellBaseLeftHeader.Weight = 1.1309915624438993;
//
// tableBaseInnerHeader
//
this.tableBaseInnerHeader.Borders = ((BorderSide)((((BorderSide.Left | BorderSide.Top)
| BorderSide.Right)
| BorderSide.Bottom)));
this.tableBaseInnerHeader.BorderWidth = 2;
resources.ApplyResources(this.tableBaseInnerHeader, "tableBaseInnerHeader");
this.tableBaseInnerHeader.Name = "tableBaseInnerHeader";
this.tableBaseInnerHeader.Padding = new PaddingInfo(2, 2, 0, 0, 100F);
this.tableBaseInnerHeader.Rows.AddRange(new XRTableRow[] {
this.rowBaseDate,
this.rowBaseTime,
this.rowBaseLanguage});
this.tableBaseInnerHeader.StylePriority.UseBorders = false;
this.tableBaseInnerHeader.StylePriority.UseBorderWidth = false;
this.tableBaseInnerHeader.StylePriority.UseFont = false;
this.tableBaseInnerHeader.StylePriority.UsePadding = false;
this.tableBaseInnerHeader.StylePriority.UseTextAlignment = false;
//
// rowBaseDate
//
this.rowBaseDate.Cells.AddRange(new XRTableCell[] {
this.cellDateHeader,
this.cellDate});
resources.ApplyResources(this.rowBaseDate, "rowBaseDate");
this.rowBaseDate.Name = "rowBaseDate";
this.rowBaseDate.Weight = 1;
//
// cellDateHeader
//
resources.ApplyResources(this.cellDateHeader, "cellDateHeader");
this.cellDateHeader.Name = "cellDateHeader";
this.cellDateHeader.Weight = 0.40595618793024008;
//
// cellDate
//
resources.ApplyResources(this.cellDate, "cellDate");
this.cellDate.Name = "cellDate";
this.cellDate.Padding = new PaddingInfo(4, 4, 0, 0, 100F);
this.cellDate.Weight = 0.2044202108490073;
//
// rowBaseTime
//
this.rowBaseTime.Cells.AddRange(new XRTableCell[] {
this.cellTimeHeader,
this.cellTime});
resources.ApplyResources(this.rowBaseTime, "rowBaseTime");
this.rowBaseTime.Name = "rowBaseTime";
this.rowBaseTime.StylePriority.UseBorders = false;
this.rowBaseTime.Weight = 1;
//
// cellTimeHeader
//
resources.ApplyResources(this.cellTimeHeader, "cellTimeHeader");
this.cellTimeHeader.Name = "cellTimeHeader";
this.cellTimeHeader.Weight = 0.40595618793024008;
//
// cellTime
//
resources.ApplyResources(this.cellTime, "cellTime");
this.cellTime.Name = "cellTime";
this.cellTime.Padding = new PaddingInfo(4, 4, 0, 0, 100F);
this.cellTime.Weight = 0.2044202108490073;
//
// rowBaseLanguage
//
this.rowBaseLanguage.Cells.AddRange(new XRTableCell[] {
this.cellLanguageHeader,
this.cellLanguage});
resources.ApplyResources(this.rowBaseLanguage, "rowBaseLanguage");
this.rowBaseLanguage.Name = "rowBaseLanguage";
this.rowBaseLanguage.Weight = 1;
//
// cellLanguageHeader
//
resources.ApplyResources(this.cellLanguageHeader, "cellLanguageHeader");
this.cellLanguageHeader.Multiline = true;
this.cellLanguageHeader.Name = "cellLanguageHeader";
this.cellLanguageHeader.Weight = 0.40595618793024008;
//
// cellLanguage
//
this.cellLanguage.DataBindings.AddRange(new XRBinding[] {
new XRBinding("Text", null, "sprepGetBaseParameters.LanguageName")});
resources.ApplyResources(this.cellLanguage, "cellLanguage");
this.cellLanguage.Name = "cellLanguage";
this.cellLanguage.Padding = new PaddingInfo(4, 4, 0, 0, 100F);
this.cellLanguage.StylePriority.UseTextAlignment = false;
this.cellLanguage.Weight = 0.2044202108490073;
//
// cellReportHeader
//
this.cellReportHeader.Controls.AddRange(new XRControl[] {
this.lblReportName});
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.Name = "cellReportHeader";
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Weight = 2.8576386811082521;
//
// lblReportName
//
this.lblReportName.Borders = BorderSide.None;
this.lblReportName.BorderWidth = 0;
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Name = "lblReportName";
this.lblReportName.Padding = new PaddingInfo(2, 2, 0, 0, 100F);
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// rowBaseCountrySite
//
this.rowBaseCountrySite.Cells.AddRange(new XRTableCell[] {
this.cellBaseCountry,
this.cellBaseSite});
resources.ApplyResources(this.rowBaseCountrySite, "rowBaseCountrySite");
this.rowBaseCountrySite.Name = "rowBaseCountrySite";
this.rowBaseCountrySite.StylePriority.UseFont = false;
this.rowBaseCountrySite.Weight = 0.95456790123456792;
//
// cellBaseCountry
//
this.cellBaseCountry.DataBindings.AddRange(new XRBinding[] {
new XRBinding("Text", null, "sprepGetBaseParameters.CountryName")});
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
this.cellBaseCountry.Name = "cellBaseCountry";
this.cellBaseCountry.Weight = 1.1309915624438993;
//
// cellBaseSite
//
this.cellBaseSite.DataBindings.AddRange(new XRBinding[] {
new XRBinding("Text", null, "sprepGetBaseParameters.SiteName")});
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
this.cellBaseSite.Name = "cellBaseSite";
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
this.cellBaseSite.Weight = 2.8576386811082521;
//
// sp_rep_BaseParametersTableAdapter
//
this.sp_rep_BaseParametersTableAdapter.ClearBeforeFill = true;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// BaseReport
//
this.Bands.AddRange(new Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.DataAdapter = this.sp_rep_BaseParametersTableAdapter;
this.DataMember = "sprepGetBaseParameters";
this.DataSource = this.baseDataSet1;
resources.ApplyResources(this, "$this");
this.FormattingRuleSheet.AddRange(new FormattingRule[] {
this.formattingRule1});
this.Landscape = true;
this.PageHeight = 827;
this.PageWidth = 1169;
this.PaperKind = PaperKind.A4;
this.Version = "10.1";
((ISupportInitialize)(this.baseDataSet1)).EndInit();
((ISupportInitialize)(this.tableBaseHeader)).EndInit();
((ISupportInitialize)(this.tableBaseInnerHeader)).EndInit();
((ISupportInitialize)(this)).EndInit();
}
#endregion
private FormattingRule formattingRule1;
private XRTableRow rowBaseDate;
private XRTableCell cellDateHeader;
private XRTableCell cellDate;
private XRTableRow rowBaseTime;
private XRTableCell cellTimeHeader;
private XRTableCell cellTime;
private XRTableRow rowBaseLanguage;
private XRTableCell cellLanguageHeader;
protected XRTableCell cellLanguage;
protected XRLabel lblReportName;
protected DetailBand Detail;
protected PageHeaderBand PageHeader;
protected PageFooterBand PageFooter;
protected sprepGetBaseParametersTableAdapter sp_rep_BaseParametersTableAdapter;
public ReportHeaderBand ReportHeader;
protected XRPageInfo xrPageInfo1;
protected BaseDataSet baseDataSet1;
protected XRTableCell cellReportHeader;
private XRTableRow rowReportName;
private XRTableRow rowBaseCountrySite;
private XRTable tableBaseInnerHeader;
protected XRTableCell cellBaseSite;
protected XRTableCell cellBaseCountry;
protected XRTableCell cellBaseLeftHeader;
protected XRTable tableBaseHeader;
private TopMarginBand topMarginBand1;
private BottomMarginBand bottomMarginBand1;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.Assets;
namespace groupmanager
{
public partial class frmGroupInfo : Form
{
Group Group;
GridClient Client;
Group Profile = new Group();
Dictionary<UUID, GroupMember> Members = new Dictionary<UUID,GroupMember>();
Dictionary<UUID, GroupTitle> Titles = new Dictionary<UUID,GroupTitle>();
Dictionary<UUID, GroupMemberData> MemberData = new Dictionary<UUID, GroupMemberData>();
Dictionary<UUID, string> Names = new Dictionary<UUID, string>();
EventHandler<GroupProfileEventArgs> GroupProfileCallback;
EventHandler<GroupMembersReplyEventArgs> GroupMembersCallback;
EventHandler<GroupTitlesReplyEventArgs> GroupTitlesCallback;
EventHandler<UUIDNameReplyEventArgs> AvatarNamesCallback;
public frmGroupInfo(Group group, GridClient client)
{
InitializeComponent();
while (!IsHandleCreated)
{
// Force handle creation
// warning CS0219: The variable `temp' is assigned but its value is never used
IntPtr temp = Handle;
}
GroupMembersCallback = new EventHandler<GroupMembersReplyEventArgs>(GroupMembersHandler);
GroupProfileCallback = new EventHandler<GroupProfileEventArgs>(GroupProfileHandler);
GroupTitlesCallback = new EventHandler<GroupTitlesReplyEventArgs>(GroupTitlesHandler);
AvatarNamesCallback = new EventHandler<UUIDNameReplyEventArgs>(AvatarNamesHandler);
Group = group;
Client = client;
// Register the callbacks for this form
Client.Groups.GroupProfile += GroupProfileCallback;
Client.Groups.GroupMembersReply += GroupMembersCallback;
Client.Groups.GroupTitlesReply += GroupTitlesCallback;
Client.Avatars.UUIDNameReply += AvatarNamesCallback;
// Request the group information
Client.Groups.RequestGroupProfile(Group.ID);
Client.Groups.RequestGroupMembers(Group.ID);
Client.Groups.RequestGroupTitles(Group.ID);
}
~frmGroupInfo()
{
// Unregister the callbacks for this form
Client.Groups.GroupProfile -= GroupProfileCallback;
Client.Groups.GroupMembersReply -= GroupMembersCallback;
Client.Groups.GroupTitlesReply -= GroupTitlesCallback;
Client.Avatars.UUIDNameReply -= AvatarNamesCallback;
}
private void GroupProfileHandler(object sender, GroupProfileEventArgs e)
{
Profile = e.Group;
if (Group.InsigniaID != UUID.Zero)
Client.Assets.RequestImage(Group.InsigniaID, ImageType.Normal,
delegate(TextureRequestState state, AssetTexture assetTexture)
{
ManagedImage imgData;
Image bitmap;
if (state != TextureRequestState.Timeout || state != TextureRequestState.NotFound)
{
OpenJPEG.DecodeToImage(assetTexture.AssetData, out imgData, out bitmap);
picInsignia.Image = bitmap;
UpdateInsigniaProgressText("Progress...");
}
if (state == TextureRequestState.Finished)
{
UpdateInsigniaProgressText("");
}
}, true);
if (this.InvokeRequired)
this.BeginInvoke(new MethodInvoker(UpdateProfile));
}
private void UpdateInsigniaProgressText(string resultText)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new MethodInvoker(delegate()
{
UpdateInsigniaProgressText(resultText);
}));
}
else
labelInsigniaProgress.Text = resultText;
}
private void UpdateProfile()
{
lblGroupName.Text = Profile.Name;
txtCharter.Text = Profile.Charter;
chkShow.Checked = Profile.ShowInList;
chkPublish.Checked = Profile.AllowPublish;
chkOpenEnrollment.Checked = Profile.OpenEnrollment;
chkFee.Checked = (Profile.MembershipFee != 0);
numFee.Value = Profile.MembershipFee;
chkMature.Checked = Profile.MaturePublish;
Client.Avatars.RequestAvatarName(Profile.FounderID);
}
private void AvatarNamesHandler(object sender, UUIDNameReplyEventArgs e)
{
lock (Names)
{
foreach (KeyValuePair<UUID, string> agent in e.Names)
{
Names[agent.Key] = agent.Value;
}
}
UpdateNames();
}
private void UpdateNames()
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(UpdateNames));
}
else
{
lock (Names)
{
if (Profile.FounderID != UUID.Zero && Names.ContainsKey(Profile.FounderID))
{
lblFoundedBy.Text = "Founded by " + Names[Profile.FounderID];
}
lock (MemberData)
{
foreach (KeyValuePair<UUID, string> name in Names)
{
if (!MemberData.ContainsKey(name.Key))
{
MemberData[name.Key] = new GroupMemberData();
}
MemberData[name.Key].Name = name.Value;
}
}
}
UpdateMemberList();
}
}
private void UpdateMemberList()
{
// General tab list
lock (lstMembers)
{
lstMembers.Items.Clear();
foreach (GroupMemberData entry in MemberData.Values)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = entry.Name;
ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = entry.Title;
lvi.SubItems.Add(lvsi);
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = entry.LastOnline;
lvi.SubItems.Add(lvsi);
lstMembers.Items.Add(lvi);
}
}
// Members tab list
lock (lstMembers2)
{
lstMembers2.Items.Clear();
foreach (GroupMemberData entry in MemberData.Values)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = entry.Name;
ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = entry.Contribution.ToString();
lvi.SubItems.Add(lvsi);
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = entry.LastOnline;
lvi.SubItems.Add(lvsi);
lstMembers2.Items.Add(lvi);
}
}
}
private void GroupMembersHandler(object sender, GroupMembersReplyEventArgs e)
{
Members = e.Members;
UpdateMembers();
}
private void UpdateMembers()
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(UpdateMembers));
}
else
{
List<UUID> requestids = new List<UUID>();
lock (Members)
{
lock (MemberData)
{
foreach (GroupMember member in Members.Values)
{
GroupMemberData memberData = new GroupMemberData();
memberData.ID = member.ID;
memberData.IsOwner = member.IsOwner;
memberData.LastOnline = member.OnlineStatus;
memberData.Powers = (ulong)member.Powers;
memberData.Title = member.Title;
memberData.Contribution = member.Contribution;
MemberData[member.ID] = memberData;
// Add this ID to the name request batch
requestids.Add(member.ID);
}
}
}
Client.Avatars.RequestAvatarNames(requestids);
}
}
private void GroupTitlesHandler(object sender, GroupTitlesReplyEventArgs e)
{
Titles = e.Titles;
UpdateTitles();
}
private void UpdateTitles()
{
if (this.InvokeRequired)
{
Invoke(new MethodInvoker(UpdateTitles));
}
else
{
lock (Titles)
{
foreach (KeyValuePair<UUID, GroupTitle> kvp in Titles)
{
Console.Write("Title: " + kvp.Value.Title + " = " + kvp.Key.ToString());
if (kvp.Value.Selected)
Console.WriteLine(" (Selected)");
else
Console.WriteLine();
}
}
}
}
}
public class GroupMemberData
{
public UUID ID;
public string Name;
public string Title;
public string LastOnline;
public ulong Powers;
public bool IsOwner;
public int Contribution;
}
}
| |
using System.Threading.Tasks;
#if !FEATURE_NETCORE
using System.Xml.XPath;
#endif // !FEATURE_NETCORE
namespace System.Xml {
internal class XmlAsyncCheckWriter : XmlWriter {
private readonly XmlWriter coreWriter = null;
private Task lastTask = AsyncHelper.DoneTask;
internal XmlWriter CoreWriter {
get {
return coreWriter;
}
}
public XmlAsyncCheckWriter(XmlWriter writer) {
coreWriter = writer;
}
private void CheckAsync() {
if (!lastTask.IsCompleted) {
throw new InvalidOperationException(Res.GetString(Res.Xml_AsyncIsRunningException));
}
}
#region [....] Methods, Properties Check
public override XmlWriterSettings Settings {
get {
XmlWriterSettings settings = coreWriter.Settings;
if (null != settings) {
settings = settings.Clone();
}
else {
settings = new XmlWriterSettings();
}
settings.Async = true;
settings.ReadOnly = true;
return settings;
}
}
public override void WriteStartDocument() {
CheckAsync();
coreWriter.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone) {
CheckAsync();
coreWriter.WriteStartDocument(standalone);
}
public override void WriteEndDocument() {
CheckAsync();
coreWriter.WriteEndDocument();
}
public override void WriteDocType(string name, string pubid, string sysid, string subset) {
CheckAsync();
coreWriter.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns) {
CheckAsync();
coreWriter.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement() {
CheckAsync();
coreWriter.WriteEndElement();
}
public override void WriteFullEndElement() {
CheckAsync();
coreWriter.WriteFullEndElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns) {
CheckAsync();
coreWriter.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute() {
CheckAsync();
coreWriter.WriteEndAttribute();
}
public override void WriteCData(string text) {
CheckAsync();
coreWriter.WriteCData(text);
}
public override void WriteComment(string text) {
CheckAsync();
coreWriter.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text) {
CheckAsync();
coreWriter.WriteProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name) {
CheckAsync();
coreWriter.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch) {
CheckAsync();
coreWriter.WriteCharEntity(ch);
}
public override void WriteWhitespace(string ws) {
CheckAsync();
coreWriter.WriteWhitespace(ws);
}
public override void WriteString(string text) {
CheckAsync();
coreWriter.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar) {
CheckAsync();
coreWriter.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteChars(char[] buffer, int index, int count) {
CheckAsync();
coreWriter.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count) {
CheckAsync();
coreWriter.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data) {
CheckAsync();
coreWriter.WriteRaw(data);
}
public override void WriteBase64(byte[] buffer, int index, int count) {
CheckAsync();
coreWriter.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count) {
CheckAsync();
coreWriter.WriteBinHex(buffer, index, count);
}
public override WriteState WriteState {
get {
CheckAsync();
return coreWriter.WriteState;
}
}
public override void Close() {
CheckAsync();
coreWriter.Close();
}
public override void Flush() {
CheckAsync();
coreWriter.Flush();
}
public override string LookupPrefix(string ns) {
CheckAsync();
return coreWriter.LookupPrefix(ns);
}
public override XmlSpace XmlSpace {
get {
CheckAsync();
return coreWriter.XmlSpace;
}
}
public override string XmlLang {
get {
CheckAsync();
return coreWriter.XmlLang;
}
}
public override void WriteNmToken(string name) {
CheckAsync();
coreWriter.WriteNmToken(name);
}
public override void WriteName(string name) {
CheckAsync();
coreWriter.WriteName(name);
}
public override void WriteQualifiedName(string localName, string ns) {
CheckAsync();
coreWriter.WriteQualifiedName(localName, ns);
}
public override void WriteValue(object value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(string value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(bool value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(DateTime value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(double value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(float value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(decimal value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(int value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteValue(long value) {
CheckAsync();
coreWriter.WriteValue(value);
}
public override void WriteAttributes(XmlReader reader, bool defattr) {
CheckAsync();
coreWriter.WriteAttributes(reader, defattr);
}
public override void WriteNode(XmlReader reader, bool defattr) {
CheckAsync();
coreWriter.WriteNode(reader, defattr);
}
#if !FEATURE_NETCORE
public override void WriteNode(XPathNavigator navigator, bool defattr) {
CheckAsync();
coreWriter.WriteNode(navigator, defattr);
}
#endif
protected override void Dispose(bool disposing) {
CheckAsync();
//since it is protected method, we can't call coreWriter.Dispose(disposing).
//Internal, it is always called to Dipose(true). So call coreWriter.Dispose() is OK.
coreWriter.Dispose();
}
#endregion
#region Async Methods
public override Task WriteStartDocumentAsync() {
CheckAsync();
var task = coreWriter.WriteStartDocumentAsync();
lastTask = task;
return task;
}
public override Task WriteStartDocumentAsync(bool standalone) {
CheckAsync();
var task = coreWriter.WriteStartDocumentAsync(standalone);
lastTask = task;
return task;
}
public override Task WriteEndDocumentAsync() {
CheckAsync();
var task = coreWriter.WriteEndDocumentAsync();
lastTask = task;
return task;
}
public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) {
CheckAsync();
var task = coreWriter.WriteDocTypeAsync(name, pubid, sysid, subset);
lastTask = task;
return task;
}
public override Task WriteStartElementAsync(string prefix, string localName, string ns) {
CheckAsync();
var task = coreWriter.WriteStartElementAsync(prefix, localName, ns);
lastTask = task;
return task;
}
public override Task WriteEndElementAsync() {
CheckAsync();
var task = coreWriter.WriteEndElementAsync();
lastTask = task;
return task;
}
public override Task WriteFullEndElementAsync() {
CheckAsync();
var task = coreWriter.WriteFullEndElementAsync();
lastTask = task;
return task;
}
protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string ns) {
CheckAsync();
var task = coreWriter.WriteStartAttributeAsync(prefix, localName, ns);
lastTask = task;
return task;
}
protected internal override Task WriteEndAttributeAsync() {
CheckAsync();
var task = coreWriter.WriteEndAttributeAsync();
lastTask = task;
return task;
}
public override Task WriteCDataAsync(string text) {
CheckAsync();
var task = coreWriter.WriteCDataAsync(text);
lastTask = task;
return task;
}
public override Task WriteCommentAsync(string text) {
CheckAsync();
var task = coreWriter.WriteCommentAsync(text);
lastTask = task;
return task;
}
public override Task WriteProcessingInstructionAsync(string name, string text) {
CheckAsync();
var task = coreWriter.WriteProcessingInstructionAsync(name, text);
lastTask = task;
return task;
}
public override Task WriteEntityRefAsync(string name) {
CheckAsync();
var task = coreWriter.WriteEntityRefAsync(name);
lastTask = task;
return task;
}
public override Task WriteCharEntityAsync(char ch) {
CheckAsync();
var task = coreWriter.WriteCharEntityAsync(ch);
lastTask = task;
return task;
}
public override Task WriteWhitespaceAsync(string ws) {
CheckAsync();
var task = coreWriter.WriteWhitespaceAsync(ws);
lastTask = task;
return task;
}
public override Task WriteStringAsync(string text) {
CheckAsync();
var task = coreWriter.WriteStringAsync(text);
lastTask = task;
return task;
}
public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) {
CheckAsync();
var task = coreWriter.WriteSurrogateCharEntityAsync(lowChar, highChar);
lastTask = task;
return task;
}
public override Task WriteCharsAsync(char[] buffer, int index, int count) {
CheckAsync();
var task = coreWriter.WriteCharsAsync(buffer, index, count);
lastTask = task;
return task;
}
public override Task WriteRawAsync(char[] buffer, int index, int count) {
CheckAsync();
var task = coreWriter.WriteRawAsync(buffer, index, count);
lastTask = task;
return task;
}
public override Task WriteRawAsync(string data) {
CheckAsync();
var task = coreWriter.WriteRawAsync(data);
lastTask = task;
return task;
}
public override Task WriteBase64Async(byte[] buffer, int index, int count) {
CheckAsync();
var task = coreWriter.WriteBase64Async(buffer, index, count);
lastTask = task;
return task;
}
public override Task WriteBinHexAsync(byte[] buffer, int index, int count) {
CheckAsync();
var task = coreWriter.WriteBinHexAsync(buffer, index, count);
lastTask = task;
return task;
}
public override Task FlushAsync() {
CheckAsync();
var task = coreWriter.FlushAsync();
lastTask = task;
return task;
}
public override Task WriteNmTokenAsync(string name) {
CheckAsync();
var task = coreWriter.WriteNmTokenAsync(name);
lastTask = task;
return task;
}
public override Task WriteNameAsync(string name) {
CheckAsync();
var task = coreWriter.WriteNameAsync(name);
lastTask = task;
return task;
}
public override Task WriteQualifiedNameAsync(string localName, string ns) {
CheckAsync();
var task = coreWriter.WriteQualifiedNameAsync(localName, ns);
lastTask = task;
return task;
}
public override Task WriteAttributesAsync(XmlReader reader, bool defattr) {
CheckAsync();
var task = coreWriter.WriteAttributesAsync(reader, defattr);
lastTask = task;
return task;
}
public override Task WriteNodeAsync(XmlReader reader, bool defattr) {
CheckAsync();
var task = coreWriter.WriteNodeAsync(reader, defattr);
lastTask = task;
return task;
}
#if !FEATURE_NETCORE
public override Task WriteNodeAsync(XPathNavigator navigator, bool defattr) {
CheckAsync();
var task = coreWriter.WriteNodeAsync(navigator, defattr);
lastTask = task;
return task;
}
#endif // !FEATURE_NETCORE
#endregion
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//***************************************************
using System;
using System.Collections.Generic;
using SharpKit.JavaScript;
namespace Y_
{
/// <summary>
/// Provides header/body/footer button support for Widgets that use the
/// `WidgetStdMod` extension.
/// This Widget extension makes it easy to declaratively configure a widget's
/// buttons. It adds a `buttons` attribute along with button- accessor and mutator
/// methods. All button nodes have the `Y.Plugin.Button` plugin applied.
/// This extension also includes `HTML_PARSER` support to seed a widget's `buttons`
/// from those which already exist in its DOM.
/// </summary>
public partial class WidgetButtons
{
/// <summary>
/// Handles this widget's `buttonsChange` event which fires anytime the
/// `buttons` attribute is modified.
/// **Note:** This method special-cases the `buttons` modifications caused by
/// `addButton()` and `removeButton()`, both of which set the `src` property on
/// the event facade to "add" and "remove" respectively.
/// </summary>
protected void _afterButtonsChange(EventFacade e){}
/// <summary>
/// Handles this widget's `headerContentChange`, `bodyContentChange`,
/// `footerContentChange` events by making sure the `buttons` remain rendered
/// after changes to the content areas.
/// These events are very chatty, so extra caution is taken to avoid doing extra
/// work or getting into an infinite loop.
/// </summary>
protected void _afterContentChangeButtons(EventFacade e){}
/// <summary>
/// Handles this widget's `defaultButtonChange` event by adding the
/// "yui3-button-primary" CSS class to the new `defaultButton` and removing it
/// from the old default button.
/// </summary>
protected void _afterDefaultButtonChange(EventFacade e){}
/// <summary>
/// Handles this widget's `visibleChange` event by focusing the `defaultButton`
/// if there is one.
/// </summary>
protected void _afterVisibleChangeButtons(EventFacade e){}
/// <summary>
/// Binds UI event listeners. This method is inserted via AOP, and will execute
/// after `bindUI()`.
/// </summary>
protected void _bindUIButtons(){}
/// <summary>
/// Returns a button node based on the specified `button` node or configuration.
/// The button node will either be created via `Y.Plugin.Button.createNode()`,
/// or when `button` is specified as a node already, it will by `plug()`ed with
/// `Y.Plugin.Button`.
/// </summary>
protected Node _createButton(object button){return null;}
[JsMethod(JsonInitializers=true)]
public WidgetButtons(){}
/// <summary>
/// Returns the buttons container for the specified `section`, passing a truthy
/// value for `create` will create the node if it does not already exist.
/// **Note:** It is up to the caller to properly insert the returned container
/// node into the content section.
/// </summary>
protected Node _getButtonContainer(object section, object create){return null;}
/// <summary>
/// Returns whether or not the specified `button` is configured to be the
/// default button.
/// When a button node is specified, the button's `getData()` method will be
/// used to determine if the button is configured to be the default. When a
/// button config object is specified, the `isDefault` prop will determine
/// whether the button is the default.
/// **Note:** `<button data-default="true"></button>` is supported via the
/// `button.getData('default')` API call.
/// </summary>
protected object _getButtonDefault(object button){return null;}
/// <summary>
/// Returns the name of the specified `button`.
/// When a button node is specified, the button's `getData('name')` method is
/// preferred, but will fallback to `get('name')`, and the result will determine
/// the button's name. When a button config object is specified, the `name` prop
/// will determine the button's name.
/// **Note:** `<button data-name="foo"></button>` is supported via the
/// `button.getData('name')` API call.
/// </summary>
protected object _getButtonName(object button){return null;}
/// <summary>
/// Getter for the `buttons` attribute. A copy of the `buttons` object is
/// returned so the stored state cannot be modified by the callers of
/// `get('buttons')`.
/// This will recreate a copy of the `buttons` object, and each section array
/// (the button nodes are *not* copied/cloned.)
/// </summary>
protected object _getButtons(object buttons){return null;}
/// <summary>
/// Adds the specified `button` to the buttons map (both name -> button and
/// section:name -> button), and sets the button as the default if it is
/// configured as the default button.
/// **Note:** If two or more buttons are configured with the same `name` and/or
/// configured to be the default button, the last one wins.
/// </summary>
protected void _mapButton(Node button, object section){}
/// <summary>
/// Adds the specified `buttons` to the buttons map (both name -> button and
/// section:name -> button), and set the a button as the default if one is
/// configured as the default button.
/// **Note:** This will clear all previous button mappings and null-out any
/// previous default button! If two or more buttons are configured with the same
/// `name` and/or configured to be the default button, the last one wins.
/// </summary>
protected void _mapButtons(object buttons){}
/// <summary>
/// Returns a copy of the specified `config` object merged with any defaults
/// provided by a `srcNode` and/or a predefined configuration for a button
/// with the same `name` on the `BUTTONS` property.
/// </summary>
protected object _mergeButtonConfig(object config){return null;}
/// <summary>
/// `HTML_PARSER` implementation for the `buttons` attribute.
/// **Note:** To determine a button node's name its `data-name` and `name`
/// attributes are examined. Whether the button should be the default is
/// determined by its `data-default` attribute.
/// </summary>
protected object _parseButtons(Node srcNode){return null;}
/// <summary>
/// Setter for the `buttons` attribute. This processes the specified `config`
/// and returns a new `buttons` object which is stored as the new state; leaving
/// the original, specified `config` unmodified.
/// The button nodes will either be created via `Y.Plugin.Button.createNode()`,
/// or when a button is already a Node already, it will by `plug()`ed with
/// `Y.Plugin.Button`.
/// </summary>
protected object _setButtons(object config){return null;}
/// <summary>
/// Syncs this widget's current button-related state to its DOM. This method is
/// inserted via AOP, and will execute after `syncUI()`.
/// </summary>
protected void _syncUIButtons(){}
/// <summary>
/// Inserts the specified `button` node into this widget's DOM at the specified
/// `section` and `index` and updates the section content.
/// The section and button container nodes will be created if they do not
/// already exist.
/// </summary>
protected void _uiInsertButton(Node button, object section, Y_.DataType_.Number index){}
/// <summary>
/// Removes the button node from this widget's DOM and detaches any event
/// subscriptions on the button that were created by this widget. The section
/// content will be updated unless `{preserveContent: true}` is passed in the
/// `options`.
/// By default the button container node will be removed when this removes the
/// last button of the specified `section`; and if no other content remains in
/// the section node, it will also be removed.
/// </summary>
protected void _uiRemoveButton(Node button, object section){}
/// <summary>
/// Removes the button node from this widget's DOM and detaches any event
/// subscriptions on the button that were created by this widget. The section
/// content will be updated unless `{preserveContent: true}` is passed in the
/// `options`.
/// By default the button container node will be removed when this removes the
/// last button of the specified `section`; and if no other content remains in
/// the section node, it will also be removed.
/// </summary>
protected void _uiRemoveButton(Node button, object section, object options){}
/// <summary>
/// Sets the current `buttons` state to this widget's DOM by rendering the
/// specified collection of `buttons` and updates the contents of each section
/// as needed.
/// Button nodes which already exist in the DOM will remain intact, or will be
/// moved if they should be in a new position. Old button nodes which are no
/// longer represented in the specified `buttons` collection will be removed,
/// and any event subscriptions on the button which were created by this widget
/// will be detached.
/// If the button nodes in this widget's DOM actually change, then each content
/// section will be updated (or removed) appropriately.
/// </summary>
protected void _uiSetButtons(object buttons){}
/// <summary>
/// Adds the "yui3-button-primary" CSS class to the new `defaultButton` and
/// removes it from the old default button.
/// </summary>
protected void _uiSetDefaultButton(Node newButton, Node oldButton){}
/// <summary>
/// Focuses this widget's `defaultButton` if there is one and this widget is
/// visible.
/// </summary>
protected void _uiSetVisibleButtons(object visible){}
/// <summary>
/// Removes the specified `button` to the buttons map, and nulls-out the
/// `defaultButton` if it is currently the default button.
/// </summary>
protected void _unMapButton(Node button){}
/// <summary>
/// Updates the content attribute which corresponds to the specified `section`.
/// The method updates the section's content to its current `childNodes`
/// (text and/or HTMLElement), or will null-out its contents if the section is
/// empty. It also specifies a `src` of `buttons` on the change event facade.
/// </summary>
protected void _updateContentButtons(object section){}
/// <summary>
/// Updates the `defaultButton` attribute if it needs to be updated by comparing
/// its current value with the protected `_defaultButton` property.
/// </summary>
protected void _updateDefaultButton(){}
/// <summary>
/// Adds a button to this widget.
/// The new button node will have the `Y.Plugin.Button` plugin applied, be added
/// to this widget's `buttons`, and rendered in the specified `section` at the
/// specified `index` (or end of the section). If the section does not exist, it
/// will be created.
/// This fires the `buttonsChange` event and adds the following properties to
/// the event facade:
/// * `button`: The button node or config object to add.
/// * `section`: The `WidgetStdMod` section (header/body/footer) where the
/// button should be added.
/// * `index`: The index at which to add the button to the section.
/// * `src`: "add"
/// </summary>
public void addButton(object button){}
/// <summary>
/// Adds a button to this widget.
/// The new button node will have the `Y.Plugin.Button` plugin applied, be added
/// to this widget's `buttons`, and rendered in the specified `section` at the
/// specified `index` (or end of the section). If the section does not exist, it
/// will be created.
/// This fires the `buttonsChange` event and adds the following properties to
/// the event facade:
/// * `button`: The button node or config object to add.
/// * `section`: The `WidgetStdMod` section (header/body/footer) where the
/// button should be added.
/// * `index`: The index at which to add the button to the section.
/// * `src`: "add"
/// </summary>
public void addButton(object button, Y_.DataType_.Number index){}
/// <summary>
/// Adds a button to this widget.
/// The new button node will have the `Y.Plugin.Button` plugin applied, be added
/// to this widget's `buttons`, and rendered in the specified `section` at the
/// specified `index` (or end of the section). If the section does not exist, it
/// will be created.
/// This fires the `buttonsChange` event and adds the following properties to
/// the event facade:
/// * `button`: The button node or config object to add.
/// * `section`: The `WidgetStdMod` section (header/body/footer) where the
/// button should be added.
/// * `index`: The index at which to add the button to the section.
/// * `src`: "add"
/// </summary>
public void addButton(object button, object section){}
/// <summary>
/// Adds a button to this widget.
/// The new button node will have the `Y.Plugin.Button` plugin applied, be added
/// to this widget's `buttons`, and rendered in the specified `section` at the
/// specified `index` (or end of the section). If the section does not exist, it
/// will be created.
/// This fires the `buttonsChange` event and adds the following properties to
/// the event facade:
/// * `button`: The button node or config object to add.
/// * `section`: The `WidgetStdMod` section (header/body/footer) where the
/// button should be added.
/// * `index`: The index at which to add the button to the section.
/// * `src`: "add"
/// </summary>
public void addButton(object button, object section, Y_.DataType_.Number index){}
/// <summary>
/// Returns a button node from this widget's `buttons`.
/// </summary>
public Node getButton(object name){return null;}
/// <summary>
/// Returns a button node from this widget's `buttons`.
/// </summary>
public Node getButton(object name, object section){return null;}
/// <summary>
/// Removes a button from this widget.
/// The button will be removed from this widget's `buttons` and its DOM. Any
/// event subscriptions on the button which were created by this widget will be
/// detached. If the content section becomes empty after removing the button
/// node, then the section will also be removed.
/// This fires the `buttonsChange` event and adds the following properties to
/// the event facade:
/// * `button`: The button node to remove.
/// * `section`: The `WidgetStdMod` section (header/body/footer) where the
/// button should be removed from.
/// * `index`: The index at which at which the button exists in the section.
/// * `src`: "remove"
/// </summary>
public void removeButton(object button){}
/// <summary>
/// Removes a button from this widget.
/// The button will be removed from this widget's `buttons` and its DOM. Any
/// event subscriptions on the button which were created by this widget will be
/// detached. If the content section becomes empty after removing the button
/// node, then the section will also be removed.
/// This fires the `buttonsChange` event and adds the following properties to
/// the event facade:
/// * `button`: The button node to remove.
/// * `section`: The `WidgetStdMod` section (header/body/footer) where the
/// button should be removed from.
/// * `index`: The index at which at which the button exists in the section.
/// * `src`: "remove"
/// </summary>
public void removeButton(object button, object section){}
/// <summary>
/// A map of button node `_yuid` -> event-handle for all button nodes which were
/// created by this widget.
/// </summary>
protected object _buttonsHandles{get;set;}
/// <summary>
/// A map of this widget's `buttons`, both name -> button and
/// section:name -> button.
/// </summary>
protected object _buttonsMap{get;set;}
/// <summary>
/// Internal reference to this widget's default button.
/// </summary>
protected Node _defaultButton{get;set;}
/// <summary>
/// Collection containing a widget's buttons.
/// The collection is an Object which contains an Array of `Y.Node`s for every
/// `WidgetStdMod` section (header, body, footer) which has one or more buttons.
/// All button nodes have the `Y.Plugin.Button` plugin applied.
/// This attribute is very flexible in the values it will accept. `buttons` can
/// be specified as a single Array, or an Object of Arrays keyed to a particular
/// section.
/// All specified values will be normalized to this type of structure:
/// {
/// header: [...],
/// footer: [...]
/// }
/// A button can be specified as a `Y.Node`, config Object, or String name for a
/// predefined button on the `BUTTONS` prototype property. When a config Object
/// is provided, it will be merged with any defaults provided by a button with
/// the same `name` defined on the `BUTTONS` property.
/// See `addButton()` for the detailed list of configuration properties.
/// For convenience, a widget's buttons will always persist and remain rendered
/// after header/body/footer content updates. Buttons should be removed by
/// updating this attribute or using the `removeButton()` method.
/// </summary>
public object buttons{get;set;}
/// <summary>
/// Collection of predefined buttons mapped by name -> config.
/// These button configurations will serve as defaults for any button added to a
/// widget's buttons which have the same `name`.
/// See `addButton()` for a list of possible configuration values.
/// </summary>
public object BUTTONS{get;set;}
/// <summary>
/// CSS classes used by `WidgetButtons`.
/// </summary>
public object CLASS_NAMES{get;set;}
/// <summary>
/// The current default button as configured through this widget's `buttons`.
/// A button can be configured as the default button in the following ways:
/// * As a config Object with an `isDefault` property:
/// `{label: 'Okay', isDefault: true}`.
/// * As a Node with a `data-default` attribute:
/// `<button data-default="true">Okay</button>`.
/// This attribute is **read-only**; anytime there are changes to this widget's
/// `buttons`, the `defaultButton` will be updated if needed.
/// **Note:** If two or more buttons are configured to be the default button,
/// the last one wins.
/// </summary>
public Node defaultButton{get;private set;}
/// <summary>
/// The list of button configuration properties which are specific to
/// `WidgetButtons` and should not be passed to `Y.Plugin.Button.createNode()`.
/// </summary>
public Y_.Array NON_BUTTON_NODE_CFG{get;set;}
}
}
| |
// 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.PetstoreV2NoSync
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SwaggerPetstoreV2.
/// </summary>
public static partial class SwaggerPetstoreV2Extensions
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class Actor : MonoBehaviour
{
enum State
{
IDLE,
MOVING,
}
float m_speed;
float m_speed_multi = 5;
public bool DebugMode;
bool onNode = true;
Vector3 m_target = new Vector3(0, 0, 0);
Vector3 currNode, targPos, movVec;
int nodeIndex;
List<Vector3> path = new List<Vector3>();
NodeControl control;
State state = State.IDLE;
float OldTime = 0;
float checkTime = 0;
float elapsedTime = 0;
float zDiff = -1;
bool toP = false;
bool canMove = false;
Enemy me;
float force;
private GameObject target;
void Awake()
{
GameObject cam = GameObject.FindGameObjectWithTag("MainCamera");
me = GetComponent<Enemy>();
control = GetComponent<NodeControl>();
canMove = false;
//control = (NodeControl)cam.GetComponent(typeof(NodeControl));
target = null;
targPos = gameObject.transform.position;
force = 10;
}
void Update()
{
//m_speed = Time.deltaTime * m_speed_multi;
canMove = me.getCanMove();
if(state == State.MOVING)
{
if(elapsedTime > 0.25)
{
elapsedTime = 0;
if(target != null)
MoveOrder(target.transform.position, toP);
else
{
target = me.target;
MoveOrder(target.transform.position, toP);
}
}
MoveToward();
if (canMove)
me.MoveToDir(targPos, 10);
}
me.updateMove(targPos);
//if (elapsedTime > OldTime)
//{
// switch (state)
// {
// case State.IDLE:
// break;
// case State.MOVING:
// OldTime = elapsedTime + 0.01f;
// if (elapsedTime > checkTime)
// {
// checkTime = elapsedTime + 1;
// //SetTarget();
// MoveOrder(target.transform.position, toP);
// }
// if (path != null)
// {
// if (onNode)
// {
// onNode = false;
// if (nodeIndex < path.Count)
// {
// MoveOrder(target.transform.position, toP);
// currNode = path[nodeIndex];
// }
// }
// MoveToward();
// }
// else
// {
// me.MoveToDir(me.targetPos);
// }
// break;
// }
//}
elapsedTime += Time.deltaTime;
}
void MoveToward()
{
if (path == null)
{
currNode = target.transform.position;
}
else
{
currNode = path[nodeIndex];
}
if (DebugMode)
{
for (int i = 0; i < path.Count - 1; ++i)
{
Debug.DrawLine((Vector3)path[i], (Vector3)path[i + 1], Color.magenta, 0.01f);
}
}
if (canMove)
{
Vector3 newPos = transform.position;
if ((currNode - newPos).magnitude < 0.25) //Reached target
{
if (m_target == currNode)
{
//ChangeState(State.IDLE);
MoveOrder(target.transform.position, toP);
}
else
{
nodeIndex++;
onNode = true;
if (path != null && nodeIndex < path.Count)
currNode = path[nodeIndex];
else
{
MoveOrder(target.transform.position, toP);
}
}
}
/***Move toward waypoint***/
//Debug.Log(currNode);
//newPos += motion;
Debug.DrawLine(transform.position, currNode, Color.red, 0.01f);
Vector3 motion = new Vector3(currNode.x, 0, currNode.z);
targPos = motion;
//newPos += motion * m_speed;
//transform.position = newPos;
}
}
public void setMove(bool c)
{
canMove = c;
}
private void SetTarget()
{
int temp = 0;
do
{
path = control.Path(transform.position, m_target, zDiff);
temp++;
} while (path == null && temp < 5);
nodeIndex = 0;
onNode = true;
}
public void setZ(float z)
{
zDiff = z;
}
public void MoveOrder(Vector3 pos, bool toPlayer = false)
{
toP = toPlayer;
if (toPlayer)
{
float f = Mathf.Sign(pos.x - transform.position.x);
m_target = pos + new Vector3(-1.5f, 0, 0) * f;
}
else
m_target = pos;
SetTarget();
ChangeState(State.MOVING);
}
private void ChangeState(State newState)
{
state = newState;
}
public void setTarg(GameObject g)
{
target = g;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.