context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.ReplacePropertyWithMethods;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplacePropertyWithMethods
{
public class ReplacePropertyWithMethodsTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ReplacePropertyWithMethodsCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetWithBody()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPublicProperty()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAnonyousType1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAnonyousType2()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void M()
{
var v = new { this.Prop } }
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void M()
{
var v = new { Prop = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPassedToRef1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void RefM(ref int i)
{
}
public void M()
{
RefM(ref this.Prop);
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void RefM(ref int i)
{
}
public void M()
{
RefM(ref this.{|Conflict:GetProp|}());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestPassedToOut1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public void OutM(out int i)
{
}
public void M()
{
OutM(out this.Prop);
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
public void OutM(out int i)
{
}
public void M()
{
OutM(out this.{|Conflict:GetProp|}());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUsedInAttribute1()
{
await TestInRegularAndScriptAsync(
@"using System;
class CAttribute : Attribute
{
public int [||]Prop
{
get
{
return 0;
}
}
}
[C(Prop = 1)]
class D
{
}",
@"using System;
class CAttribute : Attribute
{
public int GetProp()
{
return 0;
}
}
[C({|Conflict:Prop|} = 1)]
class D
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestSetWithBody1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
set
{
var v = value;
}
}
}",
@"class C
{
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestSetReference1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
set
{
var v = value;
}
}
void M()
{
this.Prop = 1;
}
}",
@"class C
{
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetterAndSetter()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestGetterAndSetterAccessibilityChange()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
private set
{
var v = value;
}
}
}",
@"class C
{
public int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestIncrement1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop++;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDecrement2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop--;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() - 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestRecursiveGet()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return this.Prop + 1;
}
}
}",
@"class C
{
private int GetProp()
{
return this.GetProp() + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestRecursiveSet()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
set
{
this.Prop = value + 1;
}
}
}",
@"class C
{
private void SetProp(int value)
{
this.SetProp(value + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCompoundAssign1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop *= x;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() * x);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCompoundAssign2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
var v = value;
}
}
void M()
{
this.Prop *= x + y;
}
}",
@"class C
{
private int GetProp()
{
return 0;
}
private void SetProp(int value)
{
var v = value;
}
void M()
{
this.SetProp(this.GetProp() * (x + y));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestMissingAccessors()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { }
void M()
{
var v = this.Prop;
}
}",
@"class C
{
void M()
{
var v = this.GetProp();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedProp()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop => 1;
}",
@"class C
{
private int GetProp()
{
return 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedPropWithTrailingTrivia()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop => 1; // Comment
}",
@"class C
{
private int GetProp()
{
return 1; // Comment
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIndentation()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Foo
{
get
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}
}",
@"class C
{
private int GetFoo()
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestComputedPropWithTrailingTriviaAfterArrow()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop => /* return 42 */ 42;
}",
@"class C
{
public int GetProp()
{
/* return 42 */
return 42;
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAbstractProperty()
{
await TestInRegularAndScriptAsync(
@"class C
{
public abstract int [||]Prop { get; }
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public abstract int GetProp();
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestVirtualProperty()
{
await TestInRegularAndScriptAsync(
@"class C
{
public virtual int [||]Prop
{
get
{
return 1;
}
}
public void M()
{
var v = new { P = this.Prop } }
}",
@"class C
{
public virtual int GetProp()
{
return 1;
}
public void M()
{
var v = new { P = this.GetProp() } }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestInterfaceProperty()
{
await TestInRegularAndScriptAsync(
@"interface I
{
int [||]Prop { get; }
}",
@"interface I
{
int GetProp();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; }
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty2()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; }
public C()
{
this.Prop++;
}
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
public C()
{
this.prop = this.GetProp() + 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty3()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; }
public C()
{
this.Prop *= x + y;
}
}",
@"class C
{
private readonly int prop;
public int GetProp()
{
return prop;
}
public C()
{
this.prop = this.GetProp() * (x + y);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty4()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop { get; } = 1;
}",
@"class C
{
private readonly int prop = 1;
public int GetProp()
{
return prop;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty5()
{
await TestInRegularAndScriptAsync(
@"class C
{
private int prop;
public int [||]Prop { get; } = 1;
}",
@"class C
{
private int prop;
private readonly int prop1 = 1;
public int GetProp()
{
return prop1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestAutoProperty6()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]PascalCase { get; }
}",
@"class C
{
private readonly int pascalCase;
public int GetPascalCase()
{
return pascalCase;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName1()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
get
{
return 0;
}
}
public abstract int GetProp();
}",
@"class C
{
public int GetProp1()
{
return 0;
}
public abstract int GetProp();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName2()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]Prop
{
set
{
}
}
public abstract void SetProp(int i);
}",
@"class C
{
public void SetProp1(int value)
{
}
public abstract void SetProp(int i);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestUniqueName3()
{
await TestInRegularAndScriptAsync(
@"class C
{
public object [||]Prop
{
set
{
}
}
public abstract void SetProp(dynamic i);
}",
@"class C
{
public void SetProp1(object value)
{
}
public abstract void SetProp(dynamic i);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop++;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() + 1);
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
/* Leading */
Prop++; /* Trailing */
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
/* Leading */
SetProp(GetProp() + 1); /* Trailing */
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestTrivia3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
/* Leading */
Prop += 1 /* Trailing */ ;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
/* Leading */
SetProp(GetProp() + 1 /* Trailing */ );
}
}", ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task ReplaceReadInsideWrite1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop = Prop + 1;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() + 1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task ReplaceReadInsideWrite2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
void M()
{
Prop *= Prop + 1;
}
}",
@"class C
{
private int prop;
private int GetProp()
{
return prop;
}
private void SetProp(int value)
{
prop = value;
}
void M()
{
SetProp(GetProp() * (GetProp() + 1));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
[WorkItem(16157, "https://github.com/dotnet/roslyn/issues/16157")]
public async Task TestWithConditionalBinding1()
{
await TestInRegularAndScriptAsync(
@"public class Foo
{
public bool [||]Any { get; } // Replace 'Any' with method
public static void Bar()
{
var foo = new Foo();
bool f = foo?.Any == true;
}
}",
@"public class Foo
{
private readonly bool any;
public bool GetAny()
{
return any;
}
public static void Bar()
{
var foo = new Foo();
bool f = foo?.GetAny() == true;
}
}");
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
}
}",
@"class C
{
private int GetProp() => 0;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
return 0;
}
set
{
throw e;
}
}
}",
@"class C
{
private int GetProp() => 0;
private void SetProp(int value) => throw e;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get => 0;
set => throw e;
}
}",
@"class C
{
private int GetProp() => 0;
private void SetProp(int value) => throw e;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop => 0;
}",
@"class C
{
private int GetProp() => 0;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle5()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; }
}",
@"class C
{
private readonly int prop;
private int GetProp() => prop;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle6()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop { get; set; }
}",
@"class C
{
private int prop;
private int GetProp() => prop;
private void SetProp(int value) => prop = value;
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestCodeStyle7()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
A();
return B();
}
}
}",
@"class C
{
private int GetProp()
{
A();
return B();
}
}", ignoreTrivia: false, options: PreferExpressionBodiedMethods);
}
[WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDocumentationComment1()
{
await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Gets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <value>
/// An value that provides access to the language service for the active configured project.
/// </value>
object [||]ActiveProjectContext
{
get;
}
}",
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Gets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <returns>
/// An value that provides access to the language service for the active configured project.
/// </returns>
object GetActiveProjectContext();
}", ignoreTrivia: false);
}
[WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDocumentationComment2()
{
await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Sets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <value>
/// An value that provides access to the language service for the active configured project.
/// </value>
object [||]ActiveProjectContext
{
set;
}
}",
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Sets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <param name=""value"">
/// An value that provides access to the language service for the active configured project.
/// </param>
void SetActiveProjectContext(object value);
}", ignoreTrivia: false);
}
[WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDocumentationComment3()
{
await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Gets or sets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <value>
/// An value that provides access to the language service for the active configured project.
/// </value>
object [||]ActiveProjectContext
{
get; set;
}
}",
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Gets or sets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <returns>
/// An value that provides access to the language service for the active configured project.
/// </returns>
object GetActiveProjectContext();
/// <summary>
/// Gets or sets the active workspace project context that provides access to the language service for the active configured project.
/// </summary>
/// <param name=""value"">
/// An value that provides access to the language service for the active configured project.
/// </param>
void SetActiveProjectContext(object value);
}", ignoreTrivia: false);
}
[WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDocumentationComment4()
{
await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Sets <see cref=""ActiveProjectContext""/>.
/// </summary>
/// <seealso cref=""ActiveProjectContext""/>
object [||]ActiveProjectContext
{
set;
}
}
internal struct AStruct
{
/// <seealso cref=""ILanguageServiceHost.ActiveProjectContext""/>
private int x;
}",
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Sets <see cref=""SetActiveProjectContext(object)""/>.
/// </summary>
/// <seealso cref=""SetActiveProjectContext(object)""/>
void SetActiveProjectContext(object value);
}
internal struct AStruct
{
/// <seealso cref=""ILanguageServiceHost.SetActiveProjectContext(object)""/>
private int x;
}", ignoreTrivia: false);
}
[WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDocumentationComment5()
{
await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Gets or sets <see cref=""ActiveProjectContext""/>.
/// </summary>
/// <seealso cref=""ActiveProjectContext""/>
object [||]ActiveProjectContext
{
get; set;
}
}
internal struct AStruct
{
/// <seealso cref=""ILanguageServiceHost.ActiveProjectContext""/>
private int x;
}",
@"internal interface ILanguageServiceHost
{
/// <summary>
/// Gets or sets <see cref=""GetActiveProjectContext()""/>.
/// </summary>
/// <seealso cref=""GetActiveProjectContext()""/>
object GetActiveProjectContext();
/// <summary>
/// Gets or sets <see cref=""GetActiveProjectContext()""/>.
/// </summary>
/// <seealso cref=""GetActiveProjectContext()""/>
void SetActiveProjectContext(object value);
}
internal struct AStruct
{
/// <seealso cref=""ILanguageServiceHost.GetActiveProjectContext()""/>
private int x;
}", ignoreTrivia: false);
}
[WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestDocumentationComment6()
{
await TestInRegularAndScriptAsync(
@"internal interface ISomeInterface<T>
{
/// <seealso cref=""Context""/>
ISomeInterface<T> [||]Context
{
set;
}
}
internal struct AStruct
{
/// <seealso cref=""ISomeInterface{T}.Context""/>
private int x;
}",
@"internal interface ISomeInterface<T>
{
/// <seealso cref=""SetContext(ISomeInterface{T})""/>
void SetContext(ISomeInterface<T> value);
}
internal struct AStruct
{
/// <seealso cref=""ISomeInterface{T}.SetContext(ISomeInterface{T})""/>
private int x;
}", ignoreTrivia: false);
}
[WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestWithDirectives1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
#if true
return 0;
#else
return 1;
#endif
}
}
}",
@"class C
{
private int GetProp()
{
#if true
return 0;
#else
return 1;
#endif
}
}", ignoreTrivia: false);
}
[WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestWithDirectives2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop
{
get
{
#if true
return 0;
#else
return 1;
#endif
}
}
}",
@"class C
{
private int GetProp() =>
#if true
0;
#else
return 1;
#endif
}", ignoreTrivia: false,
options: PreferExpressionBodiedMethods);
}
[WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestWithDirectives3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop =>
#if true
0;
#else
1;
#endif
}",
@"class C
{
private int GetProp() =>
#if true
0;
#else
1;
#endif
}", ignoreTrivia: false);
}
[WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
public async Task TestWithDirectives4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]Prop =>
#if true
0;
#else
1;
#endif
}",
@"class C
{
private int GetProp() =>
#if true
0;
#else
1;
#endif
}", ignoreTrivia: false,
options: PreferExpressionBodiedMethods);
}
private IDictionary<OptionKey, object> PreferExpressionBodiedMethods =>
OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement));
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class OrderByTests
{
// Class which is passed as an argument for Comparer
public class CaseInsensitiveComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x.ToLower(), y.ToLower());
}
}
// EqualityComparer to ignore case sensitivity: Added to support PLINQ
public class CaseInsensitiveEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (string.Compare(x.ToLower(), y.ToLower()) == 0) return true;
return false;
}
public int GetHashCode(string obj)
{
return getCaseInsensitiveString(obj).GetHashCode();
}
private string getCaseInsensitiveString(string word)
{
char[] wordchars = word.ToCharArray();
String newWord = "";
foreach (char c in wordchars)
{
newWord = newWord + (c.ToString().ToLower());
}
return newWord;
}
}
// Class to test a bad comparer: DDB: 48535
public class BadComparer1 : IComparer<int>
{
public int Compare(int x, int y)
{
return 1;
}
}
// Class to test a bad comparer: DDB: 48535
public class BadComparer2 : IComparer<int>
{
public int Compare(int x, int y)
{
return -1;
}
}
private struct Record
{
#pragma warning disable 0649
public string Name;
public int Score;
#pragma warning restore 0649
}
public class OrderBy011
{
private static int OrderBy001()
{
var q = from x1 in new int[] { 1, 6, 0, -1, 3 }
from x2 in new int[] { 55, 49, 9, -100, 24, 25 }
select new { a1 = x1, a2 = x2 };
var rst1 = q.OrderBy(e => e.a1).ThenBy(f => f.a2);
var rst2 = q.OrderBy(e => e.a1).ThenBy(f => f.a2);
return Verification.Allequal(rst1, rst2);
}
private static int OrderBy002()
{
var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 }
from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x2)
select new { a1 = x1, a2 = x2 };
var rst1 = q.OrderBy(e => e.a1);
var rst2 = q.OrderBy(e => e.a1);
return Verification.Allequal(rst1, rst2);
}
public static int Main()
{
int ret = RunTest(OrderBy001) + RunTest(OrderBy002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy1
{
// Overload-1: source is empty
public static int Test1()
{
int[] source = { };
int[] expected = { };
var actual = source.OrderBy((e) => e);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy10
{
// Overload-2: Test to verify that the QuickSort function handles underflow OutOfBounds Exception
// DDB: 48535
public static int Test10()
{
int[] source = { 1 };
int[] expected = { 1 };
var actual = source.OrderBy((e) => e, new BadComparer2());
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test10();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy2
{
// Overload-1: keySelector returns null
public static int Test2()
{
int?[] source = { null, null, null };
int?[] expected = { null, null, null };
var actual = source.OrderBy((e) => e);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy3
{
// Overload-1: All elements have the same key
public static int Test3()
{
int?[] source = { 9, 9, 9, 9, 9, 9 };
int?[] expected = { 9, 9, 9, 9, 9, 9 };
var actual = source.OrderBy((e) => e);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test3();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy4
{
// Overload-2: All elements have different keys.
// Verify keySelector function is called.
public static int Test4()
{
Record[] source = new Record[]{ new Record{Name = "Tim", Score = 90},
new Record{Name = "Robert", Score = 45},
new Record{Name = "Prakash", Score = 99}
};
Record[] expected = new Record[]{new Record{Name = "Prakash", Score = 99},
new Record{Name = "Robert", Score = 45},
new Record{Name = "Tim", Score = 90}
};
var actual = source.OrderBy((e) => e.Name, null);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test4();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy5
{
// Overload-2: 1st and last elements have same key and duplicate elements.
// Verify the given comparer function is called.
// This test calls AllequalCompaer with a EqualityComparer which is casInsensitive. This change is to help PLINQ team run our tests
public static int Test5()
{
string[] source = { "Prakash", "Alpha", "dan", "DAN", "Prakash" };
string[] expected = { "Alpha", "dan", "DAN", "Prakash", "Prakash" };
var actual = source.OrderBy((e) => e, new CaseInsensitiveComparer());
return Verification.AllequalComparer(expected, actual, new CaseInsensitiveEqualityComparer());
}
public static int Main()
{
return Test5();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy6
{
// Overload-2: 1st and last elements have same key and duplicate elements.
// Verify default comparer is called. (Also verifies that Order is preserved)
public static int Test6()
{
string[] source = { "Prakash", "Alpha", "dan", "DAN", "Prakash" };
string[] expected = { "Alpha", "dan", "DAN", "Prakash", "Prakash" };
var actual = source.OrderBy((e) => e, null);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test6();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy7
{
// Overload-2: Elements are in descending order
public static int Test7()
{
int?[] source = { 100, 30, 9, 5, 0, -50, -75, null };
int?[] expected = { null, -75, -50, 0, 5, 9, 30, 100 };
var actual = source.OrderBy((e) => e, null);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test7();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy8
{
// Overload-2: All elements have same keys, verify Order is preserved
public static int Test8()
{
Record[] source = new Record[]{ new Record{Name = "Tim", Score = 90},
new Record{Name = "Robert", Score = 90},
new Record{Name = "Prakash", Score = 90},
new Record{Name = "Jim", Score = 90},
new Record{Name = "John", Score = 90},
new Record{Name = "Albert", Score = 90},
};
Record[] expected = new Record[]{new Record{Name = "Tim", Score = 90},
new Record{Name = "Robert", Score = 90},
new Record{Name = "Prakash", Score = 90},
new Record{Name = "Jim", Score = 90},
new Record{Name = "John", Score = 90},
new Record{Name = "Albert", Score = 90},
};
var actual = source.Select((e, i) => new { V = e, I = i }).OrderBy((e) => e.V.Score).ThenBy((e) => e.I).Select((e) => e.V);
//var actual = source.OrderBy((e) => e.Score, null);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test8();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class OrderBy9
{
// Overload-2: Test to verify that the QuickSort function handles overflow OutOfBounds Exception
// DDB: 48535
public static int Test9()
{
int[] source = { 1 };
int[] expected = { 1 };
var actual = source.OrderBy((e) => e, new BadComparer1());
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test9();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
//
// URIUtils.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, 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.
//
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.IO;
namespace Couchbase.Lite.Util
{
internal static class URIUtils
{
#region Constants
private const int NotFound = -1;
private const string Utf8Encoding = "UTF-8";
private const string NotHierarchical = "This isn't a hierarchical URI.";
private static readonly char[] HexDigits = "0123456789ABCDEF".ToCharArray();
#endregion
#region Public Methods
public static string GetQueryParameter(Uri uri, string key)
{
if (key == null) {
throw new ArgumentNullException("key");
}
string query = uri.Query;
if (query == null) {
return null;
}
string encodedKey = Encode(key, null);
int length = query.Length;
int start = 0;
do {
int nextAmpersand = query.IndexOf('&', start);
int end = nextAmpersand != -1 ? nextAmpersand : length;
int separator = query.IndexOf('=', start);
if (separator > end || separator == -1) {
separator = end;
}
if (separator - start == encodedKey.Length && query.RegionMatches(start, encodedKey
, 0, encodedKey.Length)) {
if (separator == end) {
return string.Empty;
} else {
string encodedValue = query.Substring(separator + 1, end - separator + 1);
return Decode(encodedValue, true, Encoding.UTF8);
}
}
// Move start to end of name.
if (nextAmpersand != -1) {
start = nextAmpersand + 1;
} else {
break;
}
} while (true);
return null;
}
public static string Encode(string s, string allow)
{
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuilder encoded = null;
int oldLength = s.Length;
// This loop alternates between copying over allowed characters and
// encoding in chunks. This results in fewer method calls and
// allocations than encoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over allowed chars.
// Find the next character which needs to be encoded.
int nextToEncode = current;
while (nextToEncode < oldLength && IsAllowed(s[nextToEncode], allow)) {
nextToEncode++;
}
// If there's nothing more to encode...
if (nextToEncode == oldLength) {
if (current == 0) {
// We didn't need to encode anything!
return s;
}
else {
// Presumably, we've already done some encoding.
encoded.Append(s, current, oldLength - current);
return encoded.ToString();
}
}
if (encoded == null) {
encoded = new StringBuilder();
}
if (nextToEncode > current) {
// Append allowed characters leading up to this point.
encoded.Append(s, current, nextToEncode - current);
}
// assert nextToEncode == current
// Switch to "encoding" mode.
// Find the next allowed character.
current = nextToEncode;
int nextAllowed = current + 1;
while (nextAllowed < oldLength && !IsAllowed(s[nextAllowed], allow)) {
nextAllowed++;
}
// Convert the substring to bytes and encode the bytes as
// '%'-escaped octets.
string toEncode = s.Substring(current, nextAllowed - current);
byte[] bytes = Encoding.UTF8.GetBytes(toEncode);
int bytesLength = bytes.Length;
for (int i = 0; i < bytesLength; i++) {
encoded.Append('%');
encoded.Append(HexDigits[(bytes[i] & unchecked((int)(0xf0))) >> 4]);
encoded.Append(HexDigits[bytes[i] & unchecked((int)(0xf))]);
}
current = nextAllowed;
}
// Encoded could still be null at this point if s is empty.
return encoded == null ? s : encoded.ToString();
}
public static string Decode(string s, bool convertPlus, Encoding charset)
{
if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1)) {
return s;
}
StringBuilder result = new StringBuilder(s.Length);
using (MemoryStream outStream = RecyclableMemoryStreamManager.SharedInstance.GetStream()) {
for (int i = 0; i < s.Length;) {
char c = s[i];
if (c == '%') {
do {
if (i + 2 >= s.Length) {
throw new ArgumentException(String.Format("Incomplete % sequence at: {0}", i));
}
int d1 = HexToInt(s[i + 1]);
int d2 = HexToInt(s[i + 2]);
if (d1 == -1 || d2 == -1) {
throw new ArgumentException("Invalid % sequence " + s.Substring(i, 3) + " at " + i);
}
outStream.WriteByte(unchecked((byte)((d1 << 4) + d2)));
i += 3;
} while (i < s.Length && s[i] == '%');
result.Append(charset.GetString(outStream.ToArray()));
outStream.Reset();
}
else {
if (convertPlus && c == '+') {
c = ' ';
}
result.Append(c);
i++;
}
}
}
return result.ToString();
}
public static int HexToInt(char c)
{
if ('0' <= c && c <= '9') {
return c - '0';
} else {
if ('a' <= c && c <= 'f') {
return 10 + (c - 'a');
}
else {
if ('A' <= c && c <= 'F') {
return 10 + (c - 'A');
}
else {
return -1;
}
}
}
}
public static Uri AppendPath(this Uri uri, string path)
{
if (uri == null) return null;
var newUri = new UriBuilder(uri);
newUri.Path = Path.Combine(newUri.Path.TrimEnd('/'), path.TrimStart('/'));
var newUriStr = new Uri(Uri.UnescapeDataString(newUri.Uri.AbsoluteUri));
return newUriStr;
}
public static Uri Append(this Uri uri, params string[] paths)
{
return new Uri(paths.Where(x => x != null).Aggregate(uri.AbsoluteUri, (current, path) => string.Format("{0}/{1}", current.TrimEnd('/'), path.TrimStart('/'))));
}
#endregion
#region Private Methods
private static bool IsAllowed(char c, string allow)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|| "_-!.~'()*".IndexOf(c) != NotFound || (allow != null && allow.IndexOf(c) !=
NotFound);
}
#endregion
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
public class HapringSelectAndRotate : Singleton<HapringSelectAndRotate>
{
public GameObject goalNode;
private int currentIndex = -1;
private bool joyNeutral = true;
//Has the joystick been neutral in the meantime
private bool bNeutral = true;
//Has the joystick been neutral in the meantime
private Vector3 lastRotRing;
private Vector3 lastRotGraph;
private Quaternion lastRingQuad;
private Quaternion lastGraphQuad;
public static String lastPressed = "";
//private Vector3 startPosition;
//History stuff. Stacks would be simpler thatn lists
private Stack<Vector3> camPosHistory;
private Stack<Quaternion> camRotHistory;
public GameObject pivot;
public enum BUTTON_DATA
{
BUTTONA_PRESSED = 0,
BUTTONA_RELEASED = 1,
BUTTONB_PRESSED = 2,
BUTTONB_RELEASED = 3,
NONE = 4
}
public enum JOYSTICK_DATA
{
INCREASE = 0,
DECREASE = 1,
NONE = 2
}
public string serverIP = "127.0.0.1";
public static int dllPort = 26000;
public int unityPort = 27000;
byte[] data;
Socket sender;
IPEndPoint target;
UDPReceiver workerObject;
float power;
float lastSentPower = 0;
static byte lastJoystickEventReceived = (byte)JOYSTICK_DATA.NONE;
public static byte lastCommandValue = (byte)BUTTON_DATA.NONE;
public static double qw;
public static double qx;
public static double qy;
public static double qz;
public static Quaternion rot;
public static float xDeg = 0;
public static float yDeg = 0;
public static byte pressureThreshold = 127;
public static bool isTipPressed = false;
public static float tipPressCounter = 0f;
public static float zDeg = 0;
Coroutine c;
Thread workerThread;
public Camera mainCamera;
public GameObject gameController;
private HapringController hapringController;
private Transform mainCameraParentTransform;
void Awake ()
{
sender = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
target = new IPEndPoint (IPAddress.Parse (serverIP), dllPort);
Debug.Log ("UDP sender ready!");
workerObject = new UDPReceiver (unityPort, dllPort);
workerThread = new Thread (workerObject.DoWork);
workerThread.Start ();
Debug.Log ("main thread: Starting worker thread...");
while (!workerThread.IsAlive)
;
Debug.Log ("UDP receiver ready!");
doRequest (0);
requestChangeOnOrientationStatus (true);
Settings settings = SaveLoad.Load ();
xDeg = settings.xDeg;
yDeg = settings.yDeg;
zDeg = settings.zDeg;
lastRotRing = rot.eulerAngles;
lastRotGraph = pivot.transform.rotation.eulerAngles;
lastGraphQuad = pivot.transform.rotation;
lastRingQuad = rot;
camPosHistory = new Stack<Vector3> ();
camRotHistory = new Stack<Quaternion> ();
}
void OnDestroy ()
{
doRequest (0);
Debug.Log ("worker thread stopping");
workerObject.RequestStop ();
workerThread.Join ();
try {
sender.Shutdown (SocketShutdown.Both);
sender.Close ();
} catch (Exception e) {
Debug.Log (e);
}
Debug.Log ("sender destroyed");
}
void Start ()
{
if (mainCamera == null) {
Debug.LogError ("Please attach main camera to this script!!!");
} else {
mainCameraParentTransform = mainCamera.transform.parent;
}
hapringController = gameController.GetComponent<HapringController> ();
}
private float lastBClick = 0f;
void Update ()
{
// select the nodes
nodeSelection ();
// rotate around bubble
rotateTargetObject ();
if (checkButtonBStatus ()) {
GoToBubble.Zoom ();
}
}
// code for selecting the nodes
void nodeSelection ()
{
if (checkNoJoystickEvent ()) {
joyNeutral = true;
}
if (checkIncreaseJoystickEvent () && joyNeutral) {
hapringController.switchNode (HapringController.Direction.left);
lastPressed = "HAPRING_JOYSTICK_UP";
joyNeutral = false;
} else if (checkDecreaseJoystickEvent () && joyNeutral) {
hapringController.switchNode (HapringController.Direction.right);
lastPressed = "HAPRING_JOYSTICK_DOWN";
joyNeutral = false;
}
//Debug.Log("TIP PRESS COUNTER " + tipPressCounter);
if (tipPressCounter > 11) {
startVibration ();
hapringController.switchNode (HapringController.Direction.select);
// Invoke ("stopVibration", 1.0f);
tipPressCounter = 0;
}
if (tipPressCounter > 0f) {
// tipPressCounter -= 0.025f;
}
}
// code for rot ating object
public void rotateTargetObject ()
{
if (checkButtonAStatus ()) {
mainCamera.transform.SetParent (pivot.transform);
Quaternion diff = Quaternion.Inverse (lastRingQuad) * rot;
pivot.transform.rotation = lastGraphQuad * diff;
} else {
stopVibration ();
mainCamera.transform.parent = mainCameraParentTransform;
lastRotRing = rot.eulerAngles;
lastRotGraph = pivot.transform.rotation.eulerAngles;
lastGraphQuad = pivot.transform.rotation;
lastRingQuad = rot;
}
}
private void saveSettings ()
{
Settings settings = new Settings ();
settings.xDeg = xDeg;
settings.yDeg = yDeg;
settings.zDeg = zDeg;
SaveLoad.Save (settings);
}
void OnGUI ()
{
Event e = Event.current;
if (e.type.Equals (EventType.KeyDown)) {
switch (e.keyCode) {
case KeyCode.Q:
xDeg++;
break;
case KeyCode.A:
xDeg--;
break;
case KeyCode.W:
yDeg++;
break;
case KeyCode.S:
yDeg--;
break;
case KeyCode.E:
zDeg++;
break;
case KeyCode.D:
zDeg--;
break;
case KeyCode.R:
saveSettings ();
break;
case KeyCode.UpArrow:
doRequest (127);
break;
case KeyCode.DownArrow:
doRequest (0);
break;
}
}
}
public void requestChangeOnOrientationStatus (bool status)
{
data = Encoding.ASCII.GetBytes ((status ? -1.0f : -2.0f).ToString ());
sender.SendTo (data, target);
}
public void doRequest (float power)
{
try {
if (power != lastSentPower) {
data = Encoding.ASCII.GetBytes (((byte)power).ToString ());
sender.SendTo (data, target);
lastSentPower = power;
}
} catch (UnityException e) {
Debug.Log ("EXCEPTION ******************************* " + e.Message);
}
}
public class UDPReceiver
{
UdpClient client;
IPEndPoint source;
public void DoWork ()
{
bool result;
while (!_shouldStop) {
try {
if (client.Available >= 1) {
byte[] data = client.Receive (ref source);
if (data.Length == 16) {
qw = (double)((((int)data [0] << 24) + ((int)data [1] << 16) + ((int)data [2] << 8) + data [3])) * (1.0 / (1 << 30));
qx = (double)((((int)data [4] << 24) + ((int)data [5] << 16) + ((int)data [6] << 8) + data [7])) * (1.0 / (1 << 30));
qy = (double)((((int)data [8] << 24) + ((int)data [9] << 16) + ((int)data [10] << 8) + data [11])) * (1.0 / (1 << 30));
qz = (double)((((int)data [12] << 24) + ((int)data [13] << 16) + ((int)data [14] << 8) + data [15])) * (1.0 / (1 << 30));
rot = Quaternion.Euler (xDeg, yDeg, zDeg) * new Quaternion ((float)qx, (float)qy, (float)qz, (float)qw);
//Debug.Log("IMU >>>>>> " + qx + " : "+ qy + " : "+ qz + " : " + qw);
} else if (data.Length == 1) {
tipPressCounter = 0;
result = Byte.TryParse (Encoding.UTF8.GetString (data), out lastCommandValue);
} else if (data.Length == 2) {
// code to set events
if (data [0] < 80) {
lastJoystickEventReceived = (byte)JOYSTICK_DATA.INCREASE;
} else if (data [0] > 240) {
lastJoystickEventReceived = (byte)JOYSTICK_DATA.DECREASE;
} else {
lastJoystickEventReceived = (byte)JOYSTICK_DATA.NONE;
}
} else if (data.Length == 3) {
if((data [2] > pressureThreshold)) {
tipPressCounter++;
lastPressed = "HAPRING_TIP";
} else {
tipPressCounter = 0;
}
}
}
} catch (Exception e) {
Debug.Log ("EXCEPTION ******************************* " + e.Message);
}
}
client.Close ();
Debug.Log ("worker thread: terminating gracefully.");
}
public void RequestStop ()
{
_shouldStop = true;
Debug.Log ("requesting worker thread shutdown");
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop = false;
public UDPReceiver (int port, int dllport)
{
//this.port = port;
//this.dllport = dllport;
client = new UdpClient (port);
source = new IPEndPoint (IPAddress.Broadcast, dllPort);
//client.Connect(source);
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public bool checkIncreaseJoystickEvent ()
{
if (lastJoystickEventReceived == (byte)JOYSTICK_DATA.INCREASE) {
//lastJoystickEventReceived = (byte)JOYSTICK_DATA.NONE;
return true;
}
return false;
}
public bool checkDecreaseJoystickEvent ()
{
if (lastJoystickEventReceived == (byte)JOYSTICK_DATA.DECREASE) {
//lastJoystickEventReceived = (byte)JOYSTICK_DATA.NONE;
return true;
}
return false;
}
public bool checkNoJoystickEvent ()
{
if (lastJoystickEventReceived == (byte)JOYSTICK_DATA.NONE) {
//lastJoystickEventReceived = (byte)JOYSTICK_DATA.NONE;
return true;
}
return false;
}
public void startVibration ()
{
doRequest (110);
}
public void stopVibration ()
{
doRequest (0);
}
public bool checkButtonAStatus ()
{
if (lastCommandValue == (byte)BUTTON_DATA.BUTTONA_PRESSED) {
lastPressed = "HAPRING_A";
return true;
}
return false;
}
public bool checkButtonBStatus ()
{
if (lastCommandValue == (byte)BUTTON_DATA.BUTTONB_PRESSED) {
lastPressed = "HAPRING_B";
return true;
}
return 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 System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection.Metadata.Cil.Decoder;
using System.Reflection.Metadata.Cil.Instructions;
using System.Reflection.Metadata.Cil.Visitor;
using System.Reflection.Metadata.Decoding;
using System.Reflection.Metadata.Ecma335;
using System.Text;
namespace System.Reflection.Metadata.Cil
{
/// <summary>
/// Class representing a method definition in a type whithin an assembly.
/// </summary>
public struct CilMethodDefinition : ICilVisitable
{
internal CilReaders _readers;
private MethodDefinition _methodDefinition;
private CilTypeProvider _provider;
private MethodBodyBlock _methodBody;
private CilMethodImport _import;
private string _name;
private int _rva;
private MethodSignature<CilType> _signature;
private BlobReader _ilReader;
private ImmutableArray<CilInstruction> _instructions;
private CilLocal[] _locals;
private CilParameter[] _parameters;
private int _token;
private IEnumerable<CilCustomAttribute> _customAttributes;
private IEnumerable<string> _genericParameters;
private CilTypeDefinition _typeDefinition;
private int _methodDeclarationToken;
private bool _isIlReaderInitialized;
private bool _isSignatureInitialized;
private bool _isImportInitialized;
private IReadOnlyList<CilExceptionRegion> _exceptionRegions;
internal static CilMethodDefinition Create(MethodDefinition methodDefinition, int token, ref CilReaders readers, CilTypeDefinition typeDefinition)
{
CilMethodDefinition method = new CilMethodDefinition();
method._methodDefinition = methodDefinition;
method._token = token;
method._typeDefinition = typeDefinition;
method._readers = readers;
method._provider = readers.Provider;
method._rva = -1;
method._methodDeclarationToken = -1;
method._isIlReaderInitialized = false;
method._isSignatureInitialized = false;
method._isImportInitialized = false;
if(method.RelativeVirtualAddress != 0)
method._methodBody = method._readers.PEReader.GetMethodBody(method.RelativeVirtualAddress);
return method;
}
internal static CilMethodDefinition Create(MethodDefinitionHandle methodHandle, ref CilReaders readers, CilTypeDefinition typeDefinition)
{
MethodDefinition method = readers.MdReader.GetMethodDefinition(methodHandle);
int token = MetadataTokens.GetToken(methodHandle);
return Create(method, token, ref readers, typeDefinition);
}
#region Internal Properties
internal MethodBodyBlock MethodBody
{
get
{
return _methodBody;
}
}
/// <summary>
/// BlobReader that contains the msil instruction bytes.
/// </summary>
internal BlobReader IlReader
{
get
{
if (!_isIlReaderInitialized)
{
_isIlReaderInitialized = true;
_ilReader = MethodBody.GetILReader();
}
return _ilReader;
}
}
/// <summary>
/// Type provider to solve type names and references.
/// </summary>
internal CilTypeProvider Provider
{
get
{
return _provider;
}
}
#endregion
#region Public APIs
/// <summary>
/// Method name
/// </summary>
public string Name
{
get
{
return CilDecoder.GetCachedValue(_methodDefinition.Name, _readers, ref _name);
}
}
public CilTypeDefinition DeclaringType
{
get
{
return _typeDefinition;
}
}
/// <summary>
/// Method Relative Virtual Address, if is equal to 0 it is a virtual method and has no body.
/// </summary>
public int RelativeVirtualAddress
{
get
{
if(_rva == -1)
{
_rva = _methodDefinition.RelativeVirtualAddress;
}
return _rva;
}
}
/// <summary>
/// Method Token.
/// </summary>
internal int Token
{
get
{
return _token;
}
}
/// <summary>
/// Code Size in bytes not including headers.
/// </summary>
public int Size
{
get
{
return IlReader.Length;
}
}
/// <summary>
/// Method max stack capacity
/// </summary>
public int MaxStack
{
get
{
return MethodBody.MaxStack;
}
}
/// <summary>
/// Method Signature containing the return type, parameter count and header information.
/// </summary>
public MethodSignature<CilType> Signature
{
get
{
if(!_isSignatureInitialized)
{
_isSignatureInitialized = true;
_signature = CilDecoder.DecodeMethodSignature(_methodDefinition, _provider);
}
return _signature;
}
}
public bool HasImport
{
get
{
return Attributes.HasFlag(MethodAttributes.PinvokeImpl);
}
}
public CilMethodImport Import
{
get
{
if (!_isImportInitialized)
{
_isImportInitialized = true;
_import = CilMethodImport.Create(_methodDefinition.GetImport(), ref _readers, _methodDefinition);
}
return _import;
}
}
/// <summary>
/// Boolean to know if it overrides a method definition.
/// </summary>
public bool IsImplementation
{
get
{
return MethodDeclarationToken != 0;
}
}
/// <summary>
/// Boolean to know if the local variables should be initialized with the "init" prefix on its signature.
/// </summary>
public bool LocalVariablesInitialized
{
get
{
return MethodBody.LocalVariablesInitialized;
}
}
/// <summary>
/// Boolean to know if the method has a locals declared on its body.
/// </summary>
public bool HasLocals
{
get
{
return !MethodBody.LocalSignature.IsNil;
}
}
/// <summary>
/// Boolean to know if the current method is the entry point of the assembly.
/// </summary>
public bool IsEntryPoint
{
get
{
return _token == _readers.PEReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
}
}
/// <summary>
/// Token that represents the token of the method declaration if this method overrides any. 0 if it doesn't override a declaration.
/// </summary>
public int MethodDeclarationToken
{
get
{
if (_methodDeclarationToken == -1)
{
_methodDeclarationToken = _typeDefinition.GetOverridenMethodToken(Token);
}
return _methodDeclarationToken;
}
}
/// <summary>
/// Flags on the method (Calling convention, accesibility flags, etc.
/// </summary>
public MethodAttributes Attributes
{
get
{
return _methodDefinition.Attributes;
}
}
public MethodImplAttributes ImplAttributes
{
get
{
return _methodDefinition.ImplAttributes;
}
}
/// <summary>
/// Custom attributes declared on the method body header.
/// </summary>
public IEnumerable<CilCustomAttribute> CustomAttributes
{
get
{
if(_customAttributes == null)
{
_customAttributes = PopulateCustomAttributes();
}
return _customAttributes;
}
}
/// <summary>
/// Exception regions in the method body.
/// </summary>
public IReadOnlyList<CilExceptionRegion> ExceptionRegions
{
get
{
if(_exceptionRegions == null)
{
_exceptionRegions = CilExceptionRegion.CreateRegions(MethodBody.ExceptionRegions);
}
return _exceptionRegions;
}
}
/// <summary>
/// List of instructions that represent the method body.
/// </summary>
public ImmutableArray<CilInstruction> Instructions
{
get
{
if(_instructions == null)
{
_instructions = CilDecoder.DecodeMethodBody(this).ToImmutableArray();
}
return _instructions;
}
}
/// <summary>
/// Parameters that the method take.
/// </summary>
public CilParameter[] Parameters
{
get
{
if (_parameters == null)
{
_parameters = CilDecoder.DecodeParameters(Signature, _methodDefinition.GetParameters(), ref _readers);
}
return _parameters;
}
}
/// <summary>
/// Locals contained on the method body.
/// </summary>
public CilLocal[] Locals
{
get
{
if (_locals == null)
{
_locals = CilDecoder.DecodeLocalSignature(MethodBody, _readers.MdReader, _provider);
}
return _locals;
}
}
/// <summary>
/// Method generic parameters.
/// </summary>
public IEnumerable<string> GenericParameters
{
get
{
if(_genericParameters == null)
{
_genericParameters = CilDecoder.DecodeGenericParameters(_methodDefinition, this);
}
return _genericParameters;
}
}
/// <summary>
/// Method that given an index returns a local.
///
/// Exception:
/// IndexOutOfBoundsException if the index is greater or equal than the number of locals or less to 0.
/// </summary>
/// <param name="index">Index of the local to get</param>
/// <returns>The local in current index.</returns>
public CilLocal GetLocal(int index)
{
if(index < 0 || index >= Locals.Length)
{
throw new IndexOutOfRangeException("Index out of bounds trying to get local");
}
return Locals[index];
}
/// <summary>
/// Method that given an index returns a parameter.
///
/// Exception:
/// IndexOutOfBoundsException if the index is greater or equal than the number of locals or less to 0.
/// </summary>
/// <param name="index">Index of the parameter to get</param>
/// <returns>The local in current index.</returns>
public CilParameter GetParameter(int index)
{
if(index < 0 || index >= Parameters.Length)
{
throw new IndexOutOfRangeException("Index out of bounds trying to get parameter.");
}
return Parameters[index];
}
/// <summary>
/// Method that decodes the method signature as a string with all it's flags, return type, name and parameters.
/// </summary>
/// <returns>Returns the method signature as a string</returns>
public string GetDecodedSignature()
{
string attributes = GetAttributesForSignature();
StringBuilder signature = new StringBuilder();
if (Signature.Header.IsInstance)
{
signature.Append("instance ");
}
signature.Append(Signature.ReturnType);
return String.Format("{0}{1} {2}{3}{4} {5}", attributes, signature.ToString(), Name, GetGenericParametersString(), GetParameterListString(), GetImplementationFlags());
}
/// <summary>
/// Method that formats the Relative Virtual Address to it's hexadecimal representation.
/// </summary>
/// <returns>String representing the Relative virtual Address in hexadecimal</returns>
public string GetFormattedRva()
{
return string.Format("0x{0:x8}", RelativeVirtualAddress);
}
public void Accept(ICilVisitor visitor)
{
visitor.Visit(this);
}
#endregion
#region Private Methods
internal IEnumerable<CilParameter> GetOptionalParameters()
{
for(int i = 0; i<Parameters.Length; i++)
{
var parameter = Parameters[i];
if (parameter.IsOptional && parameter.HasDefault)
{
yield return parameter;
}
}
}
private string GetGenericParametersString()
{
int i = 0;
StringBuilder genericParameters = new StringBuilder();
foreach (var genericParameter in GenericParameters)
{
if (i == 0)
{
genericParameters.Append("<");
}
genericParameters.Append(genericParameter);
genericParameters.Append(",");
i++;
}
if (i > 0)
{
genericParameters.Length -= 1; //Delete trailing ,
genericParameters.Append(">");
}
return genericParameters.ToString();
}
private string GetParameterListString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
for(int i = 0; i < Parameters.Length; i++)
{
if(i > 0)
{
sb.Append(", ");
}
sb.Append(Parameters[i].GetParameterSignature());
}
sb.Append(")");
return sb.ToString();
}
private IEnumerable<CilCustomAttribute> PopulateCustomAttributes()
{
foreach(var handle in _methodDefinition.GetCustomAttributes())
{
var attribute = _readers.MdReader.GetCustomAttribute(handle);
yield return new CilCustomAttribute(attribute, ref _readers);
}
}
private string GetAttributesForSignature()
{
return string.Format("{0}{1}", GetAccessibilityFlags(), GetContractFlags());
}
private string GetContractFlags()
{
StringBuilder sb = new StringBuilder();
if (Attributes.HasFlag(MethodAttributes.HideBySig))
{
sb.Append("hidebysig ");
}
if (Attributes.HasFlag(MethodAttributes.Static))
{
sb.Append("static ");
}
if(Attributes.HasFlag(MethodAttributes.NewSlot))
{
sb.Append("newslot ");
}
if (Attributes.HasFlag(MethodAttributes.SpecialName))
{
sb.Append("specialname ");
}
if (Attributes.HasFlag(MethodAttributes.RTSpecialName))
{
sb.Append("rtspecialname ");
}
if (Attributes.HasFlag(MethodAttributes.Abstract))
{
sb.Append("abstract ");
}
if (Attributes.HasFlag(MethodAttributes.CheckAccessOnOverride))
{
sb.Append("strict ");
}
if (Attributes.HasFlag(MethodAttributes.Virtual))
{
sb.Append("virtual ");
}
if (Attributes.HasFlag(MethodAttributes.Final))
{
sb.Append("final ");
}
if (Attributes.HasFlag(MethodAttributes.PinvokeImpl))
{
sb.Append("pinvokeimpl(");
sb.Append(Import.GetMethodImportDeclaration());
sb.Append(") ");
}
return sb.ToString();
}
/// <summary>
/// This Method is intended to get the accessibility flags.
/// Since the enum doesn't have flags values, the smallest values (private, famANDAssem) will always return true.
/// To solve this we have to check from the greatest through the smallest and the first flag it finds that way we always find the desired value.
/// </summary>
/// <returns>
/// The accesibility flag as a string.
/// </returns>
private string GetAccessibilityFlags()
{
if (Attributes.HasFlag(MethodAttributes.Public))
{
return "public ";
}
if (Attributes.HasFlag(MethodAttributes.FamORAssem))
{
return "famorassem ";
}
if (Attributes.HasFlag(MethodAttributes.Family))
{
return "family ";
}
if (Attributes.HasFlag(MethodAttributes.Assembly))
{
return "assembly ";
}
if (Attributes.HasFlag(MethodAttributes.FamANDAssem))
{
return "famandassem ";
}
if (Attributes.HasFlag(MethodAttributes.Private))
{
return "private ";
}
return string.Empty;
}
private string GetImplementationFlags()
{
return string.Format("{0} {1}", GetCodeType(), GetCodeManagement());
}
private string GetCodeType()
{
if (ImplAttributes.HasFlag(MethodImplAttributes.Runtime))
{
return "runtime";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.OPTIL))
{
return "optil";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.Native))
{
return "native";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.IL))
{
return "cil";
}
throw new BadImageFormatException("Invalid Code Type flag");
}
private string GetCodeManagement()
{
if (ImplAttributes.HasFlag(MethodImplAttributes.Managed))
{
return "managed";
}
if (ImplAttributes.HasFlag(MethodImplAttributes.Unmanaged))
{
return "unmanaged";
}
throw new BadImageFormatException("Invalid code management flag");
}
#endregion
}
}
| |
namespace XenAdmin.Dialogs
{
partial class AddServerDialog
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AddServerDialog));
this.AddButton = new System.Windows.Forms.Button();
this.CancelButton2 = new System.Windows.Forms.Button();
this.ServerNameLabel = new System.Windows.Forms.Label();
this.UsernameLabel = new System.Windows.Forms.Label();
this.PasswordLabel = new System.Windows.Forms.Label();
this.UsernameTextBox = new System.Windows.Forms.TextBox();
this.PasswordTextBox = new System.Windows.Forms.TextBox();
this.ServerNameComboBox = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanelCreds = new System.Windows.Forms.TableLayoutPanel();
this.labelError = new System.Windows.Forms.Label();
this.pictureBoxError = new System.Windows.Forms.PictureBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.comboBoxClouds = new System.Windows.Forms.ComboBox();
this.labelInstructions = new System.Windows.Forms.Label();
this.tableLayoutPanelType = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox1.SuspendLayout();
this.tableLayoutPanelCreds.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
this.tableLayoutPanelType.SuspendLayout();
this.SuspendLayout();
//
// AddButton
//
resources.ApplyResources(this.AddButton, "AddButton");
this.AddButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.AddButton.Name = "AddButton";
this.AddButton.UseVisualStyleBackColor = true;
this.AddButton.Click += new System.EventHandler(this.AddButton_Click);
//
// CancelButton2
//
resources.ApplyResources(this.CancelButton2, "CancelButton2");
this.CancelButton2.CausesValidation = false;
this.CancelButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton2.Name = "CancelButton2";
this.CancelButton2.UseVisualStyleBackColor = true;
this.CancelButton2.Click += new System.EventHandler(this.CancelButton2_Click);
this.CancelButton2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CancelButton2_KeyDown);
//
// ServerNameLabel
//
resources.ApplyResources(this.ServerNameLabel, "ServerNameLabel");
this.ServerNameLabel.Name = "ServerNameLabel";
//
// UsernameLabel
//
resources.ApplyResources(this.UsernameLabel, "UsernameLabel");
this.UsernameLabel.Name = "UsernameLabel";
//
// PasswordLabel
//
resources.ApplyResources(this.PasswordLabel, "PasswordLabel");
this.PasswordLabel.Name = "PasswordLabel";
//
// UsernameTextBox
//
resources.ApplyResources(this.UsernameTextBox, "UsernameTextBox");
this.UsernameTextBox.Name = "UsernameTextBox";
this.UsernameTextBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged);
//
// PasswordTextBox
//
resources.ApplyResources(this.PasswordTextBox, "PasswordTextBox");
this.PasswordTextBox.Name = "PasswordTextBox";
this.PasswordTextBox.UseSystemPasswordChar = true;
this.PasswordTextBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged);
//
// ServerNameComboBox
//
resources.ApplyResources(this.ServerNameComboBox, "ServerNameComboBox");
this.ServerNameComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.ServerNameComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.tableLayoutPanelType.SetColumnSpan(this.ServerNameComboBox, 2);
this.ServerNameComboBox.Name = "ServerNameComboBox";
this.ServerNameComboBox.TextChanged += new System.EventHandler(this.TextFields_TextChanged);
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.tableLayoutPanelType.SetColumnSpan(this.groupBox1, 3);
this.groupBox1.Controls.Add(this.tableLayoutPanelCreds);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// tableLayoutPanelCreds
//
resources.ApplyResources(this.tableLayoutPanelCreds, "tableLayoutPanelCreds");
this.tableLayoutPanelCreds.Controls.Add(this.UsernameLabel, 0, 0);
this.tableLayoutPanelCreds.Controls.Add(this.PasswordLabel, 0, 1);
this.tableLayoutPanelCreds.Controls.Add(this.PasswordTextBox, 1, 1);
this.tableLayoutPanelCreds.Controls.Add(this.UsernameTextBox, 1, 0);
this.tableLayoutPanelCreds.Controls.Add(this.labelError, 1, 2);
this.tableLayoutPanelCreds.Controls.Add(this.pictureBoxError, 0, 2);
this.tableLayoutPanelCreds.Name = "tableLayoutPanelCreds";
//
// labelError
//
resources.ApplyResources(this.labelError, "labelError");
this.labelError.Name = "labelError";
this.labelError.TextChanged += new System.EventHandler(this.labelError_TextChanged);
//
// pictureBoxError
//
resources.ApplyResources(this.pictureBoxError, "pictureBoxError");
this.pictureBoxError.Image = global::XenAdmin.Properties.Resources._000_error_h32bit_16;
this.pictureBoxError.Name = "pictureBoxError";
this.pictureBoxError.TabStop = false;
//
// flowLayoutPanel1
//
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.tableLayoutPanelType.SetColumnSpan(this.flowLayoutPanel1, 3);
this.flowLayoutPanel1.Controls.Add(this.CancelButton2);
this.flowLayoutPanel1.Controls.Add(this.AddButton);
this.flowLayoutPanel1.Controls.Add(this.comboBoxClouds);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// comboBoxClouds
//
this.comboBoxClouds.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.comboBoxClouds, "comboBoxClouds");
this.comboBoxClouds.FormattingEnabled = true;
this.comboBoxClouds.Name = "comboBoxClouds";
//
// labelInstructions
//
resources.ApplyResources(this.labelInstructions, "labelInstructions");
this.tableLayoutPanelType.SetColumnSpan(this.labelInstructions, 3);
this.labelInstructions.Name = "labelInstructions";
//
// tableLayoutPanelType
//
resources.ApplyResources(this.tableLayoutPanelType, "tableLayoutPanelType");
this.tableLayoutPanelType.Controls.Add(this.ServerNameComboBox, 1, 2);
this.tableLayoutPanelType.Controls.Add(this.groupBox1, 0, 3);
this.tableLayoutPanelType.Controls.Add(this.ServerNameLabel, 0, 2);
this.tableLayoutPanelType.Controls.Add(this.labelInstructions, 0, 0);
this.tableLayoutPanelType.Controls.Add(this.flowLayoutPanel1, 0, 4);
this.tableLayoutPanelType.Name = "tableLayoutPanelType";
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// AddServerDialog
//
this.AcceptButton = this.AddButton;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.CancelButton2;
this.Controls.Add(this.tableLayoutPanelType);
this.Name = "AddServerDialog";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.AddServerDialog_FormClosing);
this.Load += new System.EventHandler(this.AddServerDialog_Load);
this.Shown += new System.EventHandler(this.AddServerDialog_Shown);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tableLayoutPanelCreds.ResumeLayout(false);
this.tableLayoutPanelCreds.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxError)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanelType.ResumeLayout(false);
this.tableLayoutPanelType.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
protected System.Windows.Forms.Label ServerNameLabel;
protected System.Windows.Forms.Label UsernameLabel;
protected System.Windows.Forms.Label PasswordLabel;
protected System.Windows.Forms.TextBox UsernameTextBox;
protected System.Windows.Forms.TextBox PasswordTextBox;
protected System.Windows.Forms.ComboBox ServerNameComboBox;
protected System.Windows.Forms.Button CancelButton2;
protected System.Windows.Forms.Button AddButton;
protected System.Windows.Forms.GroupBox groupBox1;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelCreds;
protected System.Windows.Forms.PictureBox pictureBoxError;
protected System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
protected System.Windows.Forms.Label labelError;
protected System.Windows.Forms.Label labelInstructions;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
protected System.Windows.Forms.RadioButton XenServerRadioButton;
protected System.Windows.Forms.TableLayoutPanel tableLayoutPanelType;
private System.Windows.Forms.ComboBox comboBoxClouds;
}
}
| |
// 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gciv = Google.Cloud.Iam.V1;
using gcscv = Google.Cloud.Spanner.Common.V1;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Spanner.Admin.Instance.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedInstanceAdminClientTest
{
[xunit::FactAttribute]
public void GetInstanceConfigRequestObject()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceConfigRequest request = new GetInstanceConfigRequest
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
};
InstanceConfig expectedResponse = new InstanceConfig
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
Replicas = { new ReplicaInfo(), },
LeaderOptions =
{
"leader_optionscedbfd6e",
},
};
mockGrpcClient.Setup(x => x.GetInstanceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceConfig response = client.GetInstanceConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceConfigRequestObjectAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceConfigRequest request = new GetInstanceConfigRequest
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
};
InstanceConfig expectedResponse = new InstanceConfig
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
Replicas = { new ReplicaInfo(), },
LeaderOptions =
{
"leader_optionscedbfd6e",
},
};
mockGrpcClient.Setup(x => x.GetInstanceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceConfig responseCallSettings = await client.GetInstanceConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InstanceConfig responseCancellationToken = await client.GetInstanceConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceConfig()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceConfigRequest request = new GetInstanceConfigRequest
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
};
InstanceConfig expectedResponse = new InstanceConfig
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
Replicas = { new ReplicaInfo(), },
LeaderOptions =
{
"leader_optionscedbfd6e",
},
};
mockGrpcClient.Setup(x => x.GetInstanceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceConfig response = client.GetInstanceConfig(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceConfigAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceConfigRequest request = new GetInstanceConfigRequest
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
};
InstanceConfig expectedResponse = new InstanceConfig
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
Replicas = { new ReplicaInfo(), },
LeaderOptions =
{
"leader_optionscedbfd6e",
},
};
mockGrpcClient.Setup(x => x.GetInstanceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceConfig responseCallSettings = await client.GetInstanceConfigAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InstanceConfig responseCancellationToken = await client.GetInstanceConfigAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceConfigResourceNames()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceConfigRequest request = new GetInstanceConfigRequest
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
};
InstanceConfig expectedResponse = new InstanceConfig
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
Replicas = { new ReplicaInfo(), },
LeaderOptions =
{
"leader_optionscedbfd6e",
},
};
mockGrpcClient.Setup(x => x.GetInstanceConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceConfig response = client.GetInstanceConfig(request.InstanceConfigName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceConfigResourceNamesAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceConfigRequest request = new GetInstanceConfigRequest
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
};
InstanceConfig expectedResponse = new InstanceConfig
{
InstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
Replicas = { new ReplicaInfo(), },
LeaderOptions =
{
"leader_optionscedbfd6e",
},
};
mockGrpcClient.Setup(x => x.GetInstanceConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceConfig responseCallSettings = await client.GetInstanceConfigAsync(request.InstanceConfigName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InstanceConfig responseCancellationToken = await client.GetInstanceConfigAsync(request.InstanceConfigName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceRequestObject()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
FieldMask = new wkt::FieldMask(),
};
Instance expectedResponse = new Instance
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
NodeCount = -1659500730,
State = Instance.Types.State.Unspecified,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EndpointUris =
{
"endpoint_uris93f83605",
},
ProcessingUnits = 759326966,
};
mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceRequestObjectAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
FieldMask = new wkt::FieldMask(),
};
Instance expectedResponse = new Instance
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
NodeCount = -1659500730,
State = Instance.Types.State.Unspecified,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EndpointUris =
{
"endpoint_uris93f83605",
},
ProcessingUnits = 759326966,
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance responseCallSettings = await client.GetInstanceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Instance responseCancellationToken = await client.GetInstanceAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstance()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
NodeCount = -1659500730,
State = Instance.Types.State.Unspecified,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EndpointUris =
{
"endpoint_uris93f83605",
},
ProcessingUnits = 759326966,
};
mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
NodeCount = -1659500730,
State = Instance.Types.State.Unspecified,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EndpointUris =
{
"endpoint_uris93f83605",
},
ProcessingUnits = 759326966,
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance responseCallSettings = await client.GetInstanceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Instance responseCancellationToken = await client.GetInstanceAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetInstanceResourceNames()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
NodeCount = -1659500730,
State = Instance.Types.State.Unspecified,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EndpointUris =
{
"endpoint_uris93f83605",
},
ProcessingUnits = 759326966,
};
mockGrpcClient.Setup(x => x.GetInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request.InstanceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetInstanceResourceNamesAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig("[PROJECT]", "[INSTANCE_CONFIG]"),
DisplayName = "display_name137f65c2",
NodeCount = -1659500730,
State = Instance.Types.State.Unspecified,
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EndpointUris =
{
"endpoint_uris93f83605",
},
ProcessingUnits = 759326966,
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance responseCallSettings = await client.GetInstanceAsync(request.InstanceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Instance responseCancellationToken = await client.GetInstanceAsync(request.InstanceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteInstanceRequestObject()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteInstance(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteInstanceRequestObjectAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteInstanceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteInstanceAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteInstance()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteInstance(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteInstanceAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteInstanceAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteInstanceAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteInstanceResourceNames()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteInstance(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteInstance(request.InstanceName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteInstanceResourceNamesAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = gcscv::InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteInstanceAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteInstanceAsync(request.InstanceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteInstanceAsync(request.InstanceName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyResourceNames()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyResourceNamesAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyResourceNames()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyResourceNamesAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsResourceNames()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsResourceNamesAsync()
{
moq::Mock<InstanceAdmin.InstanceAdminClient> mockGrpcClient = new moq::Mock<InstanceAdmin.InstanceAdminClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceAdminClient client = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.IO
{
public partial class FileStream : Stream
{
private const FileShare DefaultShare = FileShare.Read;
private const bool DefaultIsAsync = false;
internal const int DefaultBufferSize = 4096;
private byte[] _buffer;
private int _bufferLength;
private readonly SafeFileHandle _fileHandle;
/// <summary>Whether the file is opened for reading, writing, or both.</summary>
private readonly FileAccess _access;
/// <summary>The path to the opened file.</summary>
private readonly string _path;
/// <summary>The next available byte to be read from the _buffer.</summary>
private int _readPos;
/// <summary>The number of valid bytes in _buffer.</summary>
private int _readLength;
/// <summary>The next location in which a write should occur to the buffer.</summary>
private int _writePos;
/// <summary>
/// Whether asynchronous read/write/flush operations should be performed using async I/O.
/// On Windows FileOptions.Asynchronous controls how the file handle is configured,
/// and then as a result how operations are issued against that file handle. On Unix,
/// there isn't any distinction around how file descriptors are created for async vs
/// sync, but we still differentiate how the operations are issued in order to provide
/// similar behavioral semantics and performance characteristics as on Windows. On
/// Windows, if non-async, async read/write requests just delegate to the base stream,
/// and no attempt is made to synchronize between sync and async operations on the stream;
/// if async, then async read/write requests are implemented specially, and sync read/write
/// requests are coordinated with async ones by implementing the sync ones over the async
/// ones. On Unix, we do something similar. If non-async, async read/write requests just
/// delegate to the base stream, and no attempt is made to synchronize. If async, we use
/// a semaphore to coordinate both sync and async operations.
/// </summary>
private readonly bool _useAsyncIO;
/// <summary>cached task for read ops that complete synchronously</summary>
private Task<int> _lastSynchronouslyCompletedTask = null;
/// <summary>
/// Currently cached position in the stream. This should always mirror the underlying file's actual position,
/// and should only ever be out of sync if another stream with access to this same file manipulates it, at which
/// point we attempt to error out.
/// </summary>
private long _filePosition;
/// <summary>Whether the file stream's handle has been exposed.</summary>
private bool _exposedHandle;
[Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, FileAccess access)
: this(handle, access, true, DefaultBufferSize, false)
{
}
[Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, FileAccess access, bool ownsHandle)
: this(handle, access, ownsHandle, DefaultBufferSize, false)
{
}
[Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
: this(handle, access, ownsHandle, bufferSize, false)
{
}
[Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
{
SafeFileHandle safeHandle = new SafeFileHandle(handle, ownsHandle: ownsHandle);
try
{
ValidateAndInitFromHandle(safeHandle, access, bufferSize, isAsync);
}
catch
{
// We don't want to take ownership of closing passed in handles
// *unless* the constructor completes successfully.
GC.SuppressFinalize(safeHandle);
// This would also prevent Close from being called, but is unnecessary
// as we've removed the object from the finalizer queue.
//
// safeHandle.SetHandleAsInvalid();
throw;
}
// Note: Cleaner to set the following fields in ValidateAndInitFromHandle,
// but we can't as they're readonly.
_access = access;
_useAsyncIO = isAsync;
// As the handle was passed in, we must set the handle field at the very end to
// avoid the finalizer closing the handle when we throw errors.
_fileHandle = safeHandle;
}
public FileStream(SafeFileHandle handle, FileAccess access)
: this(handle, access, DefaultBufferSize)
{
}
public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize)
: this(handle, access, bufferSize, GetDefaultIsAsync(handle))
{
}
private void ValidateAndInitFromHandle(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
{
if (handle.IsInvalid)
throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
if (handle.IsClosed)
throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed);
if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.Value)
throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle));
_exposedHandle = true;
_bufferLength = bufferSize;
InitFromHandle(handle, access, isAsync);
}
public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
{
ValidateAndInitFromHandle(handle, access, bufferSize, isAsync);
// Note: Cleaner to set the following fields in ValidateAndInitFromHandle,
// but we can't as they're readonly.
_access = access;
_useAsyncIO = isAsync;
// As the handle was passed in, we must set the handle field at the very end to
// avoid the finalizer closing the handle when we throw errors.
_fileHandle = handle;
}
public FileStream(string path, FileMode mode) :
this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultIsAsync)
{ }
public FileStream(string path, FileMode mode, FileAccess access) :
this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync)
{ }
public FileStream(string path, FileMode mode, FileAccess access, FileShare share) :
this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync)
{ }
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) :
this(path, mode, access, share, bufferSize, DefaultIsAsync)
{ }
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) :
this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
{ }
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
if (path == null)
throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
// don't include inheritable in our bounds check for share
FileShare tempshare = share & ~FileShare.Inheritable;
string badArg = null;
if (mode < FileMode.CreateNew || mode > FileMode.Append)
badArg = nameof(mode);
else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
badArg = nameof(access);
else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
badArg = nameof(share);
if (badArg != null)
throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);
// NOTE: any change to FileOptions enum needs to be matched here in the error validation
if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum);
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
// Write access validation
if ((access & FileAccess.Write) == 0)
{
if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
{
// No write access, mode and access disagree but flag access since mode comes first
throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access));
}
}
if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access));
string fullPath = Path.GetFullPath(path);
_path = fullPath;
_access = access;
_bufferLength = bufferSize;
if ((options & FileOptions.Asynchronous) != 0)
_useAsyncIO = true;
_fileHandle = OpenHandle(mode, share, options);
try
{
Init(mode, share);
}
catch
{
// If anything goes wrong while setting up the stream, make sure we deterministically dispose
// of the opened handle.
_fileHandle.Dispose();
_fileHandle = null;
throw;
}
}
private static bool GetDefaultIsAsync(SafeFileHandle handle)
{
// This will eventually get more complicated as we can actually check the underlying handle type on Windows
return handle.IsAsync.HasValue ? handle.IsAsync.Value : false;
}
[Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } }
public virtual void Lock(long position, long length)
{
if (position < 0 || length < 0)
{
throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
LockInternal(position, length);
}
public virtual void Unlock(long position, long length)
{
if (position < 0 || length < 0)
{
throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
UnlockInternal(position, length);
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overridden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (GetType() != typeof(FileStream))
return base.FlushAsync(cancellationToken);
return FlushAsyncInternal(cancellationToken);
}
public override int Read(byte[] array, int offset, int count)
{
ValidateReadWriteArgs(array, offset, count);
return _useAsyncIO ?
ReadAsyncTask(array, offset, count, CancellationToken.None).GetAwaiter().GetResult() :
ReadSpan(new Span<byte>(array, offset, count));
}
public override int Read(Span<byte> destination)
{
if (GetType() == typeof(FileStream) && !_useAsyncIO)
{
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
return ReadSpan(destination);
}
else
{
// This type is derived from FileStream and/or the stream is in async mode. If this is a
// derived type, it may have overridden Read(byte[], int, int) prior to this Read(Span<byte>)
// overload being introduced. In that case, this Read(Span<byte>) overload should use the behavior
// of Read(byte[],int,int) overload. Or if the stream is in async mode, we can't call the
// synchronous ReadSpan, so we similarly call the base Read, which will turn delegate to
// Read(byte[],int,int), which will do the right thing if we're in async mode.
return base.Read(destination);
}
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/ReadAsync) when we are not sure.
// Similarly, if we weren't opened for asynchronous I/O, call to the base implementation so that
// Read is invoked asynchronously.
if (GetType() != typeof(FileStream) || !_useAsyncIO)
return base.ReadAsync(buffer, offset, count, cancellationToken);
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
if (IsClosed)
throw Error.GetFileNotOpen();
return ReadAsyncTask(buffer, offset, count, cancellationToken);
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_useAsyncIO || GetType() != typeof(FileStream))
{
// If we're not using async I/O, delegate to the base, which will queue a call to Read.
// Or if this isn't a concrete FileStream, a derived type may have overridden ReadAsync(byte[],...),
// which was introduced first, so delegate to the base which will delegate to that.
return base.ReadAsync(destination, cancellationToken);
}
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
if (IsClosed)
{
throw Error.GetFileNotOpen();
}
Task<int> t = ReadAsyncInternal(destination, cancellationToken, out int synchronousResult);
return t != null ?
new ValueTask<int>(t) :
new ValueTask<int>(synchronousResult);
}
private Task<int> ReadAsyncTask(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
Task<int> t = ReadAsyncInternal(new Memory<byte>(array, offset, count), cancellationToken, out int synchronousResult);
if (t == null)
{
t = _lastSynchronouslyCompletedTask;
Debug.Assert(t == null || t.IsCompletedSuccessfully, "Cached task should have completed successfully");
if (t == null || t.Result != synchronousResult)
{
_lastSynchronouslyCompletedTask = t = Task.FromResult(synchronousResult);
}
}
return t;
}
public override void Write(byte[] array, int offset, int count)
{
ValidateReadWriteArgs(array, offset, count);
if (_useAsyncIO)
{
WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, count), CancellationToken.None).GetAwaiter().GetResult();
}
else
{
WriteSpan(new ReadOnlySpan<byte>(array, offset, count));
}
}
public override void Write(ReadOnlySpan<byte> destination)
{
if (GetType() == typeof(FileStream) && !_useAsyncIO)
{
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
WriteSpan(destination);
}
else
{
// This type is derived from FileStream and/or the stream is in async mode. If this is a
// derived type, it may have overridden Write(byte[], int, int) prior to this Write(ReadOnlySpan<byte>)
// overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload should use the behavior
// of Write(byte[],int,int) overload. Or if the stream is in async mode, we can't call the
// synchronous WriteSpan, so we similarly call the base Write, which will turn delegate to
// Write(byte[],int,int), which will do the right thing if we're in async mode.
base.Write(destination);
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() or WriteAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write/WriteAsync) when we are not sure.
if (!_useAsyncIO || GetType() != typeof(FileStream))
return base.WriteAsync(buffer, offset, count, cancellationToken);
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
if (IsClosed)
throw Error.GetFileNotOpen();
return WriteAsyncInternal(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
}
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_useAsyncIO || GetType() != typeof(FileStream))
{
// If we're not using async I/O, delegate to the base, which will queue a call to Write.
// Or if this isn't a concrete FileStream, a derived type may have overridden WriteAsync(byte[],...),
// which was introduced first, so delegate to the base which will delegate to that.
return base.WriteAsync(source, cancellationToken);
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
if (IsClosed)
{
throw Error.GetFileNotOpen();
}
return WriteAsyncInternal(source, cancellationToken);
}
/// <summary>
/// Clears buffers for this stream and causes any buffered data to be written to the file.
/// </summary>
public override void Flush()
{
// Make sure that we call through the public virtual API
Flush(flushToDisk: false);
}
/// <summary>
/// Clears buffers for this stream, and if <param name="flushToDisk"/> is true,
/// causes any buffered data to be written to the file.
/// </summary>
public virtual void Flush(bool flushToDisk)
{
if (IsClosed) throw Error.GetFileNotOpen();
FlushInternalBuffer();
if (flushToDisk && CanWrite)
{
FlushOSBuffer();
}
}
/// <summary>Gets a value indicating whether the current stream supports reading.</summary>
public override bool CanRead
{
get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; }
}
/// <summary>Gets a value indicating whether the current stream supports writing.</summary>
public override bool CanWrite
{
get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; }
}
/// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary>
/// <param name="array">The buffer to read from or write to.</param>
/// <param name="offset">The zero-based offset into the array.</param>
/// <param name="count">The maximum number of bytes to read or write.</param>
private void ValidateReadWriteArgs(byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
}
/// <summary>Sets the length of this stream to the given value.</summary>
/// <param name="value">The new length of the stream.</param>
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
if (!CanSeek)
throw Error.GetSeekNotSupported();
if (!CanWrite)
throw Error.GetWriteNotSupported();
SetLengthInternal(value);
}
public virtual SafeFileHandle SafeFileHandle
{
get
{
Flush();
_exposedHandle = true;
return _fileHandle;
}
}
/// <summary>Gets the path that was passed to the constructor.</summary>
public virtual string Name { get { return _path ?? SR.IO_UnknownFileName; } }
/// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary>
public virtual bool IsAsync
{
get { return _useAsyncIO; }
}
/// <summary>Gets the length of the stream in bytes.</summary>
public override long Length
{
get
{
if (_fileHandle.IsClosed) throw Error.GetFileNotOpen();
if (!CanSeek) throw Error.GetSeekNotSupported();
return GetLengthInternal();
}
}
/// <summary>
/// Verify that the actual position of the OS's handle equals what we expect it to.
/// This will fail if someone else moved the UnixFileStream's handle or if
/// our position updating code is incorrect.
/// </summary>
private void VerifyOSHandlePosition()
{
bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it
#if DEBUG
verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be
#endif
if (verifyPosition && CanSeek)
{
long oldPos = _filePosition; // SeekCore will override the current _position, so save it now
long curPos = SeekCore(_fileHandle, 0, SeekOrigin.Current);
if (oldPos != curPos)
{
// For reads, this is non-fatal but we still could have returned corrupted
// data in some cases, so discard the internal buffer. For writes,
// this is a problem; discard the buffer and error out.
_readPos = _readLength = 0;
if (_writePos > 0)
{
_writePos = 0;
throw new IOException(SR.IO_FileStreamHandlePosition);
}
}
}
}
/// <summary>Verifies that state relating to the read/write buffer is consistent.</summary>
[Conditional("DEBUG")]
private void AssertBufferInvariants()
{
// Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength
Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength);
// Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength
Debug.Assert(0 <= _writePos && _writePos <= _bufferLength);
// Read buffering and write buffering can't both be active
Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0);
}
/// <summary>Validates that we're ready to read from the stream.</summary>
private void PrepareForReading()
{
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
if (_readLength == 0 && !CanRead)
throw Error.GetReadNotSupported();
AssertBufferInvariants();
}
/// <summary>Gets or sets the position within the current stream</summary>
public override long Position
{
get
{
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
if (!CanSeek)
throw Error.GetSeekNotSupported();
AssertBufferInvariants();
VerifyOSHandlePosition();
// We may have read data into our buffer from the handle, such that the handle position
// is artificially further along than the consumer's view of the stream's position.
// Thus, when reading, our position is really starting from the handle position negatively
// offset by the number of bytes in the buffer and positively offset by the number of
// bytes into that buffer we've read. When writing, both the read length and position
// must be zero, and our position is just the handle position offset positive by how many
// bytes we've written into the buffer.
return (_filePosition - _readLength) + _readPos + _writePos;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Seek(value, SeekOrigin.Begin);
}
}
internal virtual bool IsClosed => _fileHandle.IsClosed;
/// <summary>
/// Gets the array used for buffering reading and writing.
/// If the array hasn't been allocated, this will lazily allocate it.
/// </summary>
/// <returns>The buffer.</returns>
private byte[] GetBuffer()
{
Debug.Assert(_buffer == null || _buffer.Length == _bufferLength);
if (_buffer == null)
{
_buffer = new byte[_bufferLength];
OnBufferAllocated();
}
return _buffer;
}
partial void OnBufferAllocated();
/// <summary>
/// Flushes the internal read/write buffer for this stream. If write data has been buffered,
/// that data is written out to the underlying file. Or if data has been buffered for
/// reading from the stream, the data is dumped and our position in the underlying file
/// is rewound as necessary. This does not flush the OS buffer.
/// </summary>
private void FlushInternalBuffer()
{
AssertBufferInvariants();
if (_writePos > 0)
{
FlushWriteBuffer();
}
else if (_readPos < _readLength && CanSeek)
{
FlushReadBuffer();
}
}
/// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary>
private void FlushReadBuffer()
{
// Reading is done by blocks from the file, but someone could read
// 1 byte from the buffer then write. At that point, the OS's file
// pointer is out of sync with the stream's position. All write
// functions should call this function to preserve the position in the file.
AssertBufferInvariants();
Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!");
int rewind = _readPos - _readLength;
if (rewind != 0)
{
Debug.Assert(CanSeek, "FileStream will lose buffered read data now.");
SeekCore(_fileHandle, rewind, SeekOrigin.Current);
}
_readPos = _readLength = 0;
}
/// <summary>
/// Reads a byte from the file stream. Returns the byte cast to an int
/// or -1 if reading from the end of the stream.
/// </summary>
public override int ReadByte()
{
PrepareForReading();
byte[] buffer = GetBuffer();
if (_readPos == _readLength)
{
FlushWriteBuffer();
_readLength = FillReadBufferForReadByte();
_readPos = 0;
if (_readLength == 0)
{
return -1;
}
}
return buffer[_readPos++];
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position
/// within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
public override void WriteByte(byte value)
{
PrepareForWriting();
// Flush the write buffer if it's full
if (_writePos == _bufferLength)
FlushWriteBufferForWriteByte();
// We now have space in the buffer. Store the byte.
GetBuffer()[_writePos++] = value;
}
/// <summary>
/// Validates that we're ready to write to the stream,
/// including flushing a read buffer if necessary.
/// </summary>
private void PrepareForWriting()
{
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
// Make sure we're good to write. We only need to do this if there's nothing already
// in our write buffer, since if there is something in the buffer, we've already done
// this checking and flushing.
if (_writePos == 0)
{
if (!CanWrite) throw Error.GetWriteNotSupported();
FlushReadBuffer();
Debug.Assert(_bufferLength > 0, "_bufferSize > 0");
}
}
~FileStream()
{
// Preserved for compatibility since FileStream has defined a
// finalizer in past releases and derived classes may depend
// on Dispose(false) call.
Dispose(false);
}
public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object state)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (numBytes < 0)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - offset < numBytes)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed);
if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream);
if (!IsAsync)
return base.BeginRead(array, offset, numBytes, callback, state);
else
return TaskToApm.Begin(ReadAsyncTask(array, offset, numBytes, CancellationToken.None), callback, state);
}
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object state)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (numBytes < 0)
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - offset < numBytes)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed);
if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream);
if (!IsAsync)
return base.BeginWrite(array, offset, numBytes, callback, state);
else
return TaskToApm.Begin(WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, numBytes), CancellationToken.None), callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
if (!IsAsync)
return base.EndRead(asyncResult);
else
return TaskToApm.End<int>(asyncResult);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
if (!IsAsync)
base.EndWrite(asyncResult);
else
TaskToApm.End(asyncResult);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_FSSHTTP_FSSHTTPB
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.SharedAdapter;
using Microsoft.Protocols.TestSuites.SharedTestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// A class which contains test cases used to verify the schema lock sub request operation.
/// </summary>
[TestClass]
public sealed class MS_FSSHTTP_FSSHTTPB_S03_SchemaLock : S03_SchemaLock
{
#region Test Suite Initialization and clean up
/// <summary>
/// Class initialization
/// </summary>
/// <param name="testContext">The context of the test suite.</param>
[ClassInitialize]
public static new void ClassInitialize(TestContext testContext)
{
S03_SchemaLock.ClassInitialize(testContext);
}
/// <summary>
/// Class clean up
/// </summary>
[ClassCleanup]
public static new void ClassCleanup()
{
S03_SchemaLock.ClassCleanup();
}
#endregion
/// <summary>
/// A method used to verify the related requirements when get a schema lock on a file which is not existent.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S03_TC01_GetLock_FileNotExistsOrCannotBeCreated()
{
// Get a schema lock with a nonexistent file, expect the server returns the error code "FileNotExistsOrCannotBeCreated".
string fileUrlNotExit = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site);
// Initialize the service
this.InitializeContext(fileUrlNotExit, this.UserName01, this.Password01, this.Domain);
SchemaLockSubRequestType subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequest(SchemaLockRequestTypes.GetLock, false, null);
CellStorageResponse response = Adapter.CellStorageRequest(fileUrlNotExit, new SubRequestType[] { subRequest });
SchemaLockSubResponseType schemaLockSubResponse = SharedTestSuiteHelper.ExtractSubResponse<SchemaLockSubResponseType>(response, 0, 0, this.Site);
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1913
Site.CaptureRequirementIfAreEqual<ErrorCodeType>(
ErrorCodeType.FileNotExistsOrCannotBeCreated,
SharedTestSuiteHelper.ConvertToErrorCodeType(schemaLockSubResponse.ErrorCode, this.Site),
"MS-FSSHTTP",
1913,
@"[In SchemaLock Subrequest][The protocol server returns results based on the following conditions:] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""FileNotExistsOrCannotBeCreated"" in the ErrorCode attribute sent back in the SubResponse element.");
}
else
{
Site.Assert.AreEqual<ErrorCodeType>(
ErrorCodeType.FileNotExistsOrCannotBeCreated,
SharedTestSuiteHelper.ConvertToErrorCodeType(schemaLockSubResponse.ErrorCode, this.Site),
@"[In SchemaLock Subrequest][The protocol server returns results based on the following conditions:] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""FileNotExistsOrCannotBeCreated"" in the ErrorCode attribute sent back in the SubResponse element.");
}
}
/// <summary>
/// A method used to verify the related requirements when the URL attribute of the corresponding Request element doesn't exist.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S03_TC02_GetLock_UrlNotSpecified()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Create a GetLock subRequest with all valid parameters.
SchemaLockSubRequestType subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequestForGetLock(null);
CellStorageResponse response = new CellStorageResponse();
bool isR3006Verified = false;
try
{
// Send a GetLock for schema lock subRequest to the protocol server without specifying URL attribute.
response = this.Adapter.CellStorageRequest(null, new SubRequestType[] { subRequest });
}
catch (System.Xml.XmlException exception)
{
string message = exception.Message;
isR3006Verified = message.Contains("Duplicate attribute");
isR3006Verified &= message.Contains("ErrorCode");
}
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3006
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists.");
Site.CaptureRequirementIfIsTrue(
isR3006Verified,
"MS-FSSHTTP",
3006,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element.");
}
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3007
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site))
{
Site.CaptureRequirementIfIsNull(
response.ResponseCollection,
"MS-FSSHTTP",
3007,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
else
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists.");
Site.Assert.IsTrue(
isR3006Verified,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists.");
}
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site))
{
Site.Assert.IsNull(
response.ResponseCollection,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
}
/// <summary>
/// A method used to verify the related requirements when the URL attribute of the corresponding Request element doesn't exist.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S03_TC03_GetLock_UrlEmpty()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Create a GetLock subRequest with all valid parameters.
SchemaLockSubRequestType subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequestForGetLock(null);
CellStorageResponse response = new CellStorageResponse();
bool isR3008Verified = false;
try
{
// Send a GetLock for schema lock subRequest to the protocol server without specifying URL attribute.
response = this.Adapter.CellStorageRequest(string.Empty, new SubRequestType[] { subRequest });
}
catch (System.Xml.XmlException exception)
{
string message = exception.Message;
isR3008Verified = message.Contains("Duplicate attribute");
isR3008Verified &= message.Contains("ErrorCode");
}
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3008
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is empty string.");
Site.CaptureRequirementIfIsTrue(
isR3008Verified,
"MS-FSSHTTP",
3008,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element.");
}
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3009
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site))
{
Site.CaptureRequirementIfIsNull(
response.ResponseCollection,
"MS-FSSHTTP",
3009,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <11> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
else
{
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site))
{
Site.Log.Add(
LogEntryKind.Debug,
"SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is empty string.");
Site.Assert.IsTrue(
isR3008Verified,
"[In Appendix B: Product Behavior] If the URL attribute of the corresponding Request element is an empty string, the implementation does return two ErrorCode attributes in Response element. <3> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element.");
}
if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site))
{
Site.Assert.IsNull(
response.ResponseCollection,
@"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element.");
}
}
}
/// <summary>
/// A method used to verify the related requirements when getting a schema Lock on a file which is already checked out.
/// </summary>
[TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()]
public void MSFSSHTTP_FSSHTTPB_S03_TC04_GetLock_Success_ExclusiveLockReturnReason_CheckedOutByCurrentUser()
{
// Initialize the service
this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
// Check out one file by a specified user name.
bool isCheckOutSuccess = SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
Site.Assert.AreEqual(true, isCheckOutSuccess, "Cannot change the file {0} to check out status using the user name {1} and password{2}", this.DefaultFileUrl, this.UserName01, this.Password01);
this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain);
CheckLockAvailability();
// Get a schema lock with AllowFallbackToExclusive set to true, expect the server returns the error code "Success".
SchemaLockSubRequestType subRequest = SharedTestSuiteHelper.CreateSchemaLockSubRequest(SchemaLockRequestTypes.GetLock, true, null);
CellStorageResponse response = Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest });
SchemaLockSubResponseType schemaLockSubResponse = SharedTestSuiteHelper.ExtractSubResponse<SchemaLockSubResponseType>(response, 0, 0, this.Site);
this.Site.Assert.AreEqual<ErrorCodeType>(ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(schemaLockSubResponse.ErrorCode, this.Site), "The test case cannot continue unless the server responses Success when the user get a schema lock with AllowFallBack attribute true on an already checked out file by the same account.");
this.StatusManager.RecordExclusiveLock(this.DefaultFileUrl, subRequest.SubRequestData.ExclusiveLockID);
#region Verify related requirements
if (SharedContext.Current.IsMsFsshttpRequirementsCaptured)
{
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R404
Site.CaptureRequirementIfAreEqual<string>(
"ExclusiveLock",
schemaLockSubResponse.SubResponseData.LockType,
"MS-FSSHTTP",
404,
@"[In LockTypes] ExclusiveLock: The string value ""ExclusiveLock"", indicating an exclusive lock on the file.");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R406
Site.CaptureRequirementIfAreEqual<string>(
"ExclusiveLock",
schemaLockSubResponse.SubResponseData.LockType,
"MS-FSSHTTP",
406,
@"[In LockTypes][ExclusiveLock or 2] In a cell storage service response message, an exclusive lock indicates that an exclusive lock is granted to the current client for that specific file.");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1428
this.Site.Log.Add(
LogEntryKind.Debug,
"For MS-FSSHTTP_R1428 and MS-FSSHTTP_R717, the ExclusiveLockReturnReason attribute in the response should be specified, actually it is {0}.",
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReasonSpecified ? "specified" : "not specified");
Site.CaptureRequirementIfIsTrue(
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReasonSpecified,
"MS-FSSHTTP",
1428,
@"[In SubResponseDataOptionalAttributes][ExclusiveLockReturnReason] The ExclusiveLockReturnReason attribute MUST be specified in a subresponse that is generated in response to one of the following types of cell storage service subrequest operations when the LockType attribute in the subresponse is set to ""ExclusiveLock"": A schema lock subrequest of type ""Get lock"".");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R717
Site.CaptureRequirementIfIsTrue(
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReasonSpecified,
"MS-FSSHTTP",
717,
@"[In SchemaLockSubResponseDataType] The ExclusiveLockReturnReason attribute MUST be specified in a schema lock subresponse that is generated in response to a schema lock subrequest of type ""Get lock"" when the LockType attribute in the subresponse is set to ""ExclusiveLock"".");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R715
Site.CaptureRequirementIfAreEqual<ExclusiveLockReturnReasonTypes>(
ExclusiveLockReturnReasonTypes.CheckedOutByCurrentUser,
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReason,
"MS-FSSHTTP",
715,
@"[In SchemaLockSubResponseDataType] ExclusiveLockReturnReason: An ExclusiveLockReturnReasonTypes that specifies the reason why an exclusive lock is granted in a schema lock subresponse.");
// Verify MS-FSSHTTP requirement: MS-FSSHTTP_R350
Site.CaptureRequirementIfAreEqual<ExclusiveLockReturnReasonTypes>(
ExclusiveLockReturnReasonTypes.CheckedOutByCurrentUser,
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReason,
"MS-FSSHTTP",
350,
@"[In ExclusiveLockReturnReasonTypes] CheckedOutByCurrentUser: The string value ""CheckedOutByCurrentUser"", indicating that an exclusive lock is granted on the file because the file is checked out by the current user who sent the cell storage service request message.");
}
else
{
Site.Assert.AreEqual<string>(
"ExclusiveLock",
schemaLockSubResponse.SubResponseData.LockType,
@"[In LockTypes] ExclusiveLock: The string value ""ExclusiveLock"", indicating an exclusive lock on the file.");
Site.Assert.IsTrue(
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReasonSpecified,
@"[In SubResponseDataOptionalAttributes][ExclusiveLockReturnReason] The ExclusiveLockReturnReason attribute MUST be specified in a subresponse that is generated in response to one of the following types of cell storage service subrequest operations when the LockType attribute in the subresponse is set to ""ExclusiveLock"": A schema lock subrequest of type ""Get lock"".");
Site.Assert.AreEqual<ExclusiveLockReturnReasonTypes>(
ExclusiveLockReturnReasonTypes.CheckedOutByCurrentUser,
schemaLockSubResponse.SubResponseData.ExclusiveLockReturnReason,
@"[In SchemaLockSubResponseDataType] ExclusiveLockReturnReason: An ExclusiveLockReturnReasonTypes that specifies the reason why an exclusive lock is granted in a schema lock subresponse.");
}
#endregion
}
/// <summary>
/// Initialize the shared context based on the specified request file URL, user name, password and domain for the MS-FSSHTTP test purpose.
/// </summary>
/// <param name="requestFileUrl">Specify the request file URL.</param>
/// <param name="userName">Specify the user name.</param>
/// <param name="password">Specify the password.</param>
/// <param name="domain">Specify the domain.</param>
protected override void InitializeContext(string requestFileUrl, string userName, string password, string domain)
{
SharedContextUtils.InitializeSharedContextForFSSHTTP(userName, password, domain, this.Site);
}
/// <summary>
/// Merge the common configuration and should/may configuration file.
/// </summary>
/// <param name="site">An instance of interface ITestSite which provides logging, assertions,
/// and adapters for test code onto its execution context.</param>
protected override void MergeConfigurationFile(TestTools.ITestSite site)
{
ConfigurationFileHelper.MergeConfigurationFile(site);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A physical USB device
/// First published in XenServer 7.3.
/// </summary>
public partial class PUSB : XenObject<PUSB>
{
#region Constructors
public PUSB()
{
}
public PUSB(string uuid,
XenRef<USB_group> USB_group,
XenRef<Host> host,
string path,
string vendor_id,
string vendor_desc,
string product_id,
string product_desc,
string serial,
string version,
string description,
bool passthrough_enabled,
Dictionary<string, string> other_config,
double speed)
{
this.uuid = uuid;
this.USB_group = USB_group;
this.host = host;
this.path = path;
this.vendor_id = vendor_id;
this.vendor_desc = vendor_desc;
this.product_id = product_id;
this.product_desc = product_desc;
this.serial = serial;
this.version = version;
this.description = description;
this.passthrough_enabled = passthrough_enabled;
this.other_config = other_config;
this.speed = speed;
}
/// <summary>
/// Creates a new PUSB from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public PUSB(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new PUSB from a Proxy_PUSB.
/// </summary>
/// <param name="proxy"></param>
public PUSB(Proxy_PUSB proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given PUSB.
/// </summary>
public override void UpdateFrom(PUSB record)
{
uuid = record.uuid;
USB_group = record.USB_group;
host = record.host;
path = record.path;
vendor_id = record.vendor_id;
vendor_desc = record.vendor_desc;
product_id = record.product_id;
product_desc = record.product_desc;
serial = record.serial;
version = record.version;
description = record.description;
passthrough_enabled = record.passthrough_enabled;
other_config = record.other_config;
speed = record.speed;
}
internal void UpdateFrom(Proxy_PUSB proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
USB_group = proxy.USB_group == null ? null : XenRef<USB_group>.Create(proxy.USB_group);
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
path = proxy.path == null ? null : proxy.path;
vendor_id = proxy.vendor_id == null ? null : proxy.vendor_id;
vendor_desc = proxy.vendor_desc == null ? null : proxy.vendor_desc;
product_id = proxy.product_id == null ? null : proxy.product_id;
product_desc = proxy.product_desc == null ? null : proxy.product_desc;
serial = proxy.serial == null ? null : proxy.serial;
version = proxy.version == null ? null : proxy.version;
description = proxy.description == null ? null : proxy.description;
passthrough_enabled = (bool)proxy.passthrough_enabled;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
speed = Convert.ToDouble(proxy.speed);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this PUSB
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("USB_group"))
USB_group = Marshalling.ParseRef<USB_group>(table, "USB_group");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("path"))
path = Marshalling.ParseString(table, "path");
if (table.ContainsKey("vendor_id"))
vendor_id = Marshalling.ParseString(table, "vendor_id");
if (table.ContainsKey("vendor_desc"))
vendor_desc = Marshalling.ParseString(table, "vendor_desc");
if (table.ContainsKey("product_id"))
product_id = Marshalling.ParseString(table, "product_id");
if (table.ContainsKey("product_desc"))
product_desc = Marshalling.ParseString(table, "product_desc");
if (table.ContainsKey("serial"))
serial = Marshalling.ParseString(table, "serial");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("description"))
description = Marshalling.ParseString(table, "description");
if (table.ContainsKey("passthrough_enabled"))
passthrough_enabled = Marshalling.ParseBool(table, "passthrough_enabled");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("speed"))
speed = Marshalling.ParseDouble(table, "speed");
}
public Proxy_PUSB ToProxy()
{
Proxy_PUSB result_ = new Proxy_PUSB();
result_.uuid = uuid ?? "";
result_.USB_group = USB_group ?? "";
result_.host = host ?? "";
result_.path = path ?? "";
result_.vendor_id = vendor_id ?? "";
result_.vendor_desc = vendor_desc ?? "";
result_.product_id = product_id ?? "";
result_.product_desc = product_desc ?? "";
result_.serial = serial ?? "";
result_.version = version ?? "";
result_.description = description ?? "";
result_.passthrough_enabled = passthrough_enabled;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.speed = speed;
return result_;
}
public bool DeepEquals(PUSB other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._USB_group, other._USB_group) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._path, other._path) &&
Helper.AreEqual2(this._vendor_id, other._vendor_id) &&
Helper.AreEqual2(this._vendor_desc, other._vendor_desc) &&
Helper.AreEqual2(this._product_id, other._product_id) &&
Helper.AreEqual2(this._product_desc, other._product_desc) &&
Helper.AreEqual2(this._serial, other._serial) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._description, other._description) &&
Helper.AreEqual2(this._passthrough_enabled, other._passthrough_enabled) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._speed, other._speed);
}
public override string SaveChanges(Session session, string opaqueRef, PUSB server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
PUSB.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static PUSB get_record(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_record(session.opaque_ref, _pusb);
else
return new PUSB(session.XmlRpcProxy.pusb_get_record(session.opaque_ref, _pusb ?? "").parse());
}
/// <summary>
/// Get a reference to the PUSB instance with the specified UUID.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PUSB> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<PUSB>.Create(session.XmlRpcProxy.pusb_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_uuid(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_uuid(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_uuid(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the USB_group field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static XenRef<USB_group> get_USB_group(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_usb_group(session.opaque_ref, _pusb);
else
return XenRef<USB_group>.Create(session.XmlRpcProxy.pusb_get_usb_group(session.opaque_ref, _pusb ?? "").parse());
}
/// <summary>
/// Get the host field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static XenRef<Host> get_host(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_host(session.opaque_ref, _pusb);
else
return XenRef<Host>.Create(session.XmlRpcProxy.pusb_get_host(session.opaque_ref, _pusb ?? "").parse());
}
/// <summary>
/// Get the path field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_path(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_path(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_path(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the vendor_id field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_vendor_id(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_vendor_id(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_vendor_id(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the vendor_desc field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_vendor_desc(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_vendor_desc(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_vendor_desc(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the product_id field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_product_id(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_product_id(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_product_id(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the product_desc field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_product_desc(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_product_desc(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_product_desc(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the serial field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_serial(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_serial(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_serial(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the version field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_version(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_version(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_version(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the description field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static string get_description(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_description(session.opaque_ref, _pusb);
else
return session.XmlRpcProxy.pusb_get_description(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the passthrough_enabled field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static bool get_passthrough_enabled(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_passthrough_enabled(session.opaque_ref, _pusb);
else
return (bool)session.XmlRpcProxy.pusb_get_passthrough_enabled(session.opaque_ref, _pusb ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static Dictionary<string, string> get_other_config(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_other_config(session.opaque_ref, _pusb);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.pusb_get_other_config(session.opaque_ref, _pusb ?? "").parse());
}
/// <summary>
/// Get the speed field of the given PUSB.
/// First published in Citrix Hypervisor 8.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
public static double get_speed(Session session, string _pusb)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_speed(session.opaque_ref, _pusb);
else
return Convert.ToDouble(session.XmlRpcProxy.pusb_get_speed(session.opaque_ref, _pusb ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pusb, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pusb_set_other_config(session.opaque_ref, _pusb, _other_config);
else
session.XmlRpcProxy.pusb_set_other_config(session.opaque_ref, _pusb ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given PUSB.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pusb, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pusb_add_to_other_config(session.opaque_ref, _pusb, _key, _value);
else
session.XmlRpcProxy.pusb_add_to_other_config(session.opaque_ref, _pusb ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given PUSB. If the key is not in that Map, then do nothing.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pusb, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pusb_remove_from_other_config(session.opaque_ref, _pusb, _key);
else
session.XmlRpcProxy.pusb_remove_from_other_config(session.opaque_ref, _pusb ?? "", _key ?? "").parse();
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The host</param>
public static void scan(Session session, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pusb_scan(session.opaque_ref, _host);
else
session.XmlRpcProxy.pusb_scan(session.opaque_ref, _host ?? "").parse();
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The host</param>
public static XenRef<Task> async_scan(Session session, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pusb_scan(session.opaque_ref, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pusb_scan(session.opaque_ref, _host ?? "").parse());
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
/// <param name="_value">passthrough is enabled when true and disabled with false</param>
public static void set_passthrough_enabled(Session session, string _pusb, bool _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pusb_set_passthrough_enabled(session.opaque_ref, _pusb, _value);
else
session.XmlRpcProxy.pusb_set_passthrough_enabled(session.opaque_ref, _pusb ?? "", _value).parse();
}
/// <summary>
///
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pusb">The opaque_ref of the given pusb</param>
/// <param name="_value">passthrough is enabled when true and disabled with false</param>
public static XenRef<Task> async_set_passthrough_enabled(Session session, string _pusb, bool _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pusb_set_passthrough_enabled(session.opaque_ref, _pusb, _value);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pusb_set_passthrough_enabled(session.opaque_ref, _pusb ?? "", _value).parse());
}
/// <summary>
/// Return a list of all the PUSBs known to the system.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PUSB>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_all(session.opaque_ref);
else
return XenRef<PUSB>.Create(session.XmlRpcProxy.pusb_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the PUSB Records at once, in a single XML RPC call
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PUSB>, PUSB> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pusb_get_all_records(session.opaque_ref);
else
return XenRef<PUSB>.Create<Proxy_PUSB>(session.XmlRpcProxy.pusb_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// USB group the PUSB is contained in
/// </summary>
[JsonConverter(typeof(XenRefConverter<USB_group>))]
public virtual XenRef<USB_group> USB_group
{
get { return _USB_group; }
set
{
if (!Helper.AreEqual(value, _USB_group))
{
_USB_group = value;
NotifyPropertyChanged("USB_group");
}
}
}
private XenRef<USB_group> _USB_group = new XenRef<USB_group>("OpaqueRef:NULL");
/// <summary>
/// Physical machine that owns the USB device
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL");
/// <summary>
/// port path of USB device
/// </summary>
public virtual string path
{
get { return _path; }
set
{
if (!Helper.AreEqual(value, _path))
{
_path = value;
NotifyPropertyChanged("path");
}
}
}
private string _path = "";
/// <summary>
/// vendor id of the USB device
/// </summary>
public virtual string vendor_id
{
get { return _vendor_id; }
set
{
if (!Helper.AreEqual(value, _vendor_id))
{
_vendor_id = value;
NotifyPropertyChanged("vendor_id");
}
}
}
private string _vendor_id = "";
/// <summary>
/// vendor description of the USB device
/// </summary>
public virtual string vendor_desc
{
get { return _vendor_desc; }
set
{
if (!Helper.AreEqual(value, _vendor_desc))
{
_vendor_desc = value;
NotifyPropertyChanged("vendor_desc");
}
}
}
private string _vendor_desc = "";
/// <summary>
/// product id of the USB device
/// </summary>
public virtual string product_id
{
get { return _product_id; }
set
{
if (!Helper.AreEqual(value, _product_id))
{
_product_id = value;
NotifyPropertyChanged("product_id");
}
}
}
private string _product_id = "";
/// <summary>
/// product description of the USB device
/// </summary>
public virtual string product_desc
{
get { return _product_desc; }
set
{
if (!Helper.AreEqual(value, _product_desc))
{
_product_desc = value;
NotifyPropertyChanged("product_desc");
}
}
}
private string _product_desc = "";
/// <summary>
/// serial of the USB device
/// </summary>
public virtual string serial
{
get { return _serial; }
set
{
if (!Helper.AreEqual(value, _serial))
{
_serial = value;
NotifyPropertyChanged("serial");
}
}
}
private string _serial = "";
/// <summary>
/// USB device version
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// USB device description
/// </summary>
public virtual string description
{
get { return _description; }
set
{
if (!Helper.AreEqual(value, _description))
{
_description = value;
NotifyPropertyChanged("description");
}
}
}
private string _description = "";
/// <summary>
/// enabled for passthrough
/// </summary>
public virtual bool passthrough_enabled
{
get { return _passthrough_enabled; }
set
{
if (!Helper.AreEqual(value, _passthrough_enabled))
{
_passthrough_enabled = value;
NotifyPropertyChanged("passthrough_enabled");
}
}
}
private bool _passthrough_enabled = false;
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// USB device speed
/// First published in Citrix Hypervisor 8.2.
/// </summary>
public virtual double speed
{
get { return _speed; }
set
{
if (!Helper.AreEqual(value, _speed))
{
_speed = value;
NotifyPropertyChanged("speed");
}
}
}
private double _speed = -1.000;
}
}
| |
// 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.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PrimitiveOperations operations.
/// </summary>
public partial interface IPrimitiveOperations
{
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<IntWrapperInner>> GetIntWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutIntWithHttpMessagesAsync(IntWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<LongWrapperInner>> GetLongWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutLongWithHttpMessagesAsync(LongWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<FloatWrapperInner>> GetFloatWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutFloatWithHttpMessagesAsync(FloatWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DoubleWrapperInner>> GetDoubleWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutDoubleWithHttpMessagesAsync(DoubleWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<BooleanWrapperInner>> GetBoolWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutBoolWithHttpMessagesAsync(BooleanWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<StringWrapperInner>> GetStringWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutStringWithHttpMessagesAsync(StringWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DateWrapperInner>> GetDateWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutDateWithHttpMessagesAsync(DateWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DatetimeWrapperInner>> GetDateTimeWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and
/// '2015-05-18T11:38:00-08:00'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutDateTimeWithHttpMessagesAsync(DatetimeWrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Datetimerfc1123WrapperInner>> GetDateTimeRfc1123WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015
/// 11:38:00 GMT'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutDateTimeRfc1123WithHttpMessagesAsync(Datetimerfc1123WrapperInner complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DurationWrapperInner>> GetDurationWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='field'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutDurationWithHttpMessagesAsync(System.TimeSpan? field = default(System.TimeSpan?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ByteWrapperInner>> GetByteWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='field'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutByteWithHttpMessagesAsync(byte[] field = default(byte[]), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// 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.Xml.Tests
{
public class LastChildTests
{
[Fact]
public static void ElementWithNoChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<top />");
Assert.Null(xmlDocument.DocumentElement.LastChild);
}
[Fact]
public static void ElementWithNoChildTwoAttributes()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<top attr1='test1' attr2='test2' />");
Assert.Null(xmlDocument.DocumentElement.LastChild);
}
[Fact]
public static void DeleteOnlyChildInsertNewNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<elem att1='foo'><a /></elem>");
var node = xmlDocument.DocumentElement;
var old = node.FirstChild;
node.RemoveChild(old);
var newNode = xmlDocument.CreateTextNode("textNode");
node.AppendChild(newNode);
Assert.Equal("textNode", node.LastChild.Value);
Assert.Equal(XmlNodeType.Text, node.LastChild.NodeType);
Assert.Equal(1, node.ChildNodes.Count);
}
[Fact]
public static void DeleteOnlyChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<elem att1='foo'><a /></elem>");
var node = xmlDocument.DocumentElement;
var oldNode = node.FirstChild;
node.RemoveChild(oldNode);
Assert.Null(node.LastChild);
Assert.Equal(0, node.ChildNodes.Count);
}
[Fact]
public static void DeleteOnlyChildAddTwoChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<elem att1='foo'><a /></elem>");
var node = xmlDocument.DocumentElement;
var oldNode = node.FirstChild;
node.RemoveChild(oldNode);
var element1 = xmlDocument.CreateElement("elem1");
var element2 = xmlDocument.CreateElement("elem2");
node.AppendChild(element1);
node.AppendChild(element2);
Assert.Equal(2, node.ChildNodes.Count);
Assert.Equal(element2, node.LastChild);
}
[Fact]
public static void DeleteOnlyChildAddTwoChildrenDeleteBoth()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<elem att1='foo'><a /></elem>");
var node = xmlDocument.DocumentElement;
var oldNode = node.FirstChild;
node.RemoveChild(oldNode);
var element1 = xmlDocument.CreateElement("elem1");
var element2 = xmlDocument.CreateElement("elem2");
node.AppendChild(element1);
node.AppendChild(element2);
node.RemoveChild(element1);
node.RemoveChild(element2);
Assert.Null(node.LastChild);
Assert.Equal(0, node.ChildNodes.Count);
}
[Fact]
public static void AttributeWithOnlyText()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<element attrib='helloworld' />");
var node = xmlDocument.DocumentElement.GetAttributeNode("attrib");
Assert.Equal("helloworld", node.LastChild.Value);
Assert.Equal(1, node.ChildNodes.Count);
}
[Fact]
public static void ElementWithTwoAttributes()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(" <element attrib1='hello' attrib2='world' />");
Assert.Null(xmlDocument.DocumentElement.LastChild);
}
[Fact]
public static void ElementWithOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
Assert.Equal(XmlNodeType.Element, xmlDocument.DocumentElement.LastChild.NodeType);
Assert.Equal("child1", xmlDocument.DocumentElement.LastChild.Name);
}
[Fact]
public static void ElementWithMoreThanOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2>Some Text</child2><!-- comment --><?PI pi comments?></root>");
Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.NotNull(xmlDocument.DocumentElement.LastChild);
Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.DocumentElement.LastChild.NodeType);
}
[Fact]
public static void ElementNodeWithOneChildAndOneElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<element attrib1='value'>content</element>");
Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.LastChild.NodeType);
Assert.Equal("content", xmlDocument.DocumentElement.LastChild.Value);
}
[Fact]
public static void NewlyCreatedElement()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("element");
Assert.Null(node.LastChild);
}
[Fact]
public static void NewlyCreatedAttribute()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
Assert.Null(node.LastChild);
}
[Fact]
public static void NewlyCreatedTextNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateTextNode("textnode");
Assert.Null(node.LastChild);
}
[Fact]
public static void NewlyCreatedCDataNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateCDataSection("cdata section");
Assert.Null(node.LastChild);
}
[Fact]
public static void NewlyCreatedProcessingInstruction()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateProcessingInstruction("PI", "data");
Assert.Null(node.LastChild);
}
[Fact]
public static void NewlyCreatedComment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateComment("comment");
Assert.Null(node.LastChild);
}
[Fact]
public static void NewlyCreatedDocumentFragment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateDocumentFragment();
Assert.Null(node.LastChild);
}
[Fact]
public static void InsertChildAtLengthMinus1()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var child3 = xmlDocument.DocumentElement.LastChild;
Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal("child3", child3.Name);
var newNode = xmlDocument.CreateElement("elem1");
xmlDocument.DocumentElement.InsertBefore(newNode, child3);
Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(child3, xmlDocument.DocumentElement.LastChild);
}
[Fact]
public static void InsertChildToElementWithNoNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
Assert.False(xmlDocument.DocumentElement.HasChildNodes);
var newNode = xmlDocument.CreateElement("elem1");
xmlDocument.DocumentElement.AppendChild(newNode);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild);
}
[Fact]
public static void ReplaceOnlyChildOfNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
var oldNode = xmlDocument.DocumentElement.LastChild;
var newNode = xmlDocument.CreateElement("elem1");
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild);
xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild);
}
[Fact]
public static void ReplaceChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var oldNode = xmlDocument.DocumentElement.LastChild;
var newNode = xmlDocument.CreateElement("elem1");
Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild);
xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode);
Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild);
}
}
}
| |
/* Generated By: CSCC: 4.0 (03/25/2012) Do not edit this line. SyntaxChecker.cs */
namespace org.mariuszgromada.math.mxparser.syntaxchecker{
using System;
using System.IO;
public class SyntaxChecker : SyntaxCheckerConstants {
public void checkSyntax()
{
start();
}
/*
* Lexer logic - grammar
*/
public void start() {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case LEFT_PAR:
case PLUS:
case MINUS:
case UNIT:
case NOT:
case BITNOT:
case NUMBER_CONSTANT:
case IDENTIFIER:
case FUNCTION:
case 48:
expression();
jj_consume_token(0);
break;
case 0:
jj_consume_token(0);
break;
default:
jj_la1[0] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
}
/*
* Grammar for expression
*/
public void expression() {
binaryExpression();
}
/*
* Grammar for binary operators
*/
public void binaryExpression() {
unaryRigthExpression();
while (true) {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case PLUS:
case MINUS:
case MULTIPLY:
case DIV:
case POWER:
case MODULO:
case EQ:
case NEQ:
case LT:
case LEQ:
case GT:
case GEQ:
case OR:
case AND:
case IMP:
case CIMP:
case NIMP:
case CNIMP:
case NAND:
case EQV:
case NOR:
case BITWISE:
case XOR:
;
break;
default:
jj_la1[1] = jj_gen;
goto label_1;
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case PLUS:
jj_consume_token(PLUS);
unaryRigthExpression();
break;
case MINUS:
jj_consume_token(MINUS);
unaryRigthExpression();
break;
case MULTIPLY:
jj_consume_token(MULTIPLY);
unaryRigthExpression();
break;
case DIV:
jj_consume_token(DIV);
unaryRigthExpression();
break;
case MODULO:
jj_consume_token(MODULO);
unaryRigthExpression();
break;
case POWER:
jj_consume_token(POWER);
unaryRigthExpression();
break;
case EQ:
jj_consume_token(EQ);
unaryRigthExpression();
break;
case NEQ:
jj_consume_token(NEQ);
unaryRigthExpression();
break;
case GT:
jj_consume_token(GT);
unaryRigthExpression();
break;
case GEQ:
jj_consume_token(GEQ);
unaryRigthExpression();
break;
case LT:
jj_consume_token(LT);
unaryRigthExpression();
break;
case LEQ:
jj_consume_token(LEQ);
unaryRigthExpression();
break;
case OR:
jj_consume_token(OR);
unaryRigthExpression();
break;
case AND:
jj_consume_token(AND);
unaryRigthExpression();
break;
case NOR:
jj_consume_token(NOR);
unaryRigthExpression();
break;
case NAND:
jj_consume_token(NAND);
unaryRigthExpression();
break;
case XOR:
jj_consume_token(XOR);
unaryRigthExpression();
break;
case IMP:
jj_consume_token(IMP);
unaryRigthExpression();
break;
case CIMP:
jj_consume_token(CIMP);
unaryRigthExpression();
break;
case NIMP:
jj_consume_token(NIMP);
unaryRigthExpression();
break;
case CNIMP:
jj_consume_token(CNIMP);
unaryRigthExpression();
break;
case EQV:
jj_consume_token(EQV);
unaryRigthExpression();
break;
case BITWISE:
jj_consume_token(BITWISE);
unaryRigthExpression();
break;
default:
jj_la1[2] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
}
label_1: ;
}
/*
* Grammar for unary rigth operators
*/
public void unaryRigthExpression() {
unaryLeftExpression();
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case FACTORIAL:
jj_consume_token(FACTORIAL);
break;
default:
jj_la1[3] = jj_gen;
;break;
}
}
/*
* Grammar for unary left operators
*/
public void unaryLeftExpression() {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case NOT:
case BITNOT:
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case NOT:
jj_consume_token(NOT);
break;
case BITNOT:
jj_consume_token(BITNOT);
break;
default:
jj_la1[4] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
break;
default:
jj_la1[5] = jj_gen;
;break;
}
itemExpression();
}
/*
* Grammar for items
*/
public void itemExpression() {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case PLUS:
case MINUS:
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case PLUS:
jj_consume_token(PLUS);
break;
case MINUS:
jj_consume_token(MINUS);
break;
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
break;
default:
jj_la1[7] = jj_gen;
;break;
}
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case NUMBER_CONSTANT:
jj_consume_token(NUMBER_CONSTANT);
break;
case UNIT:
case IDENTIFIER:
case FUNCTION:
case 48:
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case UNIT:
case IDENTIFIER:
case 48:
identifierGr();
break;
case FUNCTION:
jj_consume_token(FUNCTION);
break;
default:
jj_la1[8] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case LEFT_PAR:
jj_consume_token(LEFT_PAR);
argumentList();
jj_consume_token(RIGHT_PAR);
break;
default:
jj_la1[9] = jj_gen;
;break;
}
break;
case LEFT_PAR:
jj_consume_token(LEFT_PAR);
expression();
jj_consume_token(RIGHT_PAR);
break;
default:
jj_la1[10] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
}
/*
* Grammar for arguments list
*/
public void argumentList() {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case LEFT_PAR:
case PLUS:
case MINUS:
case UNIT:
case NOT:
case BITNOT:
case NUMBER_CONSTANT:
case IDENTIFIER:
case FUNCTION:
case 48:
expression();
while (true) {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case COMMA:
case SEMICOLON:
;
break;
default:
jj_la1[11] = jj_gen;
goto label_2;
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case COMMA:
jj_consume_token(COMMA);
break;
case SEMICOLON:
jj_consume_token(SEMICOLON);
break;
default:
jj_la1[12] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
expression();
}
label_2: ;
break;
default:
jj_la1[13] = jj_gen;
;break;
}
}
/*
* Grammar for identifiers
*/
public void identifierGr() {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case IDENTIFIER:
jj_consume_token(IDENTIFIER);
break;
case UNIT:
jj_consume_token(UNIT);
break;
case 48:
jj_consume_token(48);
while (true) {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case CHAR:
jj_consume_token(CHAR);
break;
case IDENTIFIER:
jj_consume_token(IDENTIFIER);
while (true) {
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case LEFT_PAR:
case RIGHT_PAR:
case PLUS:
case MINUS:
case MULTIPLY:
case DIV:
case POWER:
case MODULO:
case COMMA:
case LT:
case GT:
case OR:
case AND:
case NOT:
case NUMBER_CONSTANT:
;
break;
default:
jj_la1[14] = jj_gen;
goto label_4;
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case NOT:
jj_consume_token(NOT);
break;
case MODULO:
jj_consume_token(MODULO);
break;
case POWER:
jj_consume_token(POWER);
break;
case AND:
jj_consume_token(AND);
break;
case MULTIPLY:
jj_consume_token(MULTIPLY);
break;
case DIV:
jj_consume_token(DIV);
break;
case LEFT_PAR:
jj_consume_token(LEFT_PAR);
break;
case RIGHT_PAR:
jj_consume_token(RIGHT_PAR);
break;
case MINUS:
jj_consume_token(MINUS);
break;
case PLUS:
jj_consume_token(PLUS);
break;
case COMMA:
jj_consume_token(COMMA);
break;
case OR:
jj_consume_token(OR);
break;
case GT:
jj_consume_token(GT);
break;
case LT:
jj_consume_token(LT);
break;
case NUMBER_CONSTANT:
jj_consume_token(NUMBER_CONSTANT);
break;
default:
jj_la1[15] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
}
label_4: ;
break;
default:
jj_la1[16] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
switch ((jj_ntk==-1)?jj_init_ntk():jj_ntk) {
case CHAR:
case IDENTIFIER:
;
break;
default:
jj_la1[17] = jj_gen;
goto label_3;
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
}
label_3: ;
jj_consume_token(49);
break;
default:
jj_la1[18] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
#if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS
break;
#endif
}
}
public SyntaxCheckerTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
private long jj_ntk;
private long jj_gen;
private long[] jj_la1 = new long[19];
static private long[] jj_la1_0;
static private long[] jj_la1_1;
static SyntaxChecker(){
jj_la1_init_0();
jj_la1_init_1();
}
private static void jj_la1_init_0() {
jj_la1_0 = new long[] {0x80806801,0x7f47e000,0x7f47e000,0x80000,0x80000000,0x80000000,0x6000,0x6000,0x800000,0x800,0x800800,0x300000,0x300000,0x80806800,0xea17f800,0xea17f800,0x0,0x0,0x800000,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new long[] {0x1e001,0x3fe,0x3fe,0x0,0x1,0x1,0x0,0x0,0x1c000,0x0,0x1e000,0x0,0x0,0x1e001,0x2000,0x2000,0x4400,0x4400,0x14000,};
}
public SyntaxChecker(System.IO.Stream stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new SyntaxCheckerTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 19; i++) jj_la1[i] = -1;
}
public void ReInit(System.IO.Stream stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 19; i++) jj_la1[i] = -1;
}
public SyntaxChecker(System.IO.TextReader stream) {
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new SyntaxCheckerTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 19; i++) jj_la1[i] = -1;
}
public void ReInit(System.IO.TextReader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 19; i++) jj_la1[i] = -1;
}
public SyntaxChecker(SyntaxCheckerTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 19; i++) jj_la1[i] = -1;
}
public void ReInit(SyntaxCheckerTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 19; i++) jj_la1[i] = -1;
}
private Token jj_consume_token(int kind){
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private long jj_init_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private System.Collections.Generic.List<long[]> jj_expentries = new System.Collections.Generic.List<long[]>();
private long[] jj_expentry;
private long jj_kind = -1;
public ParseException generateParseException() {
jj_expentries.Clear();
bool[] la1tokens = new bool[52];
for (int i = 0; i < 52; i++) {
la1tokens[i] = false;
}
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 19; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 52; i++) {
if (la1tokens[i]) {
jj_expentry = new long[1];
jj_expentry[0] = i;
jj_expentries.Add(jj_expentry);
}
}
long[][] exptokseq = new long[jj_expentries.Count][];
for (int i = 0; i < jj_expentries.Count; i++) {
exptokseq[i] = (long[])jj_expentries[i];
}
return new ParseException(token, exptokseq, tokenImage);
}
public void enable_tracing() {
}
public void disable_tracing() {
}
}
}
| |
// <copyright file="GPGSUtil.cs" company="Google Inc.">
// Copyright (C) 2014 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 GooglePlayGames.Editor
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Utility class to perform various tasks in the editor.
/// </summary>
public static class GPGSUtil
{
/// <summary>Property key for project requiring G+ access
public const string REQUIREGOOGLEPLUSKEY = "proj.requireGPlus";
/// <summary>Property key for project settings.</summary>
public const string SERVICEIDKEY = "App.NearbdServiceId";
/// <summary>Property key for project settings.</summary>
public const string APPIDKEY = "proj.AppId";
/// <summary>Property key for project settings.</summary>
public const string CLASSDIRECTORYKEY = "proj.classDir";
/// <summary>Property key for project settings.</summary>
public const string CLASSNAMEKEY = "proj.ConstantsClassName";
/// <summary>Property key for project settings.</summary>
public const string WEBCLIENTIDKEY = "and.ClientId";
/// <summary>Property key for project settings.</summary>
public const string IOSCLIENTIDKEY = "ios.ClientId";
/// <summary>Property key for project settings.</summary>
public const string IOSBUNDLEIDKEY = "ios.BundleId";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDRESOURCEKEY = "and.ResourceData";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDSETUPDONEKEY = "android.SetupDone";
/// <summary>Property key for project settings.</summary>
public const string ANDROIDBUNDLEIDKEY = "and.BundleId";
/// <summary>Property key for project settings.</summary>
public const string IOSRESOURCEKEY = "ios.ResourceData";
/// <summary>Property key for project settings.</summary>
public const string IOSSETUPDONEKEY = "ios.SetupDone";
/// <summary>Property key for nearby settings done.</summary>
public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone";
/// <summary>Property key for project settings.</summary>
public const string LASTUPGRADEKEY = "lastUpgrade";
/// <summary>Constant for token replacement</summary>
private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__";
/// <summary>Constant for token replacement</summary>
private const string APPIDPLACEHOLDER = "__APP_ID__";
/// <summary>Constant for token replacement</summary>
private const string CLASSNAMEPLACEHOLDER = "__Class__";
/// <summary>Constant for token replacement</summary>
private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__";
/// <summary>Constant for token replacement</summary>
private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__";
/// <summary>Constant for token replacement</summary>
private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__";
/// <summary>Constant for token replacement</summary>
private const string TOKENPERMISSIONSHOLDER = "__TOKEN_PERMISSIONS__";
/// <summary>Constant for require google plus token replacement</summary>
private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__";
/// <summary>Property key for project settings.</summary>
private const string TOKENPERMISSIONKEY = "proj.tokenPermissions";
/// <summary>Constant for token replacement</summary>
private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__";
/// <summary>Constant for token replacement</summary>
private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__";
/// <summary>Constant for token replacement</summary>
private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__";
/// <summary>
/// The game info file path. This is a generated file.
/// </summary>
private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs";
/// <summary>
/// The token permissions to add if needed.
/// </summary>
private const string TokenPermissions =
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>\n" +
"<uses-permission android:name=\"android.permission.USE_CREDENTIALS\"/>";
/// <summary>
/// The map of replacements for filling in code templates. The
/// key is the string that appears in the template as a placeholder,
/// the value is the key into the GPGSProjectSettings.
/// </summary>
private static Dictionary<string, string> replacements =
new Dictionary<string, string>()
{
{ SERVICEIDPLACEHOLDER, SERVICEIDKEY },
{ APPIDPLACEHOLDER, APPIDKEY },
{ CLASSNAMEPLACEHOLDER, CLASSNAMEKEY },
{ WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY },
{ IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY },
{ IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY },
{ TOKENPERMISSIONSHOLDER, TOKENPERMISSIONKEY },
{ REQUIREGOOGLEPLUSPLACEHOLDER, REQUIREGOOGLEPLUSKEY }
};
/// <summary>
/// Replaces / in file path to be the os specific separator.
/// </summary>
/// <returns>The path.</returns>
/// <param name="path">Path with correct separators.</param>
public static string SlashesToPlatformSeparator(string path)
{
return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString());
}
/// <summary>
/// Reads the file.
/// </summary>
/// <returns>The file contents. The slashes are corrected.</returns>
/// <param name="filePath">File path.</param>
public static string ReadFile(string filePath)
{
filePath = SlashesToPlatformSeparator(filePath);
if (!File.Exists(filePath))
{
Alert("Plugin error: file not found: " + filePath);
return null;
}
StreamReader sr = new StreamReader(filePath);
string body = sr.ReadToEnd();
sr.Close();
return body;
}
/// <summary>
/// Reads the editor template.
/// </summary>
/// <returns>The editor template contents.</returns>
/// <param name="name">Name of the template in the editor directory.</param>
public static string ReadEditorTemplate(string name)
{
return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt"));
}
/// <summary>
/// Writes the file.
/// </summary>
/// <param name="file">File path - the slashes will be corrected.</param>
/// <param name="body">Body of the file to write.</param>
public static void WriteFile(string file, string body)
{
file = SlashesToPlatformSeparator(file);
using (var wr = new StreamWriter(file, false))
{
wr.Write(body);
}
}
/// <summary>
/// Validates the string to be a valid nearby service id.
/// </summary>
/// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns>
/// <param name="s">string to test.</param>
public static bool LooksLikeValidServiceId(string s)
{
if (s.Length < 3)
{
return false;
}
foreach (char c in s)
{
if (!char.IsLetterOrDigit(c) && c != '.')
{
return false;
}
}
return true;
}
/// <summary>
/// Looks the like valid app identifier.
/// </summary>
/// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidAppId(string s)
{
if (s.Length < 5)
{
return false;
}
foreach (char c in s)
{
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}
/// <summary>
/// Looks the like valid client identifier.
/// </summary>
/// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidClientId(string s)
{
return s.EndsWith(".googleusercontent.com");
}
/// <summary>
/// Looks the like a valid bundle identifier.
/// </summary>
/// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidBundleId(string s)
{
return s.Length > 3;
}
/// <summary>
/// Looks like a valid package.
/// </summary>
/// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns>
/// <param name="s">the string to test.</param>
public static bool LooksLikeValidPackageName(string s)
{
if (string.IsNullOrEmpty(s))
{
throw new Exception("cannot be empty");
}
string[] parts = s.Split(new char[] { '.' });
foreach (string p in parts)
{
char[] bytes = p.ToCharArray();
for (int i = 0; i < bytes.Length; i++)
{
if (i == 0 && !char.IsLetter(bytes[i]))
{
throw new Exception("each part must start with a letter");
}
else if (char.IsWhiteSpace(bytes[i]))
{
throw new Exception("cannot contain spaces");
}
else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_')
{
throw new Exception("must be alphanumeric or _");
}
}
}
return parts.Length >= 1;
}
/// <summary>
/// Determines if is setup done.
/// </summary>
/// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns>
public static bool IsSetupDone()
{
bool doneSetup = true;
#if UNITY_ANDROID
doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false);
// check gameinfo
if (File.Exists(GameInfoPath))
{
string contents = ReadFile(GameInfoPath);
if (contents.Contains(APPIDPLACEHOLDER))
{
Debug.Log("GameInfo not initialized with AppId. " +
"Run Window > Google Play Games > Setup > Android Setup...");
return false;
}
}
else
{
Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup...");
return false;
}
#elif (UNITY_IPHONE && !NO_GPGS)
doneSetup = GPGSProjectSettings.Instance.GetBool(IOSSETUPDONEKEY, false);
// check gameinfo
if (File.Exists(GameInfoPath))
{
string contents = ReadFile(GameInfoPath);
if (contents.Contains(IOSCLIENTIDPLACEHOLDER))
{
Debug.Log("GameInfo not initialized with Client Id. " +
"Run Window > Google Play Games > Setup > iOS Setup...");
return false;
}
}
else
{
Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > iOS Setup...");
return false;
}
#endif
return doneSetup;
}
/// <summary>
/// Makes legal identifier from string.
/// Returns a legal C# identifier from the given string. The transformations are:
/// - spaces => underscore _
/// - punctuation => empty string
/// - leading numbers are prefixed with underscore.
/// </summary>
/// <returns>the id</returns>
/// <param name="key">Key to convert to an identifier.</param>
public static string MakeIdentifier(string key)
{
string s;
string retval = string.Empty;
if (string.IsNullOrEmpty(key))
{
return "_";
}
s = key.Trim().Replace(' ', '_');
foreach (char c in s)
{
if (char.IsLetterOrDigit(c) || c == '_')
{
retval += c;
}
}
return retval;
}
/// <summary>
/// Displays an error dialog.
/// </summary>
/// <param name="s">the message</param>
public static void Alert(string s)
{
Alert(GPGSStrings.Error, s);
}
/// <summary>
/// Displays a dialog with the given title and message.
/// </summary>
/// <param name="title">the title.</param>
/// <param name="message">the message.</param>
public static void Alert(string title, string message)
{
EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok);
}
/// <summary>
/// Gets the android sdk path.
/// </summary>
/// <returns>The android sdk path.</returns>
public static string GetAndroidSdkPath()
{
string sdkPath = EditorPrefs.GetString("AndroidSdkRoot");
if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\")))
{
sdkPath = sdkPath.Substring(0, sdkPath.Length - 1);
}
return sdkPath;
}
/// <summary>
/// Determines if the android sdk exists.
/// </summary>
/// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns>
public static bool HasAndroidSdk()
{
string sdkPath = GetAndroidSdkPath();
return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath);
}
/// <summary>
/// Gets the unity major version.
/// </summary>
/// <returns>The unity major version.</returns>
public static int GetUnityMajorVersion()
{
#if UNITY_5
string majorVersion = Application.unityVersion.Split('.')[0];
int ver;
if (!int.TryParse(majorVersion, out ver))
{
ver = 0;
}
return ver;
#elif UNITY_4_6
return 4;
#else
return 0;
#endif
}
/// <summary>
/// Checks for the android manifest file exsistance.
/// </summary>
/// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns>
public static bool AndroidManifestExists()
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
return File.Exists(destFilename);
}
/// <summary>
/// Generates the android manifest.
/// </summary>
/// <param name="needTokenPermissions">If set to <c>true</c> need token permissions.</param>
public static void GenerateAndroidManifest(bool needTokenPermissions)
{
string destFilename = GPGSUtil.SlashesToPlatformSeparator(
"Assets/Plugins/Android/MainLibProj/AndroidManifest.xml");
// Generate AndroidManifest.xml
string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest");
Dictionary<string, string> overrideValues =
new Dictionary<string, string>();
if (!needTokenPermissions)
{
overrideValues[TOKENPERMISSIONKEY] = string.Empty;
overrideValues[WEBCLIENTIDPLACEHOLDER] = string.Empty;
}
else
{
overrideValues[TOKENPERMISSIONKEY] = TokenPermissions;
}
foreach (KeyValuePair<string, string> ent in replacements)
{
string value =
GPGSProjectSettings.Instance.Get(ent.Value, overrideValues);
manifestBody = manifestBody.Replace(ent.Key, value);
}
GPGSUtil.WriteFile(destFilename, manifestBody);
GPGSUtil.UpdateGameInfo();
}
/// <summary>
/// Writes the resource identifiers file. This file contains the
/// resource ids copied (downloaded?) from the play game app console.
/// </summary>
/// <param name="classDirectory">Class directory.</param>
/// <param name="className">Class name.</param>
/// <param name="resourceKeys">Resource keys.</param>
public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys)
{
string constantsValues = string.Empty;
string[] parts = className.Split('.');
string dirName = classDirectory;
if (string.IsNullOrEmpty(dirName))
{
dirName = "Assets";
}
string nameSpace = string.Empty;
for (int i = 0; i < parts.Length - 1; i++)
{
dirName += "/" + parts[i];
if (nameSpace != string.Empty)
{
nameSpace += ".";
}
nameSpace += parts[i];
}
EnsureDirExists(dirName);
foreach (DictionaryEntry ent in resourceKeys)
{
string key = MakeIdentifier((string)ent.Key);
constantsValues += " public const string " +
key + " = \"" + ent.Value + "\"; // <GPGSID>\n";
}
string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants");
if (nameSpace != string.Empty)
{
fileBody = fileBody.Replace(
NAMESPACESTARTPLACEHOLDER,
"namespace " + nameSpace + "\n{");
}
else
{
fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty);
}
fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]);
fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues);
if (nameSpace != string.Empty)
{
fileBody = fileBody.Replace(
NAMESPACEENDPLACEHOLDER,
"}");
}
else
{
fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty);
}
WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody);
}
/// <summary>
/// Updates the game info file. This is a generated file containing the
/// app and client ids.
/// </summary>
public static void UpdateGameInfo()
{
string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo");
foreach (KeyValuePair<string, string> ent in replacements)
{
string value =
GPGSProjectSettings.Instance.Get(ent.Value);
fileBody = fileBody.Replace(ent.Key, value);
}
GPGSUtil.WriteFile(GameInfoPath, fileBody);
}
/// <summary>
/// Ensures the dir exists.
/// </summary>
/// <param name="dir">Directory to check.</param>
public static void EnsureDirExists(string dir)
{
dir = SlashesToPlatformSeparator(dir);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
/// <summary>
/// Deletes the dir if exists.
/// </summary>
/// <param name="dir">Directory to delete.</param>
public static void DeleteDirIfExists(string dir)
{
dir = SlashesToPlatformSeparator(dir);
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
}
/// <summary>
/// Gets the Google Play Services library version. This is only
/// needed for Unity versions less than 5.
/// </summary>
/// <returns>The GPS version.</returns>
/// <param name="libProjPath">Lib proj path.</param>
private static int GetGPSVersion(string libProjPath)
{
string versionFile = libProjPath + "/res/values/version.xml";
XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile));
bool inResource = false;
int version = -1;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "integer")
{
if ("google_play_services_version".Equals(
reader.GetAttribute("name")))
{
reader.Read();
Debug.Log("Read version string: " + reader.Value);
version = Convert.ToInt32(reader.Value);
}
}
}
reader.Close();
return version;
}
}
}
| |
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
//Added references
using ArcGIS.Core.CIM; //CIM
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout class
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping;
namespace Layout_HelpExamples
{
internal class LayoutClass : Button
{
protected override void OnClick()
{
LayoutClassSamples.MethodSnippets();
}
}
public class LayoutClassSamples
{
async public static void MethodSnippets()
{
#region LayoutProjectItem_GetLayout
//Reference the layout associated with a layout project item.
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout layout = await QueuedTask.Run(() => layoutItem.GetLayout()); //Perform on the worker thread
#endregion LayoutProjectItem_GetLayout
TextElement elm = layout.FindElement("Text") as TextElement;
// cref: Layout_DeleteElement;ArcGIS.Desktop.Layouts.Layout.DeleteElement(ArcGIS.Desktop.Layouts.Element)
#region Layout_DeleteElement
//Delete a single layout element.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
layout.DeleteElement(elm);
});
#endregion Layout_DeleteElement
// cref: Layout_DeleteElements;ArcGIS.Desktop.Layouts.Layout.DeleteElements(System.Func{ArcGIS.Desktop.Layouts.Element,System.Boolean})
#region Layout_DeleteElements
//Delete multiple layout elements.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
layout.DeleteElements(item => item.Name.Contains("Clone"));
});
#endregion Layout_DeleteElements
// cref: Layout_FindElement;ArcGIS.Desktop.Layouts.Layout.FindElement(System.String)
#region Layout_FindElement
//Find a layout element. The example below is referencing an existing text element.
TextElement txtElm = layout.FindElement("Text") as TextElement;
#endregion Layout_FindElement
// cref: Layout_GetSetDefinition;ArcGIS.Desktop.Layouts.Layout.GetDefinition
// cref: Layout_GetSetDefinition;ArcGIS.Desktop.Layouts.Layout.SetDefinition(ArcGIS.Core.CIM.CIMLayout)
#region Layout_GetSetDefinition
//Modify a layout's CIM definition
//Perform on the worker thread
await QueuedTask.Run(() =>
{
CIMLayout cimLayout = layout.GetDefinition();
//Do something
layout.SetDefinition(cimLayout);
});
#endregion Layout_GetSetDefinition
// cref: Layout_GetSetPage;ArcGIS.Desktop.Layouts.Layout.GetPage
// cref: Layout_GetSetPage;ArcGIS.Desktop.Layouts.Layout.SetPage(ArcGIS.Core.CIM.CIMPage)
#region Layout_GetSetPage
//Modify a layouts page settings.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
CIMPage page = layout.GetPage();
//Do something
layout.SetPage(page);
});
#endregion Layout_GetSetPage
String filePath = null;
#region Layout_ExportPDF
//See ProSnippets "Export layout to PDF"
#endregion Layout_ExportPDF
#region Layout_ExportMS_PDF
//Export multiple map series pages to PDF
//Create a PDF export format
PDFFormat msPDF = new PDFFormat()
{
Resolution = 300,
OutputFileName = filePath,
DoCompressVectorGraphics = true
};
//Set up the export options for the map series
MapSeriesExportOptions MSExport_custom = new MapSeriesExportOptions()
{
ExportPages = ExportPages.Custom,
CustomPages = "1-3, 5",
ExportFileOptions = ExportFileOptions.ExportAsSinglePDF,
ShowSelectedSymbology = false
};
//Check to see if the path is valid and export
if (msPDF.ValidateOutputFilePath())
{
layout.Export(msPDF, MSExport_custom); //Export the PDF to a single, multiple page PDF.
}
#endregion Layout_ExportMS_PDF
#region Layout_ExportMS_TIFF
//Export multiple map series pages to TIFF
//Create a TIFF export format
TIFFFormat msTIFF = new TIFFFormat()
{
Resolution = 300,
OutputFileName = filePath,
ColorMode = ColorMode.TwentyFourBitTrueColor,
HasGeoTiffTags = true,
HasWorldFile = true
};
//Set up the export options for the map series
MapSeriesExportOptions MSExport_All = new MapSeriesExportOptions()
{
ExportPages = ExportPages.All,
ExportFileOptions = ExportFileOptions.ExportMultipleNames,
ShowSelectedSymbology = false
};
//Check to see if the path is valid and export
if (msPDF.ValidateOutputFilePath())
{
layout.Export(msPDF, MSExport_All); //Export each page to a TIFF and apppend the page name suffix to each output file
}
#endregion Layout_ExportMS_TIFF
// cref: Layout_RefreshMapSeries;ArcGIS.Desktop.Layouts.Layout.RefreshMapSeries
#region Layout_RefreshMapSeries
//Refresh the map series associated with the layout.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
layout.RefreshMapSeries();
});
#endregion Layout_RefreshMapSeries
// cref: Layout_SaveAsFile;ArcGIS.Desktop.Layouts.Layout.SaveAsFile(System.String,System.Boolean)
#region Layout_SaveAsFile
//Save a layout to a pagx file.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
layout.SaveAsFile(filePath);
});
#endregion Layout_SaveAsFile
// cref: Layout_SetName;ArcGIS.Desktop.Layouts.Layout.SetName(System.String)
#region Layout_SetName
//Change the name of a layout.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
layout.SetName("New Name");
});
#endregion Layout_SetName
SpatialMapSeries SMS = null;
// cref: Layout_SetMapSeries;ArcGIS.Desktop.Layouts.Layout.SetMapSeries(ArcGIS.Desktop.Layouts.MapSeries)
#region Layout_SetMapSeries
//Change the properities of a spacial map series.
//Perform on the worker thread
await QueuedTask.Run(() =>
{
layout.SetMapSeries(SMS);
});
#endregion Layout_SetMapSeries
// cref: Layout_ShowProperties;ArcGIS.Desktop.Layouts.Layout.ShowProperties
#region Layout_ShowProperties
//Open the layout properties dialog.
//Get the layout associated with a layout project item
LayoutProjectItem lytItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout lyt = await QueuedTask.Run(() => lytItem.GetLayout()); //Worker thread
//Open the properties dialog
lyt.ShowProperties(); //GUI thread
#endregion Layout_ShowProperties
}
}
}
| |
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace DuendeIdP.Pages.Ciba;
[Authorize]
[SecurityHeadersAttribute]
public class Consent : PageModel
{
private readonly IBackchannelAuthenticationInteractionService _interaction;
private readonly IEventService _events;
private readonly ILogger<Index> _logger;
public Consent(
IBackchannelAuthenticationInteractionService interaction,
IEventService events,
ILogger<Index> logger)
{
_interaction = interaction;
_events = events;
_logger = logger;
}
public ViewModel View { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public async Task<IActionResult> OnGet(string id)
{
View = await BuildViewModelAsync(id);
if (View == null)
{
return RedirectToPage("/Home/Error/Index");
}
Input = new InputModel
{
Id = id
};
return Page();
}
public async Task<IActionResult> OnPost()
{
// validate return url is still valid
var request = await _interaction.GetLoginRequestByInternalIdAsync(Input.Id);
if (request == null || request.Subject.GetSubjectId() != User.GetSubjectId())
{
_logger.LogError("Invalid id {id}", Input.Id);
return RedirectToPage("/Home/Error/Index");
}
CompleteBackchannelLoginRequest result = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (Input?.Button == "no")
{
result = new CompleteBackchannelLoginRequest(Input.Id);
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues));
}
// user clicked 'yes' - validate the data
else if (Input?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (Input.ScopesConsented != null && Input.ScopesConsented.Any())
{
var scopes = Input.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess);
}
result = new CompleteBackchannelLoginRequest(Input.Id)
{
ScopesValuesConsented = scopes.ToArray(),
Description = Input.Description
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, result.ScopesValuesConsented, false));
}
else
{
ModelState.AddModelError("", ConsentOptions.MustChooseOneErrorMessage);
}
}
else
{
ModelState.AddModelError("", ConsentOptions.InvalidSelectionErrorMessage);
}
if (result != null)
{
// communicate outcome of consent back to identityserver
await _interaction.CompleteLoginRequestAsync(result);
return RedirectToPage("/Ciba/All");
}
// we need to redisplay the consent UI
View = await BuildViewModelAsync(Input.Id, Input);
return Page();
}
private async Task<ViewModel> BuildViewModelAsync(string id, InputModel model = null)
{
var request = await _interaction.GetLoginRequestByInternalIdAsync(id);
if (request != null && request.Subject.GetSubjectId() == User.GetSubjectId())
{
return CreateConsentViewModel(model, id, request);
}
else
{
_logger.LogError("No backchannel login request matching id: {id}", id);
}
return null;
}
private ViewModel CreateConsentViewModel(
InputModel model, string id,
BackchannelUserLoginRequest request)
{
var vm = new ViewModel
{
ClientName = request.Client.ClientName ?? request.Client.ClientId,
ClientUrl = request.Client.ClientUri,
ClientLogoUrl = request.Client.LogoUri,
BindingMessage = request.BindingMessage
};
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources
.Select(x => CreateScopeViewModel(x, model?.ScopesConsented == null || model.ScopesConsented?.Contains(x.Name) == true))
.ToArray();
var resourceIndicators = request.RequestedResourceIndicators ?? Enumerable.Empty<string>();
var apiResources = request.ValidatedResources.Resources.ApiResources.Where(x => resourceIndicators.Contains(x.Name));
var apiScopes = new List<ScopeViewModel>();
foreach (var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)
{
var scopeVm = CreateScopeViewModel(parsedScope, apiScope, model == null || model.ScopesConsented?.Contains(parsedScope.RawValue) == true);
scopeVm.Resources = apiResources.Where(x => x.Scopes.Contains(parsedScope.ParsedName))
.Select(x => new ResourceViewModel
{
Name = x.Name,
DisplayName = x.DisplayName ?? x.Name,
}).ToArray();
apiScopes.Add(scopeVm);
}
}
if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess)
{
apiScopes.Add(GetOfflineAccessScope(model == null || model.ScopesConsented?.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) == true));
}
vm.ApiScopes = apiScopes;
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
Value = identity.Name,
DisplayName = identity.DisplayName ?? identity.Name,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check)
{
var displayName = apiScope.DisplayName ?? apiScope.Name;
if (!String.IsNullOrWhiteSpace(parsedScopeValue.ParsedParameter))
{
displayName += ":" + parsedScopeValue.ParsedParameter;
}
return new ScopeViewModel
{
Name = parsedScopeValue.ParsedName,
Value = parsedScopeValue.RawValue,
DisplayName = displayName,
Description = apiScope.Description,
Emphasize = apiScope.Emphasize,
Required = apiScope.Required,
Checked = check || apiScope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CslaDataSource.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>A Web Forms data binding control designed to support</summary>
//-----------------------------------------------------------------------
#if !CLIENTONLY
using System;
using System.Web.UI;
using System.ComponentModel;
using System.Reflection;
using Csla.Properties;
namespace Csla.Web
{
/// <summary>
/// A Web Forms data binding control designed to support
/// CSLA .NET business objects as data sources.
/// </summary>
[Designer(typeof(Csla.Web.Design.CslaDataSourceDesigner))]
[DisplayName("CslaDataSource")]
[Description("CSLA .NET Data Source Control")]
[ToolboxData("<{0}:CslaDataSource runat=\"server\"></{0}:CslaDataSource>")]
public class CslaDataSource : DataSourceControl
{
private CslaDataSourceView _defaultView;
/// <summary>
/// Event raised when an object is to be created and
/// populated with data.
/// </summary>
/// <remarks>Handle this event in a page and set
/// e.BusinessObject to the populated business object.
/// </remarks>
public event EventHandler<SelectObjectArgs> SelectObject;
/// <summary>
/// Event raised when an object is to be populated with data
/// and inserted.
/// </summary>
/// <remarks>Handle this event in a page to create an
/// instance of the object, load the object with data and
/// insert the object into the database.</remarks>
public event EventHandler<InsertObjectArgs> InsertObject;
/// <summary>
/// Event raised when an object is to be updated.
/// </summary>
/// <remarks>Handle this event in a page to update an
/// existing instance of an object with new data and then
/// save the object into the database.</remarks>
public event EventHandler<UpdateObjectArgs> UpdateObject;
/// <summary>
/// Event raised when an object is to be deleted.
/// </summary>
/// <remarks>Handle this event in a page to delete
/// an object from the database.</remarks>
public event EventHandler<DeleteObjectArgs> DeleteObject;
/// <summary>
/// Returns the default view for this data control.
/// </summary>
/// <param name="viewName">Ignored.</param>
/// <returns></returns>
/// <remarks>This control only contains a "Default" view.</remarks>
protected override DataSourceView GetView(string viewName)
{
if (_defaultView == null)
_defaultView = new CslaDataSourceView(this, "Default");
return _defaultView;
}
/// <summary>
/// Get or set the name of the assembly (no longer used).
/// </summary>
/// <value>Obsolete - do not use.</value>
public string TypeAssemblyName
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeAssemblyName; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeAssemblyName = value; }
}
/// <summary>
/// Get or set the full type name of the business object
/// class to be used as a data source.
/// </summary>
/// <value>Full type name of the business class,
/// including assembly name.</value>
public string TypeName
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeName; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeName = value; }
}
/// <summary>
/// Get or set a value indicating whether the
/// business object data source supports paging.
/// </summary>
/// <remarks>
/// To support paging, the business object
/// (collection) must implement
/// <see cref="Csla.Core.IReportTotalRowCount"/>.
/// </remarks>
public bool TypeSupportsPaging
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeSupportsPaging; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeSupportsPaging = value; }
}
/// <summary>
/// Get or set a value indicating whether the
/// business object data source supports sorting.
/// </summary>
public bool TypeSupportsSorting
{
get { return ((CslaDataSourceView)this.GetView("Default")).TypeSupportsSorting; }
set { ((CslaDataSourceView)this.GetView("Default")).TypeSupportsSorting = value; }
}
private static System.Collections.Generic.Dictionary<string,Type> _typeCache =
new System.Collections.Generic.Dictionary<string,Type>();
/// <summary>
/// Returns a <see cref="Type">Type</see> object based on the
/// assembly and type information provided.
/// </summary>
/// <param name="typeAssemblyName">Optional assembly name.</param>
/// <param name="typeName">Full type name of the class,
/// including assembly name.</param>
/// <remarks></remarks>
internal static Type GetType(
string typeAssemblyName, string typeName)
{
Type result = null;
if (!string.IsNullOrEmpty(typeAssemblyName))
{
// explicit assembly name provided
result = Type.GetType(string.Format(
"{0}, {1}", typeName, typeAssemblyName), true, true);
}
else if (typeName.IndexOf(",") > 0)
{
// assembly qualified type name provided
result = Type.GetType(typeName, true, true);
}
else
{
// no assembly name provided
result = _typeCache[typeName];
if (result == null)
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
result = asm.GetType(typeName, false, true);
if (result != null)
{
_typeCache.Add(typeName, result);
break;
}
}
}
if (result == null)
throw new TypeLoadException(String.Format(Resources.TypeLoadException, typeName));
return result;
}
/// <summary>
/// Returns a list of views available for this control.
/// </summary>
/// <remarks>This control only provides the "Default" view.</remarks>
protected override System.Collections.ICollection GetViewNames()
{
return new string[] { "Default" };
}
/// <summary>
/// Raises the SelectObject event.
/// </summary>
internal void OnSelectObject(SelectObjectArgs e)
{
if (SelectObject != null)
SelectObject(this, e);
}
/// <summary>
/// Raises the InsertObject event.
/// </summary>
internal void OnInsertObject(InsertObjectArgs e)
{
if (InsertObject != null)
InsertObject(this, e);
}
/// <summary>
/// Raises the UpdateObject event.
/// </summary>
internal void OnUpdateObject(UpdateObjectArgs e)
{
if (UpdateObject != null)
UpdateObject(this, e);
}
/// <summary>
/// Raises the DeleteObject event.
/// </summary>
internal void OnDeleteObject(DeleteObjectArgs e)
{
if (DeleteObject != null)
DeleteObject(this, e);
}
}
}
#endif
| |
#region Copyright and License
// Copyright 2010..2015 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ARSoft.Tools.Net.Dns
{
internal class DnsSecValidator<TState>
{
private readonly IInternalDnsSecResolver<TState> _resolver;
private readonly IResolverHintStore _resolverHintStore;
public DnsSecValidator(IInternalDnsSecResolver<TState> resolver, IResolverHintStore resolverHintStore)
{
_resolver = resolver;
_resolverHintStore = resolverHintStore;
}
public async Task<DnsSecValidationResult> ValidateAsync<TRecord>(DomainName name, RecordType recordType, RecordClass recordClass, DnsMessage msg, List<TRecord> resultRecords, TState state, CancellationToken token)
where TRecord : DnsRecordBase
{
List<RrSigRecord> rrSigRecords = msg
.AnswerRecords.OfType<RrSigRecord>()
.Union(msg.AuthorityRecords.OfType<RrSigRecord>())
.Where(x => name.IsEqualOrSubDomainOf(x.SignersName) && (x.SignatureInception <= DateTime.Now) && (x.SignatureExpiration >= DateTime.Now)).ToList();
if (rrSigRecords.Count == 0)
{
return await ValidateOptOut(name, recordClass, state, token) ? DnsSecValidationResult.Unsigned : DnsSecValidationResult.Bogus;
}
DomainName zoneApex = rrSigRecords.OrderByDescending(x => x.Labels).First().SignersName;
if (resultRecords.Count != 0)
return await ValidateRrSigAsync(name, recordType, recordClass, resultRecords, rrSigRecords, zoneApex, msg, state, token);
return await ValidateNonExistenceAsync(name, recordType, recordClass, rrSigRecords, DomainName.Asterisk + zoneApex, zoneApex, msg, state, token);
}
private async Task<bool> ValidateOptOut(DomainName name, RecordClass recordClass, TState state, CancellationToken token)
{
while (name != DomainName.Root)
{
DnsMessage msg = await _resolver.ResolveMessageAsync(name, RecordType.Ds, recordClass, state, token);
if ((msg == null) || ((msg.ReturnCode != ReturnCode.NoError) && (msg.ReturnCode != ReturnCode.NxDomain)))
{
throw new Exception("DNS request failed");
}
List<RrSigRecord> rrSigRecords = msg
.AnswerRecords.OfType<RrSigRecord>()
.Union(msg.AuthorityRecords.OfType<RrSigRecord>())
.Where(x => name.IsEqualOrSubDomainOf(x.SignersName) && (x.SignatureInception <= DateTime.Now) && (x.SignatureExpiration >= DateTime.Now)).ToList();
if (rrSigRecords.Count != 0)
{
DomainName zoneApex = rrSigRecords.OrderByDescending(x => x.Labels).First().SignersName;
var nonExistenceValidation = await ValidateNonExistenceAsync(name, RecordType.Ds, recordClass, rrSigRecords, name, zoneApex, msg, state, token);
if ((nonExistenceValidation != DnsSecValidationResult.Bogus) && (nonExistenceValidation != DnsSecValidationResult.Indeterminate))
return true;
}
name = name.GetParentName();
}
return false;
}
private async Task<DnsSecValidationResult> ValidateNonExistenceAsync(DomainName name, RecordType recordType, RecordClass recordClass, List<RrSigRecord> rrSigRecords, DomainName stop, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
{
var nsecRes = await ValidateNSecAsync(name, recordType, recordClass, rrSigRecords, stop, zoneApex, msg, state, token);
if (nsecRes == DnsSecValidationResult.Signed)
return nsecRes;
var nsec3Res = await ValidateNSec3Async(name, recordType, recordClass, rrSigRecords, stop == DomainName.Asterisk + zoneApex, zoneApex, msg, state, token);
if (nsec3Res == DnsSecValidationResult.Signed)
return nsec3Res;
if ((nsecRes == DnsSecValidationResult.Unsigned) || (nsec3Res == DnsSecValidationResult.Unsigned))
return DnsSecValidationResult.Unsigned;
if ((nsecRes == DnsSecValidationResult.Bogus) || (nsec3Res == DnsSecValidationResult.Bogus))
return DnsSecValidationResult.Bogus;
return DnsSecValidationResult.Indeterminate;
}
private async Task<DnsSecValidationResult> ValidateNSecAsync(DomainName name, RecordType recordType, RecordClass recordClass, List<RrSigRecord> rrSigRecords, DomainName stop, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
{
List<NSecRecord> nsecRecords = msg.AuthorityRecords.OfType<NSecRecord>().ToList();
if (nsecRecords.Count == 0)
return DnsSecValidationResult.Indeterminate;
foreach (var nsecGroup in nsecRecords.GroupBy(x => x.Name))
{
DnsSecValidationResult validationResult = await ValidateRrSigAsync(nsecGroup.Key, RecordType.NSec, recordClass, nsecGroup.ToList(), rrSigRecords, zoneApex, msg, state, token);
if (validationResult != DnsSecValidationResult.Signed)
return validationResult;
}
DomainName current = name;
while (true)
{
if (current.Equals(stop))
{
return DnsSecValidationResult.Signed;
}
NSecRecord nsecRecord = nsecRecords.FirstOrDefault(x => x.Name.Equals(current));
if (nsecRecord != null)
{
return nsecRecord.Types.Contains(recordType) ? DnsSecValidationResult.Bogus : DnsSecValidationResult.Signed;
}
else
{
nsecRecord = nsecRecords.FirstOrDefault(x => x.IsCovering(current, zoneApex));
if (nsecRecord == null)
return DnsSecValidationResult.Bogus;
}
current = DomainName.Asterisk + current.GetParentName(current.Labels[0] == "*" ? 2 : 1);
}
}
private async Task<DnsSecValidationResult> ValidateNSec3Async(DomainName name, RecordType recordType, RecordClass recordClass, List<RrSigRecord> rrSigRecords, bool checkWildcard, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
{
List<NSec3Record> nsecRecords = msg.AuthorityRecords.OfType<NSec3Record>().ToList();
if (nsecRecords.Count == 0)
return DnsSecValidationResult.Indeterminate;
foreach (var nsecGroup in nsecRecords.GroupBy(x => x.Name))
{
DnsSecValidationResult validationResult = await ValidateRrSigAsync(nsecGroup.Key, RecordType.NSec3, recordClass, nsecGroup.ToList(), rrSigRecords, zoneApex, msg, state, token);
if (validationResult != DnsSecValidationResult.Signed)
return validationResult;
}
var nsec3Parameter = nsecRecords.Where(x => x.Name.GetParentName().Equals(zoneApex)).Where(x => x.HashAlgorithm.IsSupported()).Select(x => new { x.HashAlgorithm, x.Iterations, x.Salt }).OrderBy(x => x.HashAlgorithm.GetPriority()).First();
DomainName hashedName = name.GetNsec3HashName(nsec3Parameter.HashAlgorithm, nsec3Parameter.Iterations, nsec3Parameter.Salt, zoneApex);
if (recordType == RecordType.Ds && nsecRecords.Any(x => (x.Flags == 1) && (x.IsCovering(hashedName))))
return DnsSecValidationResult.Unsigned;
var directMatch = nsecRecords.FirstOrDefault(x => x.Name.Equals(hashedName));
if (directMatch != null)
{
return directMatch.Types.Contains(recordType) ? DnsSecValidationResult.Bogus : DnsSecValidationResult.Signed;
}
// find closest encloser
DomainName current = name;
DomainName previousHashedName = hashedName;
while (true)
{
if (nsecRecords.Any(x => x.Name == hashedName))
break;
if (current == zoneApex)
return DnsSecValidationResult.Bogus; // closest encloser could not be found, but at least the zone apex must be found as
current = current.GetParentName();
previousHashedName = hashedName;
hashedName = current.GetNsec3HashName(nsec3Parameter.HashAlgorithm, nsec3Parameter.Iterations, nsec3Parameter.Salt, zoneApex);
}
if (!nsecRecords.Any(x => x.IsCovering(previousHashedName)))
return DnsSecValidationResult.Bogus;
if (checkWildcard)
{
DomainName wildcardHashName = (DomainName.Asterisk + current).GetNsec3HashName(nsec3Parameter.HashAlgorithm, nsec3Parameter.Iterations, nsec3Parameter.Salt, zoneApex);
var wildcardDirectMatch = nsecRecords.FirstOrDefault(x => x.Name.Equals(wildcardHashName));
if ((wildcardDirectMatch != null) && (!wildcardDirectMatch.Types.Contains(recordType)))
return wildcardDirectMatch.Types.Contains(recordType) ? DnsSecValidationResult.Bogus : DnsSecValidationResult.Signed;
var wildcardCoveringMatch = nsecRecords.FirstOrDefault(x => x.IsCovering(wildcardHashName));
return (wildcardCoveringMatch != null) ? DnsSecValidationResult.Signed : DnsSecValidationResult.Bogus;
}
else
{
return DnsSecValidationResult.Signed;
}
}
private async Task<DnsSecValidationResult> ValidateRrSigAsync<TRecord>(DomainName name, RecordType recordType, RecordClass recordClass, List<TRecord> resultRecords, List<RrSigRecord> rrSigRecords, DomainName zoneApex, DnsMessageBase msg, TState state, CancellationToken token)
where TRecord : DnsRecordBase
{
DnsSecValidationResult res = DnsSecValidationResult.Bogus;
foreach (var record in rrSigRecords.Where(x => x.Name.Equals(name) && (x.TypeCovered == recordType)))
{
res = await VerifyAsync(record, resultRecords, recordClass, state, token);
if (res == DnsSecValidationResult.Signed)
{
if ((record.Labels == name.LabelCount)
|| ((name.Labels[0] == "*") && (record.Labels == name.LabelCount - 1)))
return DnsSecValidationResult.Signed;
if (await ValidateNonExistenceAsync(name, recordType, recordClass, rrSigRecords, DomainName.Asterisk + record.Name.GetParentName(record.Name.LabelCount - record.Labels), zoneApex, msg, state, token) == DnsSecValidationResult.Signed)
return DnsSecValidationResult.Signed;
}
}
return res;
}
private async Task<DnsSecValidationResult> VerifyAsync<TRecord>(RrSigRecord rrSigRecord, List<TRecord> coveredRecords, RecordClass recordClass, TState state, CancellationToken token)
where TRecord : DnsRecordBase
{
if (rrSigRecord.TypeCovered == RecordType.DnsKey)
{
List<DsRecord> dsRecords;
if (rrSigRecord.SignersName.Equals(DomainName.Root))
{
dsRecords = _resolverHintStore.RootKeys;
}
else
{
var dsRecordResults = await _resolver.ResolveSecureAsync<DsRecord>(rrSigRecord.SignersName, RecordType.Ds, recordClass, state, token);
if ((dsRecordResults.ValidationResult == DnsSecValidationResult.Bogus) || (dsRecordResults.ValidationResult == DnsSecValidationResult.Indeterminate))
throw new DnsSecValidationException("DS records could not be retrieved");
if (dsRecordResults.ValidationResult == DnsSecValidationResult.Unsigned)
return DnsSecValidationResult.Unsigned;
dsRecords = dsRecordResults.Records;
}
return dsRecords.Any(dsRecord => rrSigRecord.Verify(coveredRecords, coveredRecords.Cast<DnsKeyRecord>().Where(dsRecord.IsCovering).ToList())) ? DnsSecValidationResult.Signed : DnsSecValidationResult.Bogus;
}
else
{
var dnsKeyRecordResults = await _resolver.ResolveSecureAsync<DnsKeyRecord>(rrSigRecord.SignersName, RecordType.DnsKey, recordClass, state, token);
if ((dnsKeyRecordResults.ValidationResult == DnsSecValidationResult.Bogus) || (dnsKeyRecordResults.ValidationResult == DnsSecValidationResult.Indeterminate))
throw new DnsSecValidationException("DNSKEY records could not be retrieved");
if (dnsKeyRecordResults.ValidationResult == DnsSecValidationResult.Unsigned)
return DnsSecValidationResult.Unsigned;
return rrSigRecord.Verify(coveredRecords, dnsKeyRecordResults.Records) ? DnsSecValidationResult.Signed : DnsSecValidationResult.Bogus;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Text
{
internal static class InvariantUtf8IntegerFormatter
{
private const byte Minus = (byte)'-';
private const byte Period = (byte)'.';
private const byte Seperator = (byte)',';
// Invariant formatting uses groups of 3 for each number group seperated by commas.
// ex. 1,234,567,890
private const int GroupSize = 3;
public static bool TryFormatDecimalInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int bytesNeeded = digitCount + (int)((value >> 63) & 1);
if (buffer.Length < bytesNeeded)
{
bytesWritten = 0;
return false;
}
ref byte utf8Bytes = ref buffer.DangerousGetPinnableReference();
int idx = 0;
if (value < 0)
{
Unsafe.Add(ref utf8Bytes, idx++) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (value == long.MinValue)
{
if (!TryFormatDecimalUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(1), out bytesWritten))
return false;
bytesWritten += 1; // Add the minus sign
return true;
}
value = -value;
}
if (precision != ParsedFormat.NoPrecision)
{
int leadingZeros = (int)precision - digitCount;
while (leadingZeros-- > 0)
Unsafe.Add(ref utf8Bytes, idx++) = (byte)'0';
}
idx += FormattingHelpers.WriteDigits(value, digitCount, ref utf8Bytes, idx);
bytesWritten = idx;
return true;
}
public static bool TryFormatDecimalUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten);
// Remove a single digit from the number. This will get it below long.MaxValue
// Then we call the faster long version and follow-up with writing the last
// digit. This ends up being faster by a factor of 2 than to just do the entire
// operation using the unsigned versions.
value = FormattingHelpers.DivMod(value, 10, out ulong lastDigit);
if (precision != ParsedFormat.NoPrecision && precision > 0)
precision -= 1;
if (!TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten))
return false;
if (buffer.Length - 1 < bytesWritten)
{
bytesWritten = 0;
return false;
}
ref byte utf8Bytes = ref buffer.DangerousGetPinnableReference();
bytesWritten += FormattingHelpers.WriteDigits(lastDigit, 1, ref utf8Bytes, bytesWritten);
return true;
}
public static bool TryFormatNumericInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int groupSeperators = (int)FormattingHelpers.DivMod(digitCount, GroupSize, out long firstGroup);
if (firstGroup == 0)
{
firstGroup = 3;
groupSeperators--;
}
int trailingZeros = (precision == ParsedFormat.NoPrecision) ? 2 : precision;
int idx = (int)((value >> 63) & 1) + digitCount + groupSeperators;
bytesWritten = idx;
if (trailingZeros > 0)
bytesWritten += trailingZeros + 1; // +1 for period.
if (buffer.Length < bytesWritten)
{
bytesWritten = 0;
return false;
}
ref byte utf8Bytes = ref buffer.DangerousGetPinnableReference();
long v = value;
if (v < 0)
{
Unsafe.Add(ref utf8Bytes, 0) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (v == long.MinValue)
{
if (!TryFormatNumericUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(1), out bytesWritten))
return false;
bytesWritten += 1; // Add the minus sign
return true;
}
v = -v;
}
// Write out the trailing zeros
if (trailingZeros > 0)
{
Unsafe.Add(ref utf8Bytes, idx) = Period;
FormattingHelpers.WriteDigits(0, trailingZeros, ref utf8Bytes, idx + 1);
}
// Starting from the back, write each group of digits except the first group
while (digitCount > 3)
{
digitCount -= 3;
idx -= 3;
v = FormattingHelpers.DivMod(v, 1000, out long groupValue);
FormattingHelpers.WriteDigits(groupValue, 3, ref utf8Bytes, idx);
Unsafe.Add(ref utf8Bytes, --idx) = Seperator;
}
// Write the first group of digits.
FormattingHelpers.WriteDigits(v, (int)firstGroup, ref utf8Bytes, idx - (int)firstGroup);
return true;
}
public static bool TryFormatNumericUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatNumericInt64((long)value, precision, buffer, out bytesWritten);
// The ulong path is much slower than the long path here, so we are doing the last group
// inside this method plus the zero padding but routing to the long version for the rest.
value = FormattingHelpers.DivMod(value, 1000, out ulong lastGroup);
if (!TryFormatNumericInt64((long)value, 0, buffer, out bytesWritten))
return false;
if (precision == ParsedFormat.NoPrecision)
precision = 2;
int idx = bytesWritten;
// Since this method routes entirely to the long version if the number is smaller than
// long.MaxValue, we are guaranteed to need to write 3 more digits here before the set
// of trailing zeros.
bytesWritten += 4; // 3 digits + group seperator
if (precision > 0)
bytesWritten += precision + 1; // +1 for period.
if (buffer.Length < bytesWritten)
{
bytesWritten = 0;
return false;
}
ref byte utf8Bytes = ref buffer.DangerousGetPinnableReference();
// Write the last group
Unsafe.Add(ref utf8Bytes, idx++) = Seperator;
idx += FormattingHelpers.WriteDigits(lastGroup, 3, ref utf8Bytes, idx);
// Write out the trailing zeros
if (precision > 0)
{
Unsafe.Add(ref utf8Bytes, idx) = Period;
FormattingHelpers.WriteDigits(0, precision, ref utf8Bytes, idx + 1);
}
return true;
}
public static bool TryFormatHexUInt64(ulong value, byte precision, bool useLower, Span<byte> buffer, out int bytesWritten)
{
const string HexTableLower = "0123456789abcdef";
const string HexTableUpper = "0123456789ABCDEF";
var digits = 1;
var v = value;
if (v > 0xFFFFFFFF)
{
digits += 8;
v >>= 0x20;
}
if (v > 0xFFFF)
{
digits += 4;
v >>= 0x10;
}
if (v > 0xFF)
{
digits += 2;
v >>= 0x8;
}
if (v > 0xF) digits++;
int paddingCount = (precision == ParsedFormat.NoPrecision) ? 0 : precision - digits;
if (paddingCount < 0) paddingCount = 0;
bytesWritten = digits + paddingCount;
if (buffer.Length < bytesWritten)
{
bytesWritten = 0;
return false;
}
string hexTable = useLower ? HexTableLower : HexTableUpper;
ref byte utf8Bytes = ref buffer.DangerousGetPinnableReference();
int idx = bytesWritten;
for (v = value; digits-- > 0; v >>= 4)
Unsafe.Add(ref utf8Bytes, --idx) = (byte)hexTable[(int)(v & 0xF)];
while (paddingCount-- > 0)
Unsafe.Add(ref utf8Bytes, --idx) = (byte)'0';
return true;
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
namespace Orleans
{
internal static class OrleansTaskExtentions
{
internal static readonly Task<object> CanceledTask = TaskFromCanceled<object>();
internal static readonly Task<object> CompletedTask = Task.FromResult(default(object));
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task"/>.
/// </summary>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask(this Task task)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return CompletedTask;
case TaskStatus.Faulted:
return TaskFromFaulted(task);
case TaskStatus.Canceled:
return CanceledTask;
default:
return ConvertAsync(task);
}
async Task<object> ConvertAsync(Task asyncTask)
{
await asyncTask;
return null;
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>.
/// </summary>
/// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask<T>(this Task<T> task)
{
if (typeof(T) == typeof(object))
return task as Task<object>;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((object)GetResult(task));
case TaskStatus.Faulted:
return TaskFromFaulted(task);
case TaskStatus.Canceled:
return CanceledTask;
default:
return ConvertAsync(task);
}
async Task<object> ConvertAsync(Task<T> asyncTask)
{
return await asyncTask.ConfigureAwait(false);
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>.
/// </summary>
/// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam>
/// <param name="task">The task.</param>
internal static Task<T> ToTypedTask<T>(this Task<object> task)
{
if (typeof(T) == typeof(object))
return task as Task<T>;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((T)GetResult(task));
case TaskStatus.Faulted:
return TaskFromFaulted<T>(task);
case TaskStatus.Canceled:
return TaskFromCanceled<T>();
default:
return ConvertAsync(task);
}
async Task<T> ConvertAsync(Task<object> asyncTask)
{
var result = await asyncTask.ConfigureAwait(false);
if (result is null)
{
if (!NullabilityHelper<T>.IsNullableType)
{
ThrowInvalidTaskResultType(typeof(T));
}
return default;
}
return (T)result;
}
}
private static class NullabilityHelper<T>
{
/// <summary>
/// True if <typeparamref name="T" /> is an instance of a nullable type (a reference type or <see cref="Nullable{T}"/>), otherwise false.
/// </summary>
public static readonly bool IsNullableType = !typeof(T).IsValueType || typeof(T).IsConstructedGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidTaskResultType(Type type)
{
var message = $"Expected result of type {type} but encountered a null value. This may be caused by a grain call filter swallowing an exception.";
throw new InvalidOperationException(message);
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{Object}"/>.
/// </summary>
/// <param name="task">The task.</param>
public static Task<object> ToUntypedTask(this Task<object> task)
{
return task;
}
private static Task<object> TaskFromFaulted(Task task)
{
var completion = new TaskCompletionSource<object>();
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
private static Task<T> TaskFromFaulted<T>(Task task)
{
var completion = new TaskCompletionSource<T>();
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
private static Task<T> TaskFromCanceled<T>()
{
var completion = new TaskCompletionSource<T>();
completion.SetCanceled();
return completion.Task;
}
public static async Task LogException(this Task task, ILogger logger, ErrorCode errorCode, string message)
{
try
{
await task;
}
catch (Exception exc)
{
var ignored = task.Exception; // Observe exception
logger.Error(errorCode, message, exc);
throw;
}
}
// Executes an async function such as Exception is never thrown but rather always returned as a broken task.
public static async Task SafeExecute(Func<Task> action)
{
await action();
}
public static async Task ExecuteAndIgnoreException(Func<Task> action)
{
try
{
await action();
}
catch (Exception)
{
// dont re-throw, just eat it.
}
}
internal static String ToString(this Task t)
{
return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status));
}
internal static String ToString<T>(this Task<T> t)
{
return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status));
}
internal static void WaitWithThrow(this Task task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException($"Task.WaitWithThrow has timed out after {timeout}.");
}
}
internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException($"Task<T>.WaitForResultWithThrow has timed out after {timeout}.");
}
return task.Result;
}
/// <summary>
/// This will apply a timeout delay to the task, allowing us to exit early
/// </summary>
/// <param name="taskToComplete">The task we will timeout after timeSpan</param>
/// <param name="timeout">Amount of time to wait before timing out</param>
/// <param name="exceptionMessage">Text to put into the timeout exception message</param>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The completed task</returns>
public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout, string exceptionMessage = null)
{
if (taskToComplete.IsCompleted)
{
await taskToComplete;
return;
}
var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
// We got done before the timeout, or were able to complete before this code ran, return the result
if (taskToComplete == completedTask)
{
timeoutCancellationTokenSource.Cancel();
// Await this so as to propagate the exception correctly
await taskToComplete;
return;
}
// We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur
taskToComplete.Ignore();
var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeout}";
throw new TimeoutException(errorMessage);
}
/// <summary>
/// This will apply a timeout delay to the task, allowing us to exit early
/// </summary>
/// <param name="taskToComplete">The task we will timeout after timeSpan</param>
/// <param name="timeSpan">Amount of time to wait before timing out</param>
/// <param name="exceptionMessage">Text to put into the timeout exception message</param>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The value of the completed task</returns>
public static async Task<T> WithTimeout<T>(this Task<T> taskToComplete, TimeSpan timeSpan, string exceptionMessage = null)
{
if (taskToComplete.IsCompleted)
{
return await taskToComplete;
}
var timeoutCancellationTokenSource = new CancellationTokenSource();
var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeSpan, timeoutCancellationTokenSource.Token));
// We got done before the timeout, or were able to complete before this code ran, return the result
if (taskToComplete == completedTask)
{
timeoutCancellationTokenSource.Cancel();
// Await this so as to propagate the exception correctly
return await taskToComplete;
}
// We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur
taskToComplete.Ignore();
var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeSpan}";
throw new TimeoutException(errorMessage);
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <param name="message">Message to set in the exception</param>
/// <returns></returns>
internal static async Task WithCancellation(
this Task taskToComplete,
CancellationToken cancellationToken,
string message)
{
try
{
await taskToComplete.WithCancellation(cancellationToken);
}
catch (TaskCanceledException ex)
{
throw new TaskCanceledException(message, ex);
}
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <returns></returns>
internal static Task WithCancellation(this Task taskToComplete, CancellationToken cancellationToken)
{
if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled)
{
return taskToComplete;
}
else if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<object>(cancellationToken);
}
else
{
return MakeCancellable(taskToComplete, cancellationToken);
}
}
private static async Task MakeCancellable(Task task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<object>();
using (cancellationToken.Register(() =>
tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false))
{
var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (firstToComplete != task)
{
task.Ignore();
}
await firstToComplete.ConfigureAwait(false);
}
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <param name="message">Message to set in the exception</param>
/// <returns></returns>
internal static async Task<T> WithCancellation<T>(
this Task<T> taskToComplete,
CancellationToken cancellationToken,
string message)
{
try
{
return await taskToComplete.WithCancellation(cancellationToken);
}
catch (TaskCanceledException ex)
{
throw new TaskCanceledException(message, ex);
}
}
/// <summary>
/// For making an uncancellable task cancellable, by ignoring its result.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="taskToComplete">The task to wait for unless cancelled</param>
/// <param name="cancellationToken">A cancellation token for cancelling the wait</param>
/// <returns></returns>
internal static Task<T> WithCancellation<T>(this Task<T> taskToComplete, CancellationToken cancellationToken)
{
if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled)
{
return taskToComplete;
}
else if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<T>(cancellationToken);
}
else
{
return MakeCancellable(taskToComplete, cancellationToken);
}
}
private static async Task<T> MakeCancellable<T>(Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<T>();
using (cancellationToken.Register(() =>
tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false))
{
var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (firstToComplete != task)
{
task.Ignore();
}
return await firstToComplete.ConfigureAwait(false);
}
}
internal static Task WrapInTask(Action action)
{
try
{
action();
return Task.CompletedTask;
}
catch (Exception exc)
{
return Task.FromException<object>(exc);
}
}
internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task)
{
if (task == null) return Task.FromResult(default(T));
var resolver = new TaskCompletionSource<T>();
if (task.Status == TaskStatus.RanToCompletion)
{
resolver.TrySetResult(task.Result);
}
else if (task.IsFaulted)
{
resolver.TrySetException(task.Exception.InnerExceptions);
}
else if (task.IsCanceled)
{
resolver.TrySetException(new TaskCanceledException(task));
}
else
{
if (task.Status == TaskStatus.Created) task.Start();
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
resolver.TrySetException(t.Exception.InnerExceptions);
}
else if (t.IsCanceled)
{
resolver.TrySetException(new TaskCanceledException(t));
}
else
{
resolver.TrySetResult(t.GetResult());
}
});
}
return resolver.Task;
}
//The rationale for GetAwaiter().GetResult() instead of .Result
//is presented at https://github.com/aspnet/Security/issues/59.
internal static T GetResult<T>(this Task<T> task)
{
return task.GetAwaiter().GetResult();
}
internal static void GetResult(this Task task)
{
task.GetAwaiter().GetResult();
}
internal static Task WhenCancelled(this CancellationToken token)
{
if (token.IsCancellationRequested)
{
return Task.CompletedTask;
}
var waitForCancellation = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
token.Register(obj =>
{
var tcs = (TaskCompletionSource<object>)obj;
tcs.TrySetResult(null);
}, waitForCancellation);
return waitForCancellation.Task;
}
}
}
namespace Orleans
{
/// <summary>
/// A special void 'Done' Task that is already in the RunToCompletion state.
/// Equivalent to Task.FromResult(1).
/// </summary>
public static class TaskDone
{
/// <summary>
/// A special 'Done' Task that is already in the RunToCompletion state
/// </summary>
[Obsolete("Use Task.CompletedTask")]
public static Task Done => Task.CompletedTask;
}
}
| |
/*
* 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 OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
public struct WearableItem
{
public UUID ItemID;
public UUID AssetID;
public WearableItem(UUID itemID, UUID assetID)
{
ItemID = itemID;
AssetID = assetID;
}
}
public class AvatarWearable
{
// these are guessed at by the list here -
// http://wiki.secondlife.com/wiki/Avatar_Appearance. We'll
// correct them over time for when were are wrong.
public static readonly int BODY = 0;
public static readonly int SKIN = 1;
public static readonly int HAIR = 2;
public static readonly int EYES = 3;
public static readonly int SHIRT = 4;
public static readonly int PANTS = 5;
public static readonly int SHOES = 6;
public static readonly int SOCKS = 7;
public static readonly int JACKET = 8;
public static readonly int GLOVES = 9;
public static readonly int UNDERSHIRT = 10;
public static readonly int UNDERPANTS = 11;
public static readonly int SKIRT = 12;
public static readonly int MAX_BASICWEARABLES = 13;
public static readonly int ALPHA = 13;
public static readonly int TATTOO = 14;
public static readonly int LEGACY_VERSION_MAX_WEARABLES = 15;
// public static readonly int PHYSICS = 15;
// public static int MAX_WEARABLES = 16;
public static readonly UUID DEFAULT_BODY_ITEM = new UUID("66c41e39-38f9-f75a-024e-585989bfaba9");
public static readonly UUID DEFAULT_BODY_ASSET = new UUID("66c41e39-38f9-f75a-024e-585989bfab73");
public static readonly UUID DEFAULT_HAIR_ITEM = new UUID("d342e6c1-b9d2-11dc-95ff-0800200c9a66");
public static readonly UUID DEFAULT_HAIR_ASSET = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66");
public static readonly UUID DEFAULT_SKIN_ITEM = new UUID("77c41e39-38f9-f75a-024e-585989bfabc9");
public static readonly UUID DEFAULT_SKIN_ASSET = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb");
public static readonly UUID DEFAULT_EYES_ITEM = new UUID("cdc31054-eed8-4021-994f-4e0c6e861b50");
public static readonly UUID DEFAULT_EYES_ASSET = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7");
public static readonly UUID DEFAULT_SHIRT_ITEM = new UUID("77c41e39-38f9-f75a-0000-585989bf0000");
public static readonly UUID DEFAULT_SHIRT_ASSET = new UUID("00000000-38f9-1111-024e-222222111110");
public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111");
public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120");
public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8");
public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594");
public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1");
public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007");
protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>();
protected List<UUID> m_ids = new List<UUID>();
public AvatarWearable()
{
}
public AvatarWearable(UUID itemID, UUID assetID)
{
Wear(itemID, assetID);
}
public AvatarWearable(OSDArray args)
{
Unpack(args);
}
public OSD Pack()
{
OSDArray wearlist = new OSDArray();
foreach (UUID id in m_ids)
{
OSDMap weardata = new OSDMap();
weardata["item"] = OSD.FromUUID(id);
weardata["asset"] = OSD.FromUUID(m_items[id]);
wearlist.Add(weardata);
}
return wearlist;
}
public void Unpack(OSDArray args)
{
Clear();
foreach (OSDMap weardata in args)
{
Add(weardata["item"].AsUUID(), weardata["asset"].AsUUID());
}
}
public int Count
{
get { return m_ids.Count; }
}
public void Add(UUID itemID, UUID assetID)
{
if (itemID == UUID.Zero)
return;
if (m_items.ContainsKey(itemID))
{
m_items[itemID] = assetID;
return;
}
if (m_ids.Count >= 5)
return;
m_ids.Add(itemID);
m_items[itemID] = assetID;
}
public void Wear(WearableItem item)
{
Wear(item.ItemID, item.AssetID);
}
public void Wear(UUID itemID, UUID assetID)
{
Clear();
Add(itemID, assetID);
}
public void Clear()
{
m_ids.Clear();
m_items.Clear();
}
public void RemoveItem(UUID itemID)
{
if (m_items.ContainsKey(itemID))
{
m_ids.Remove(itemID);
m_items.Remove(itemID);
}
}
public void RemoveAsset(UUID assetID)
{
UUID itemID = UUID.Zero;
foreach (KeyValuePair<UUID, UUID> kvp in m_items)
{
if (kvp.Value == assetID)
{
itemID = kvp.Key;
break;
}
}
if (itemID != UUID.Zero)
{
m_ids.Remove(itemID);
m_items.Remove(itemID);
}
}
public WearableItem this [int idx]
{
get
{
if (idx >= m_ids.Count || idx < 0)
return new WearableItem(UUID.Zero, UUID.Zero);
return new WearableItem(m_ids[idx], m_items[m_ids[idx]]);
}
}
public UUID GetAsset(UUID itemID)
{
if (!m_items.ContainsKey(itemID))
return UUID.Zero;
return m_items[itemID];
}
public static AvatarWearable[] DefaultWearables
{
get
{
// We use the legacy count here because this is just a fallback anyway
AvatarWearable[] defaultWearables = new AvatarWearable[LEGACY_VERSION_MAX_WEARABLES];
for (int i = 0; i < LEGACY_VERSION_MAX_WEARABLES; i++)
{
defaultWearables[i] = new AvatarWearable();
}
// Body
defaultWearables[BODY].Add(DEFAULT_BODY_ITEM, DEFAULT_BODY_ASSET);
// Hair
defaultWearables[HAIR].Add(DEFAULT_HAIR_ITEM, DEFAULT_HAIR_ASSET);
// Skin
defaultWearables[SKIN].Add(DEFAULT_SKIN_ITEM, DEFAULT_SKIN_ASSET);
// Eyes
defaultWearables[EYES].Add(DEFAULT_EYES_ITEM, DEFAULT_EYES_ASSET);
// Shirt
defaultWearables[SHIRT].Add(DEFAULT_SHIRT_ITEM, DEFAULT_SHIRT_ASSET);
// Pants
defaultWearables[PANTS].Add(DEFAULT_PANTS_ITEM, DEFAULT_PANTS_ASSET);
// // Alpha
// defaultWearables[ALPHA].Add(DEFAULT_ALPHA_ITEM, DEFAULT_ALPHA_ASSET);
// // Tattoo
// defaultWearables[TATTOO].Add(DEFAULT_TATTOO_ITEM, DEFAULT_TATTOO_ASSET);
// // Physics
// defaultWearables[PHYSICS].Add(DEFAULT_TATTOO_ITEM, DEFAULT_TATTOO_ASSET);
return defaultWearables;
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Text.RegularExpressions;
using Mercurial.Attributes;
namespace Mercurial
{
/// <summary>
/// This class implements the "hg bisect" command (<see href="http://www.selenic.com/mercurial/hg.1.html#bisect"/>):
/// subdivision search of changesets.
/// </summary>
/// <remarks>
/// <para>The <see cref="BisectCommand"/> should be used by first updating the repository to a changeset
/// where the current state is known to be bad or good, and then updated to another changeset were the
/// current state is known to be the opposite of the previous changeset. Then the <see cref="BisectCommand"/>
/// should be iteratively executed, analyzing the <see cref="BisectCommand.Result"/> property each time.</para>
/// <para>When the <see cref="BisectResult"/> object in that property says <see cref="BisectResult.Done"/> = <c>false</c>,
/// then the repository has been updated to a new changeset. The program should then analyze the changeset and determine
/// if its state is good or bad, and issue another <see cref="BisectCommand"/> to that effect.</para>
/// <para>When the <see cref="BisectResult"/> says that <see cref="BisectResult.Done"/> = <c>true</c>,
/// the <see cref="BisectResult.Revision"/> property contains the revspec of the first changeset that is
/// deemed good or bad, depending on what you're looking for.</para>
/// </remarks>
public sealed class BisectCommand : MercurialCommandBase<BisectCommand>, IMercurialCommand<BisectResult>
{
/// <summary>
/// This is the backing field for the <see cref="TestCommand"/> property.
/// </summary>
private string _TestCommand = string.Empty;
/// <summary>
/// This is the backing field for the <see cref="State"/> property.
/// </summary>
private BisectState _State = BisectState.None;
/// <summary>
/// This is the backing field for the <see cref="Update"/> property.
/// </summary>
private bool _Update = true;
/// <summary>
/// Initializes a new instance of the <see cref="BisectCommand"/> class.
/// </summary>
public BisectCommand()
: base("bisect")
{
}
/// <summary>
/// Gets or sets a value specifying how to proceed with the bisect command, by marking
/// the current changeset good or bad.
/// </summary>
[EnumArgument(BisectState.Skip, "--skip")]
[EnumArgument(BisectState.Good, "--good")]
[EnumArgument(BisectState.Bad, "--bad")]
[EnumArgument(BisectState.Reset, "--reset")]
[DefaultValue(BisectState.None)]
public BisectState State
{
get
{
return _State;
}
set
{
_State = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether to update to target revision.
/// Default value is <c>true</c>.
/// </summary>
[BooleanArgument(FalseOption = "--noupdate")]
[DefaultValue(true)]
public bool Update
{
get
{
return _Update;
}
set
{
_Update = value;
}
}
/// <summary>
/// Gets or sets the command to execute from Mercurial in order to test each changeset,
/// doing an automated search instead of one controlled by the program using Mercurial.Net.
/// </summary>
[DefaultValue("")]
public string TestCommand
{
get
{
return _TestCommand;
}
set
{
_TestCommand = (value ?? string.Empty).Trim();
}
}
/// <summary>
/// Validates the command configuration. This method should throw the necessary
/// exceptions to signal missing or incorrect configuration (like attempting to
/// add files to the repository without specifying which files to add.)
/// </summary>
/// <exception cref="InvalidOperationException">The State property must be set to something other than None before executing a BisectCommand</exception>
public override void Validate()
{
base.Validate();
if (State == BisectState.None)
throw new InvalidOperationException("The State property must be set to something other than None before executing a BisectCommand");
}
/// <summary>
/// Sets the <see cref="State"/> property to the specified value and
/// returns this <see cref="BisectCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="State"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="BisectCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public BisectCommand WithState(BisectState value)
{
State = value;
return this;
}
/// <summary>
/// Sets the <see cref="Update"/> property to the specified value and
/// returns this <see cref="BisectCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Update"/> property,
/// defaults to <c>true</c>.
/// </param>
/// <returns>
/// This <see cref="BisectCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public BisectCommand WithUpdate(bool value)
{
Update = value;
return this;
}
/// <summary>
/// This method should parse and store the appropriate execution result output
/// according to the type of data the command line client would return for
/// the command.
/// </summary>
/// <param name="exitCode">
/// The exit code from executing the command line client.
/// </param>
/// <param name="standardOutput">
/// The standard output from executing the command line client.
/// </param>
/// <exception cref="MercurialResultParsingException">
/// <para>There was an error in the output from executing the command; the text did not match any of the known patterns.</para>
/// </exception>
protected override void ParseStandardOutputForResults(int exitCode, string standardOutput)
{
if (ParseEmptyResult(standardOutput))
return;
if (ParseTestingResult(standardOutput))
return;
if (ParseFoundResult(standardOutput))
return;
throw new MercurialResultParsingException(exitCode, "Unknown result returned from the bisect command", standardOutput);
}
/// <summary>
/// Attempts to parse the empty result, typically returned from executing a <see cref="BisectCommand"/>
/// with a <see cref="State"/> of <see cref="BisectState.Reset"/>.
/// </summary>
/// <param name="standardOutput">
/// The standard output from executing the command.
/// </param>
/// <returns>
/// <c>true</c> if this method was able to parse the results correctly;
/// otherwise <c>false</c> to continue testing other ways to parse it.
/// </returns>
private bool ParseEmptyResult(string standardOutput)
{
if (StringEx.IsNullOrWhiteSpace(standardOutput))
{
Result = new BisectResult();
return true;
}
return false;
}
/// <summary>
/// Attempts to parse the results that indicate that the first good changeset was found.
/// </summary>
/// <param name="standardOutput">
/// The standard output from executing the command.
/// </param>
/// <returns>
/// <c>true</c> if this method was able to parse the results correctly;
/// otherwise <c>false</c> to continue testing other ways to parse it.
/// </returns>
private bool ParseFoundResult(string standardOutput)
{
var re = new Regex(@"^The first good revision is:\s+changeset:\s+(?<revno>\d+):", RegexOptions.IgnoreCase);
Match ma = re.Match(standardOutput);
if (ma.Success)
{
int foundAtRevision = int.Parse(ma.Groups["revno"].Value, CultureInfo.InvariantCulture);
Result = new BisectResult(RevSpec.Single(foundAtRevision), true);
}
return ma.Success;
}
/// <summary>
/// Attempts to parse the results indicating that further testing is required and that the
/// repository has now been updated to a new revision for testing and subsequent marking of
/// good or bad.
/// </summary>
/// <param name="standardOutput">
/// The standard output from executing the command.
/// </param>
/// <returns>
/// <c>true</c> if this method was able to parse the results correctly;
/// otherwise <c>false</c> to continue testing other ways to parse it.
/// </returns>
private bool ParseTestingResult(string standardOutput)
{
var re = new Regex(@"^Testing changeset (?<revno>\d+):", RegexOptions.IgnoreCase);
Match ma = re.Match(standardOutput);
if (ma.Success)
{
int currentlyAtRevision = int.Parse(ma.Groups["revno"].Value, CultureInfo.InvariantCulture);
Result = new BisectResult(RevSpec.Single(currentlyAtRevision), false);
}
return ma.Success;
}
/// <summary>
/// Gets the result from the command line execution, as an appropriately typed value.
/// </summary>
public BisectResult Result
{
get;
private set;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Encapsulates initialization and shutdown of gRPC library.
/// </summary>
public class GrpcEnvironment
{
const int MinDefaultThreadPoolSize = 4;
const int DefaultBatchContextPoolSharedCapacity = 10000;
const int DefaultBatchContextPoolThreadLocalCapacity = 64;
const int DefaultRequestCallContextPoolSharedCapacity = 10000;
const int DefaultRequestCallContextPoolThreadLocalCapacity = 64;
static object staticLock = new object();
static GrpcEnvironment instance;
static int refCount;
static int? customThreadPoolSize;
static int? customCompletionQueueCount;
static bool inlineHandlers;
static int batchContextPoolSharedCapacity = DefaultBatchContextPoolSharedCapacity;
static int batchContextPoolThreadLocalCapacity = DefaultBatchContextPoolThreadLocalCapacity;
static int requestCallContextPoolSharedCapacity = DefaultRequestCallContextPoolSharedCapacity;
static int requestCallContextPoolThreadLocalCapacity = DefaultRequestCallContextPoolThreadLocalCapacity;
static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>();
static readonly HashSet<Server> registeredServers = new HashSet<Server>();
static ILogger logger = new LogLevelFilterLogger(new ConsoleLogger(), LogLevel.Off, true);
readonly IObjectPool<BatchContextSafeHandle> batchContextPool;
readonly IObjectPool<RequestCallContextSafeHandle> requestCallContextPool;
readonly GrpcThreadPool threadPool;
readonly DebugStats debugStats = new DebugStats();
readonly AtomicCounter cqPickerCounter = new AtomicCounter();
bool isShutdown;
/// <summary>
/// Returns a reference-counted instance of initialized gRPC environment.
/// Subsequent invocations return the same instance unless reference count has dropped to zero previously.
/// </summary>
internal static GrpcEnvironment AddRef()
{
ShutdownHooks.Register();
lock (staticLock)
{
refCount++;
if (instance == null)
{
instance = new GrpcEnvironment();
}
return instance;
}
}
/// <summary>
/// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero.
/// </summary>
internal static async Task ReleaseAsync()
{
GrpcEnvironment instanceToShutdown = null;
lock (staticLock)
{
GrpcPreconditions.CheckState(refCount > 0);
refCount--;
if (refCount == 0)
{
instanceToShutdown = instance;
instance = null;
}
}
if (instanceToShutdown != null)
{
await instanceToShutdown.ShutdownAsync().ConfigureAwait(false);
}
}
internal static int GetRefCount()
{
lock (staticLock)
{
return refCount;
}
}
internal static void RegisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
registeredChannels.Add(channel);
}
}
internal static void UnregisterChannel(Channel channel)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(channel);
GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set.");
}
}
internal static void RegisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
registeredServers.Add(server);
}
}
internal static void UnregisterServer(Server server)
{
lock (staticLock)
{
GrpcPreconditions.CheckNotNull(server);
GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set.");
}
}
/// <summary>
/// Requests shutdown of all channels created by the current process.
/// </summary>
public static Task ShutdownChannelsAsync()
{
HashSet<Channel> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Channel>(registeredChannels);
}
return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync()));
}
/// <summary>
/// Requests immediate shutdown of all servers created by the current process.
/// </summary>
public static Task KillServersAsync()
{
HashSet<Server> snapshot = null;
lock (staticLock)
{
snapshot = new HashSet<Server>(registeredServers);
}
return Task.WhenAll(snapshot.Select((server) => server.KillAsync()));
}
/// <summary>
/// Gets application-wide logger used by gRPC.
/// </summary>
/// <value>The logger.</value>
public static ILogger Logger
{
get
{
return logger;
}
}
/// <summary>
/// Sets the application-wide logger that should be used by gRPC.
/// </summary>
public static void SetLogger(ILogger customLogger)
{
GrpcPreconditions.CheckNotNull(customLogger, "customLogger");
logger = customLogger;
}
/// <summary>
/// Sets the number of threads in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetThreadPoolSize(int threadCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number");
customThreadPoolSize = threadCount;
}
}
/// <summary>
/// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetCompletionQueueCount(int completionQueueCount)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number");
customCompletionQueueCount = completionQueueCount;
}
}
/// <summary>
/// By default, gRPC's internal event handlers get offloaded to .NET default thread pool thread (<c>inlineHandlers=false</c>).
/// Setting <c>inlineHandlers</c> to <c>true</c> will allow scheduling the event handlers directly to
/// <c>GrpcThreadPool</c> internal threads. That can lead to significant performance gains in some situations,
/// but requires user to never block in async code (incorrectly written code can easily lead to deadlocks).
/// Inlining handlers is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// Note: <c>inlineHandlers=true</c> was the default in gRPC C# v1.4.x and earlier.
/// </summary>
public static void SetHandlerInlining(bool inlineHandlers)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcEnvironment.inlineHandlers = inlineHandlers;
}
}
/// <summary>
/// Sets the parameters for a pool that caches batch context instances. Reusing batch context instances
/// instead of creating a new one for every C core operation helps reducing the GC pressure.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// This is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetBatchContextPoolParams(int sharedCapacity, int threadLocalCapacity)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number");
GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number");
batchContextPoolSharedCapacity = sharedCapacity;
batchContextPoolThreadLocalCapacity = threadLocalCapacity;
}
}
/// <summary>
/// Sets the parameters for a pool that caches request call context instances. Reusing request call context instances
/// instead of creating a new one for every requested call in C core helps reducing the GC pressure.
/// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards.
/// This is an advanced setting and you should only use it if you know what you are doing.
/// Most users should rely on the default value provided by gRPC library.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.
/// </summary>
public static void SetRequestCallContextPoolParams(int sharedCapacity, int threadLocalCapacity)
{
lock (staticLock)
{
GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized");
GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number");
GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number");
requestCallContextPoolSharedCapacity = sharedCapacity;
requestCallContextPoolThreadLocalCapacity = threadLocalCapacity;
}
}
/// <summary>
/// Occurs when <c>GrpcEnvironment</c> is about the start the shutdown logic.
/// If <c>GrpcEnvironment</c> is later initialized and shutdown, the event will be fired again (unless unregistered first).
/// </summary>
public static event EventHandler ShuttingDown;
/// <summary>
/// Creates gRPC environment.
/// </summary>
private GrpcEnvironment()
{
GrpcNativeInit();
batchContextPool = new DefaultObjectPool<BatchContextSafeHandle>(() => BatchContextSafeHandle.Create(this.batchContextPool), batchContextPoolSharedCapacity, batchContextPoolThreadLocalCapacity);
requestCallContextPool = new DefaultObjectPool<RequestCallContextSafeHandle>(() => RequestCallContextSafeHandle.Create(this.requestCallContextPool), requestCallContextPoolSharedCapacity, requestCallContextPoolThreadLocalCapacity);
threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault(), inlineHandlers);
threadPool.Start();
}
/// <summary>
/// Gets the completion queues used by this gRPC environment.
/// </summary>
internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues
{
get
{
return this.threadPool.CompletionQueues;
}
}
internal IObjectPool<BatchContextSafeHandle> BatchContextPool => batchContextPool;
internal IObjectPool<RequestCallContextSafeHandle> RequestCallContextPool => requestCallContextPool;
internal bool IsAlive
{
get
{
return this.threadPool.IsAlive;
}
}
/// <summary>
/// Picks a completion queue in a round-robin fashion.
/// Shouldn't be invoked on a per-call basis (used at per-channel basis).
/// </summary>
internal CompletionQueueSafeHandle PickCompletionQueue()
{
var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count);
return this.threadPool.CompletionQueues.ElementAt(cqIndex);
}
/// <summary>
/// Gets the completion queue used by this gRPC environment.
/// </summary>
internal DebugStats DebugStats
{
get
{
return this.debugStats;
}
}
/// <summary>
/// Gets version of gRPC C core.
/// </summary>
internal static string GetCoreVersionString()
{
var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned
return Marshal.PtrToStringAnsi(ptr);
}
internal static void GrpcNativeInit()
{
NativeMethods.Get().grpcsharp_init();
}
internal static void GrpcNativeShutdown()
{
NativeMethods.Get().grpcsharp_shutdown();
}
/// <summary>
/// Shuts down this environment.
/// </summary>
private async Task ShutdownAsync()
{
if (isShutdown)
{
throw new InvalidOperationException("ShutdownAsync has already been called");
}
await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false);
await threadPool.StopAsync().ConfigureAwait(false);
batchContextPool.Dispose();
GrpcNativeShutdown();
isShutdown = true;
debugStats.CheckOK();
}
private int GetThreadPoolSizeOrDefault()
{
if (customThreadPoolSize.HasValue)
{
return customThreadPoolSize.Value;
}
// In systems with many cores, use half of the cores for GrpcThreadPool
// and the other half for .NET thread pool. This heuristic definitely needs
// more work, but seems to work reasonably well for a start.
return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2);
}
private int GetCompletionQueueCountOrDefault()
{
if (customCompletionQueueCount.HasValue)
{
return customCompletionQueueCount.Value;
}
// by default, create a completion queue for each thread
return GetThreadPoolSizeOrDefault();
}
private static class ShutdownHooks
{
static object staticLock = new object();
static bool hooksRegistered;
public static void Register()
{
lock (staticLock)
{
if (!hooksRegistered)
{
#if NETSTANDARD1_5
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (assemblyLoadContext) => { HandleShutdown(); };
#else
AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { HandleShutdown(); };
AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { HandleShutdown(); };
#endif
}
hooksRegistered = true;
}
}
/// <summary>
/// Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks.
/// </summary>
private static void HandleShutdown()
{
Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace Internal.Runtime.Augments
{
public class RuntimeThread : CriticalFinalizerObject
{
private static int s_optimalMaxSpinWaitsPerSpinIteration;
internal RuntimeThread() { }
public static RuntimeThread Create(ThreadStart start) => new Thread(start);
public static RuntimeThread Create(ThreadStart start, int maxStackSize) => new Thread(start, maxStackSize);
public static RuntimeThread Create(ParameterizedThreadStart start) => new Thread(start);
public static RuntimeThread Create(ParameterizedThreadStart start, int maxStackSize) => new Thread(start, maxStackSize);
private Thread AsThread()
{
Debug.Assert(this is Thread);
return (Thread)this;
}
public static RuntimeThread CurrentThread => Thread.CurrentThread;
/*=========================================================================
** Returns true if the thread has been started and is not dead.
=========================================================================*/
public extern bool IsAlive
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
/*=========================================================================
** Return whether or not this thread is a background thread. Background
** threads do not affect when the Execution Engine shuts down.
**
** Exceptions: ThreadStateException if the thread is dead.
=========================================================================*/
public bool IsBackground
{
get { return IsBackgroundNative(); }
set { SetBackgroundNative(value); }
}
[MethodImpl(MethodImplOptions.InternalCall)]
private extern bool IsBackgroundNative();
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void SetBackgroundNative(bool isBackground);
/*=========================================================================
** Returns true if the thread is a threadpool thread.
=========================================================================*/
public extern bool IsThreadPoolThread
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
public int ManagedThreadId => AsThread().ManagedThreadId;
public string Name { get { return AsThread().Name; } set { AsThread().Name = value; } }
/*=========================================================================
** Returns the priority of the thread.
**
** Exceptions: ThreadStateException if the thread is dead.
=========================================================================*/
public ThreadPriority Priority
{
get { return (ThreadPriority)GetPriorityNative(); }
set { SetPriorityNative((int)value); }
}
[MethodImpl(MethodImplOptions.InternalCall)]
private extern int GetPriorityNative();
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void SetPriorityNative(int priority);
/*=========================================================================
** Return the thread state as a consistent set of bits. This is more
** general then IsAlive or IsBackground.
=========================================================================*/
public ThreadState ThreadState
{
get { return (ThreadState)GetThreadStateNative(); }
}
[MethodImpl(MethodImplOptions.InternalCall)]
private extern int GetThreadStateNative();
public ApartmentState GetApartmentState()
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
return (ApartmentState)GetApartmentStateNative();
#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
Debug.Assert(false); // the Thread class in CoreFX should have handled this case
return ApartmentState.MTA;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
/*=========================================================================
** An unstarted thread can be marked to indicate that it will host a
** single-threaded or multi-threaded apartment.
=========================================================================*/
public bool TrySetApartmentState(ApartmentState state)
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
return SetApartmentStateHelper(state, false);
#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
Debug.Assert(false); // the Thread class in CoreFX should have handled this case
return false;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
internal bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch)
{
ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch);
// Special case where we pass in Unknown and get back MTA.
// Once we CoUninitialize the thread, the OS will still
// report the thread as implicitly in the MTA if any
// other thread in the process is CoInitialized.
if ((state == System.Threading.ApartmentState.Unknown) && (retState == System.Threading.ApartmentState.MTA))
return true;
if (retState != state)
return false;
return true;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern int GetApartmentStateNative();
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch);
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
#if FEATURE_COMINTEROP
[MethodImpl(MethodImplOptions.InternalCall)]
public extern void DisableComObjectEagerCleanup();
#else // !FEATURE_COMINTEROP
public void DisableComObjectEagerCleanup()
{
Debug.Assert(false); // the Thread class in CoreFX should have handled this case
}
#endif // FEATURE_COMINTEROP
/*=========================================================================
** Interrupts a thread that is inside a Wait(), Sleep() or Join(). If that
** thread is not currently blocked in that manner, it will be interrupted
** when it next begins to block.
=========================================================================*/
public void Interrupt() => InterruptInternal();
// Internal helper (since we can't place security demands on
// ecalls/fcalls).
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void InterruptInternal();
/*=========================================================================
** Waits for the thread to die or for timeout milliseconds to elapse.
** Returns true if the thread died, or false if the wait timed out. If
** Timeout.Infinite is given as the parameter, no timeout will occur.
**
** Exceptions: ArgumentException if timeout < 0.
** ThreadInterruptedException if the thread is interrupted while waiting.
** ThreadStateException if the thread has not been started yet.
=========================================================================*/
public void Join() => JoinInternal(Timeout.Infinite);
public bool Join(int millisecondsTimeout) => JoinInternal(millisecondsTimeout);
[MethodImpl(MethodImplOptions.InternalCall)]
private extern bool JoinInternal(int millisecondsTimeout);
public static void Sleep(int millisecondsTimeout) => Thread.Sleep(millisecondsTimeout);
[DllImport(JitHelpers.QCall)]
private static extern int GetOptimalMaxSpinWaitsPerSpinIterationInternal();
/// <summary>
/// Max value to be passed into <see cref="SpinWait(int)"/> for optimal delaying. This value is normalized to be
/// appropriate for the processor.
/// </summary>
internal static int OptimalMaxSpinWaitsPerSpinIteration
{
get
{
if (s_optimalMaxSpinWaitsPerSpinIteration != 0)
{
return s_optimalMaxSpinWaitsPerSpinIteration;
}
// This is done lazily because the first call to the function below in the process triggers a measurement that
// takes a nontrivial amount of time if the measurement has not already been done in the backgorund.
// See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value.
s_optimalMaxSpinWaitsPerSpinIteration = GetOptimalMaxSpinWaitsPerSpinIterationInternal();
Debug.Assert(s_optimalMaxSpinWaitsPerSpinIteration > 0);
return s_optimalMaxSpinWaitsPerSpinIteration;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetCurrentProcessorNumber();
// The upper bits of t_currentProcessorIdCache are the currentProcessorId. The lower bits of
// the t_currentProcessorIdCache are counting down to get it periodically refreshed.
// TODO: Consider flushing the currentProcessorIdCache on Wait operations or similar
// actions that are likely to result in changing the executing core
[ThreadStatic]
private static int t_currentProcessorIdCache;
private const int ProcessorIdCacheShift = 16;
private const int ProcessorIdCacheCountDownMask = (1 << ProcessorIdCacheShift) - 1;
private const int ProcessorIdRefreshRate = 5000;
private static int RefreshCurrentProcessorId()
{
int currentProcessorId = GetCurrentProcessorNumber();
// On Unix, GetCurrentProcessorNumber() is implemented in terms of sched_getcpu, which
// doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber()
// returns -1. As a fallback in that case and to spread the threads across the buckets
// by default, we use the current managed thread ID as a proxy.
if (currentProcessorId < 0) currentProcessorId = Environment.CurrentManagedThreadId;
// Add offset to make it clear that it is not guaranteed to be 0-based processor number
currentProcessorId += 100;
Debug.Assert(ProcessorIdRefreshRate <= ProcessorIdCacheCountDownMask);
// Mask with Int32.MaxValue to ensure the execution Id is not negative
t_currentProcessorIdCache = ((currentProcessorId << ProcessorIdCacheShift) & Int32.MaxValue) | ProcessorIdRefreshRate;
return currentProcessorId;
}
// Cached processor id used as a hint for which per-core stack to access. It is periodically
// refreshed to trail the actual thread core affinity.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetCurrentProcessorId()
{
int currentProcessorIdCache = t_currentProcessorIdCache--;
if ((currentProcessorIdCache & ProcessorIdCacheCountDownMask) == 0)
return RefreshCurrentProcessorId();
return (currentProcessorIdCache >> ProcessorIdCacheShift);
}
public static void SpinWait(int iterations) => Thread.SpinWait(iterations);
public static bool Yield() => Thread.Yield();
public void Start() => AsThread().Start();
public void Start(object parameter) => AsThread().Start(parameter);
}
}
| |
using Signum.Entities.SMS;
using Signum.Utilities.Reflection;
using Signum.Engine.Processes;
using Signum.Entities.Processes;
using Signum.Entities.Basics;
using System.Globalization;
using Signum.Engine.Templating;
namespace Signum.Engine.SMS;
public static class SMSLogic
{
public static SMSTemplateMessageEmbedded? GetCultureMessage(this SMSTemplateEntity template, CultureInfo ci)
{
return template.Messages.SingleOrDefault(tm => tm.CultureInfo.ToCultureInfo() == ci);
}
[AutoExpressionField]
public static IQueryable<SMSMessageEntity> SMSMessages(this ISMSOwnerEntity e) =>
As.Expression(() => Database.Query<SMSMessageEntity>().Where(m => m.Referred.Is(e)));
[AutoExpressionField]
public static IQueryable<SMSMessageEntity> SMSMessages(this SMSSendPackageEntity e) =>
As.Expression(() => Database.Query<SMSMessageEntity>().Where(a => a.SendPackage.Is(e)));
[AutoExpressionField]
public static IQueryable<SMSMessageEntity> SMSMessages(this SMSUpdatePackageEntity e) =>
As.Expression(() => Database.Query<SMSMessageEntity>().Where(a => a.UpdatePackage.Is(e)));
static Func<SMSConfigurationEmbedded> getConfiguration = null!;
public static SMSConfigurationEmbedded Configuration
{
get { return getConfiguration(); }
}
public static ISMSProvider? Provider { get; set; }
public static ISMSProvider GetProvider() => Provider ?? throw new InvalidOperationException("No ISMSProvider set");
public static ResetLazy<Dictionary<Lite<SMSTemplateEntity>, SMSTemplateEntity>> SMSTemplatesLazy = null!;
public static ResetLazy<Dictionary<object, List<SMSTemplateEntity>>> SMSTemplatesByQueryName = null!;
public static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!, null!, null!)));
}
public static void Start(SchemaBuilder sb, ISMSProvider? provider, Func<SMSConfigurationEmbedded> getConfiguration)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
CultureInfoLogic.AssertStarted(sb);
sb.Schema.SchemaCompleted += () => Schema_SchemaCompleted(sb);
SMSLogic.getConfiguration = getConfiguration;
SMSLogic.Provider = provider;
sb.Include<SMSMessageEntity>()
.WithQuery(() => m => new
{
Entity = m,
m.Id,
m.From,
m.DestinationNumber,
m.State,
m.SendDate,
m.Template,
m.Referred,
m.Exception,
});
sb.Include<SMSTemplateEntity>()
.WithQuery(() => t => new
{
Entity = t,
t.Id,
t.Name,
t.IsActive,
t.From,
t.Query,
t.Model,
});
sb.Schema.EntityEvents<SMSTemplateEntity>().PreSaving += new PreSavingEventHandler<SMSTemplateEntity>(EmailTemplate_PreSaving);
sb.Schema.EntityEvents<SMSTemplateEntity>().Retrieved += SMSTemplateLogic_Retrieved;
sb.Schema.Table<SMSModelEntity>().PreDeleteSqlSync += e =>
Administrator.UnsafeDeletePreCommand(Database.Query<SMSTemplateEntity>()
.Where(a => a.Model.Is(e)));
SMSTemplatesLazy = sb.GlobalLazy(() =>
Database.Query<SMSTemplateEntity>().ToDictionary(et => et.ToLite())
, new InvalidateWith(typeof(SMSTemplateEntity)));
SMSTemplatesByQueryName = sb.GlobalLazy(() =>
{
return SMSTemplatesLazy.Value.Values.Where(q=>q.Query!=null).SelectCatch(et => KeyValuePair.Create(et.Query!.ToQueryName(), et)).GroupToDictionary();
}, new InvalidateWith(typeof(SMSTemplateEntity)));
SMSMessageGraph.Register();
SMSTemplateGraph.Register();
Validator.PropertyValidator<SMSTemplateEntity>(et => et.Messages).StaticPropertyValidation += (t, pi) =>
{
var dc = SMSLogic.Configuration?.DefaultCulture;
if (dc != null && !t.Messages.Any(m => m.CultureInfo.Is(dc)))
return SMSTemplateMessage.ThereMustBeAMessageFor0.NiceToString().FormatWith(dc.EnglishName);
return null;
};
sb.AddUniqueIndex((SMSTemplateEntity t) => new { t.Model }, where: t => t.Model != null && t.IsActive == true);
ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages;
}
}
public static void ExceptionLogic_DeletePackages(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token)
{
Database.Query<SMSSendPackageEntity>().Where(pack => !Database.Query<ProcessEntity>().Any(pr => pr.Data == pack) && !pack.SMSMessages().Any())
.UnsafeDeleteChunksLog(parameters, sb, token);
Database.Query<SMSUpdatePackageEntity>().Where(pack => !Database.Query<ProcessEntity>().Any(pr => pr.Data == pack) && !pack.SMSMessages().Any())
.UnsafeDeleteChunksLog(parameters, sb, token);
}
public static void ExceptionLogic_DeleteLogs(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token)
{
void Remove(DateTime? dateLimit, bool withExceptions)
{
if (dateLimit == null)
return;
var query = Database.Query<SMSMessageEntity>().Where(o => o.SendDate != null && o.SendDate < dateLimit);
if (withExceptions)
query = query.Where(a => a.Exception != null);
query.UnsafeDeleteChunksLog(parameters, sb, token);
}
Remove(parameters.GetDateLimitDelete(typeof(SMSMessageEntity).ToTypeEntity()), withExceptions: false);
Remove(parameters.GetDateLimitDeleteWithExceptions(typeof(SMSMessageEntity).ToTypeEntity()), withExceptions: true);
}
public static HashSet<Type> GetAllTypes()
{
return TypeLogic.TypeToEntity
.Where(kvp => typeof(ISMSOwnerEntity).IsAssignableFrom(kvp.Key))
.Select(kvp => kvp.Key)
.ToHashSet();
}
public static void SMSTemplateLogic_Retrieved(SMSTemplateEntity smsTemplate, PostRetrievingContext ctx)
{
if (smsTemplate.Query == null)
return;
using (smsTemplate.DisableAuthorization ? ExecutionMode.Global() : null)
{
object queryName = QueryLogic.ToQueryName(smsTemplate.Query!.Key);
QueryDescription description = QueryLogic.Queries.QueryDescription(queryName);
using (smsTemplate.DisableAuthorization ? ExecutionMode.Global() : null)
smsTemplate.ParseData(description);
}
}
static void EmailTemplate_PreSaving(SMSTemplateEntity smsTemplate, PreSavingContext ctx)
{
if (smsTemplate.Query == null)
return;
using (smsTemplate.DisableAuthorization ? ExecutionMode.Global() : null)
{
var queryName = QueryLogic.ToQueryName(smsTemplate.Query!.Key);
QueryDescription qd = QueryLogic.Queries.QueryDescription(queryName);
List<QueryToken> list = new List<QueryToken>();
foreach (var message in smsTemplate.Messages)
{
message.Message = TextTemplateParser.Parse(message.Message, qd, smsTemplate.Model?.ToType()).ToString();
}
}
}
static string CheckLength(string result, SMSTemplateEntity template)
{
if (template.RemoveNoSMSCharacters)
{
result = SMSCharacters.RemoveNoSMSCharacters(result);
}
int remainingLength = SMSCharacters.RemainingLength(result);
if (remainingLength < 0)
{
switch (template.MessageLengthExceeded)
{
case MessageLengthExceeded.NotAllowed:
throw new ApplicationException(SMSCharactersMessage.TheTextForTheSMSMessageExceedsTheLengthLimit.NiceToString());
case MessageLengthExceeded.Allowed:
break;
case MessageLengthExceeded.TextPruning:
return result.RemoveEnd(Math.Abs(remainingLength));
}
}
return result;
}
public static void SendSMS(SMSMessageEntity message)
{
if (!message.DestinationNumber.Contains(','))
{
SendOneMessage(message);
}
else
{
var numbers = message.DestinationNumber.Split(',').Select(n => n.Trim()).Distinct();
message.DestinationNumber = numbers.FirstEx();
SendOneMessage(message);
foreach (var number in numbers.Skip(1))
{
SendOneMessage(new SMSMessageEntity
{
DestinationNumber = number,
Certified = message.Certified,
EditableMessage = message.EditableMessage,
From = message.From,
Message = message.Message,
Referred = message.Referred,
State = SMSMessageState.Created,
Template = message.Template,
SendPackage = message.SendPackage,
UpdatePackage = message.UpdatePackage,
UpdatePackageProcessed = message.UpdatePackageProcessed,
});
}
}
}
private static void SendOneMessage(SMSMessageEntity message)
{
using (OperationLogic.AllowSave<SMSMessageEntity>())
{
try
{
message.MessageID = GetProvider().SMSSendAndGetTicket(message);
message.SendDate = Clock.Now.TrimToSeconds();
message.State = SMSMessageState.Sent;
message.Save();
}
catch (Exception e)
{
var ex = e.LogException();
using (var tr = Transaction.ForceNew())
{
message.Exception = ex.ToLite();
message.State = SMSMessageState.SendFailed;
message.Save();
tr.Commit();
}
throw;
}
}
}
public static void SendAsyncSMS(SMSMessageEntity message)
{
Task.Factory.StartNew(() =>
{
SendSMS(message);
});
}
public static List<SMSMessageEntity> CreateAndSendMultipleSMSMessages(MultipleSMSModel template, List<string> phones)
{
var messages = new List<SMSMessageEntity>();
var IDs = GetProvider().SMSMultipleSendAction(template, phones);
var sendDate = Clock.Now.TrimToSeconds();
for (int i = 0; i < phones.Count; i++)
{
var message = new SMSMessageEntity { Message = template.Message, From = template.From };
message.SendDate = sendDate;
//message.SendState = SendState.Sent;
message.DestinationNumber = phones[i];
message.MessageID = IDs[i];
message.Save();
messages.Add(message);
}
return messages;
}
public static SMSMessageEntity CreateSMSMessage(Lite<SMSTemplateEntity> template, Entity? entity, ISMSModel? model, CultureInfo? forceCulture)
{
var t = SMSLogic.SMSTemplatesLazy.Value.GetOrThrow(template);
var defaultCulture = SMSLogic.Configuration.DefaultCulture.ToCultureInfo();
if (t.Query != null)
{
var qd = QueryLogic.Queries.QueryDescription(t.Query.ToQueryName());
List<QueryToken> tokens = new List<QueryToken>();
t.ParseData(qd);
tokens.Add(t.To!.Token);
var parsedNodes = t.Messages.ToDictionary(
tm => tm.CultureInfo.ToCultureInfo(),
tm => TextTemplateParser.Parse(tm.Message, qd, t.Model?.ToType())
);
parsedNodes.Values.ToList().ForEach(n => n.FillQueryTokens(tokens));
var columns = tokens.Distinct().Select(qt => new Column(qt, null)).ToList();
var filters = model != null ? model.GetFilters(qd) :
new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, entity!.ToLite()) };
var table = QueryLogic.Queries.ExecuteQuery(new QueryRequest
{
QueryName = qd.QueryName,
Columns = columns,
Pagination = model?.GetPagination() ?? new Pagination.All(),
Filters = filters,
Orders = model?.GetOrders(qd) ?? new List<Order>(),
});
var columnTokens = table.Columns.ToDictionary(a => a.Column.Token);
var ownerData = (SMSOwnerData)table.Rows[0][columnTokens.GetOrThrow(t.To!.Token)]!;
var ci = forceCulture ?? ownerData.CultureInfo?.ToCultureInfo() ?? defaultCulture;
var node = parsedNodes.TryGetC(ci) ?? parsedNodes.GetOrThrow(defaultCulture);
return new SMSMessageEntity
{
Template = t.ToLite(),
Message = node.Print(new TextTemplateParameters(entity, ci, columnTokens, table.Rows) { Model = model }),
From = t.From,
EditableMessage = t.EditableMessage,
State = SMSMessageState.Created,
Referred = ownerData.Owner,
DestinationNumber = ownerData.TelephoneNumber,
Certified = t.Certified
};
}
else
{
var ci = (forceCulture ?? defaultCulture).ToCultureInfoEntity();
return new SMSMessageEntity
{
Template = t.ToLite(),
Message = t.Messages.Where(m=> m.CultureInfo.Is(ci)).SingleEx().Message,
From = t.From,
EditableMessage = t.EditableMessage,
State = SMSMessageState.Created,
Certified = t.Certified
};
}
}
private static void Schema_SchemaCompleted(SchemaBuilder sb)
{
var types = sb.Schema.Tables.Keys.Where(t => typeof(ISMSOwnerEntity).IsAssignableFrom(t));
foreach (var type in types)
giRegisterSMSMessagesExpression.GetInvoker(type)(sb);
}
static GenericInvoker<Action<SchemaBuilder>> giRegisterSMSMessagesExpression = new(sb => RegisterSMSMessagesExpression<ISMSOwnerEntity>(sb));
private static void RegisterSMSMessagesExpression<T>(SchemaBuilder sb)
where T : ISMSOwnerEntity
{
QueryLogic.Expressions.Register((T a) => a.SMSMessages(), () => typeof(SMSMessageEntity).NicePluralName());
}
}
public class SMSMessageGraph : Graph<SMSMessageEntity, SMSMessageState>
{
public static void Register()
{
GetState = m => m.State;
new ConstructFrom<SMSTemplateEntity>(SMSMessageOperation.CreateSMSFromTemplate)
{
CanConstruct = t => !t.IsActive ? SMSCharactersMessage.TheTemplateMustBeActiveToConstructSMSMessages.NiceToString() : null,
ToStates = { SMSMessageState.Created },
Construct = (t, args) =>
{
return SMSLogic.CreateSMSMessage(t.ToLite(),
args.TryGetArgC<Lite<Entity>>()?.RetrieveAndRemember(),
args.TryGetArgC<ISMSModel>(),
args.TryGetArgC<CultureInfo>());
}
}.Register();
new Execute(SMSMessageOperation.Send)
{
CanBeNew = true,
CanBeModified = true,
FromStates = { SMSMessageState.Created },
ToStates = { SMSMessageState.Sent },
Execute = (m, _) =>
{
try
{
SMSLogic.SendSMS(m);
}
catch (Exception e)
{
var ex = e.LogException();
using (var tr = Transaction.ForceNew())
{
m.Exception = ex.ToLite();
m.Save();
tr.Commit();
}
throw;
}
}
}.Register();
new Graph<SMSMessageEntity>.Execute(SMSMessageOperation.UpdateStatus)
{
CanExecute = m => m.State != SMSMessageState.Created ? null : SMSCharactersMessage.StatusCanNotBeUpdatedForNonSentMessages.NiceToString(),
Execute = (sms, args) =>
{
var func = args.TryGetArgC<Func<SMSMessageEntity, SMSMessageState>>();
if (func == null)
func = SMSLogic.GetProvider().SMSUpdateStatusAction;
sms.State = func(sms);
if (sms.UpdatePackage != null)
sms.UpdatePackageProcessed = true;
}
}.Register();
}
}
public class SMSTemplateGraph : Graph<SMSTemplateEntity>
{
public static void Register()
{
new Construct(SMSTemplateOperation.Create)
{
Construct = _ => new SMSTemplateEntity
{
Messages =
{
new SMSTemplateMessageEmbedded
{
CultureInfo = SMSLogic.Configuration.DefaultCulture
}
}
},
}.Register();
new Execute(SMSTemplateOperation.Save)
{
CanBeModified = true,
CanBeNew = true,
Execute = (t, _) => { }
}.Register();
}
}
public interface ISMSProvider
{
string SMSSendAndGetTicket(SMSMessageEntity message);
List<string> SMSMultipleSendAction(MultipleSMSModel template, List<string> phones);
SMSMessageState SMSUpdateStatusAction(SMSMessageEntity message);
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Parameters;
namespace NBitcoin.BouncyCastle.Crypto.Engines
{
/**
* an implementation of Rijndael, based on the documentation and reference implementation
* by Paulo Barreto, Vincent Rijmen, for v2.0 August '99.
* <p>
* Note: this implementation is based on information prior to readonly NIST publication.
* </p>
*/
public class RijndaelEngine
: IBlockCipher
{
private static readonly int MAXROUNDS = 14;
private static readonly int MAXKC = (256/4);
private static readonly byte[] Logtable =
{
0, 0, 25, 1, 50, 2, 26, 198,
75, 199, 27, 104, 51, 238, 223, 3,
100, 4, 224, 14, 52, 141, 129, 239,
76, 113, 8, 200, 248, 105, 28, 193,
125, 194, 29, 181, 249, 185, 39, 106,
77, 228, 166, 114, 154, 201, 9, 120,
101, 47, 138, 5, 33, 15, 225, 36,
18, 240, 130, 69, 53, 147, 218, 142,
150, 143, 219, 189, 54, 208, 206, 148,
19, 92, 210, 241, 64, 70, 131, 56,
102, 221, 253, 48, 191, 6, 139, 98,
179, 37, 226, 152, 34, 136, 145, 16,
126, 110, 72, 195, 163, 182, 30, 66,
58, 107, 40, 84, 250, 133, 61, 186,
43, 121, 10, 21, 155, 159, 94, 202,
78, 212, 172, 229, 243, 115, 167, 87,
175, 88, 168, 80, 244, 234, 214, 116,
79, 174, 233, 213, 231, 230, 173, 232,
44, 215, 117, 122, 235, 22, 11, 245,
89, 203, 95, 176, 156, 169, 81, 160,
127, 12, 246, 111, 23, 196, 73, 236,
216, 67, 31, 45, 164, 118, 123, 183,
204, 187, 62, 90, 251, 96, 177, 134,
59, 82, 161, 108, 170, 85, 41, 157,
151, 178, 135, 144, 97, 190, 220, 252,
188, 149, 207, 205, 55, 63, 91, 209,
83, 57, 132, 60, 65, 162, 109, 71,
20, 42, 158, 93, 86, 242, 211, 171,
68, 17, 146, 217, 35, 32, 46, 137,
180, 124, 184, 38, 119, 153, 227, 165,
103, 74, 237, 222, 197, 49, 254, 24,
13, 99, 140, 128, 192, 247, 112, 7
};
private static readonly byte[] Alogtable =
{
0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53,
95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170,
229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49,
83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205,
76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136,
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154,
181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163,
254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160,
251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65,
195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117,
159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128,
155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84,
252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202,
69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14,
18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23,
57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1,
3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53,
95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170,
229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49,
83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205,
76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136,
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154,
181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163,
254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160,
251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65,
195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117,
159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128,
155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84,
252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202,
69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14,
18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23,
57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1,
};
private static readonly byte[] S =
{
99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22,
};
private static readonly byte[] Si =
{
82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125,
};
private static readonly byte[] rcon =
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91
};
static readonly byte[][] shifts0 = new byte [][]
{
new byte[]{ 0, 8, 16, 24 },
new byte[]{ 0, 8, 16, 24 },
new byte[]{ 0, 8, 16, 24 },
new byte[]{ 0, 8, 16, 32 },
new byte[]{ 0, 8, 24, 32 }
};
static readonly byte[][] shifts1 =
{
new byte[]{ 0, 24, 16, 8 },
new byte[]{ 0, 32, 24, 16 },
new byte[]{ 0, 40, 32, 24 },
new byte[]{ 0, 48, 40, 24 },
new byte[]{ 0, 56, 40, 32 }
};
/**
* multiply two elements of GF(2^m)
* needed for MixColumn and InvMixColumn
*/
private byte Mul0x2(
int b)
{
if (b != 0)
{
return Alogtable[25 + (Logtable[b] & 0xff)];
}
else
{
return 0;
}
}
private byte Mul0x3(
int b)
{
if (b != 0)
{
return Alogtable[1 + (Logtable[b] & 0xff)];
}
else
{
return 0;
}
}
private byte Mul0x9(
int b)
{
if (b >= 0)
{
return Alogtable[199 + b];
}
else
{
return 0;
}
}
private byte Mul0xb(
int b)
{
if (b >= 0)
{
return Alogtable[104 + b];
}
else
{
return 0;
}
}
private byte Mul0xd(
int b)
{
if (b >= 0)
{
return Alogtable[238 + b];
}
else
{
return 0;
}
}
private byte Mul0xe(
int b)
{
if (b >= 0)
{
return Alogtable[223 + b];
}
else
{
return 0;
}
}
/**
* xor corresponding text input and round key input bytes
*/
private void KeyAddition(
long[] rk)
{
A0 ^= rk[0];
A1 ^= rk[1];
A2 ^= rk[2];
A3 ^= rk[3];
}
private long Shift(
long r,
int shift)
{
//return (((long)((ulong) r >> shift) | (r << (BC - shift)))) & BC_MASK;
ulong temp = (ulong) r >> shift;
// NB: This corrects for Mono Bug #79087 (fixed in 1.1.17)
if (shift > 31)
{
temp &= 0xFFFFFFFFUL;
}
return ((long) temp | (r << (BC - shift))) & BC_MASK;
}
/**
* Row 0 remains unchanged
* The other three rows are shifted a variable amount
*/
private void ShiftRow(
byte[] shiftsSC)
{
A1 = Shift(A1, shiftsSC[1]);
A2 = Shift(A2, shiftsSC[2]);
A3 = Shift(A3, shiftsSC[3]);
}
private long ApplyS(
long r,
byte[] box)
{
long res = 0;
for (int j = 0; j < BC; j += 8)
{
res |= (long)(box[(int)((r >> j) & 0xff)] & 0xff) << j;
}
return res;
}
/**
* Replace every byte of the input by the byte at that place
* in the nonlinear S-box
*/
private void Substitution(
byte[] box)
{
A0 = ApplyS(A0, box);
A1 = ApplyS(A1, box);
A2 = ApplyS(A2, box);
A3 = ApplyS(A3, box);
}
/**
* Mix the bytes of every column in a linear way
*/
private void MixColumn()
{
long r0, r1, r2, r3;
r0 = r1 = r2 = r3 = 0;
for (int j = 0; j < BC; j += 8)
{
int a0 = (int)((A0 >> j) & 0xff);
int a1 = (int)((A1 >> j) & 0xff);
int a2 = (int)((A2 >> j) & 0xff);
int a3 = (int)((A3 >> j) & 0xff);
r0 |= (long)((Mul0x2(a0) ^ Mul0x3(a1) ^ a2 ^ a3) & 0xff) << j;
r1 |= (long)((Mul0x2(a1) ^ Mul0x3(a2) ^ a3 ^ a0) & 0xff) << j;
r2 |= (long)((Mul0x2(a2) ^ Mul0x3(a3) ^ a0 ^ a1) & 0xff) << j;
r3 |= (long)((Mul0x2(a3) ^ Mul0x3(a0) ^ a1 ^ a2) & 0xff) << j;
}
A0 = r0;
A1 = r1;
A2 = r2;
A3 = r3;
}
/**
* Mix the bytes of every column in a linear way
* This is the opposite operation of Mixcolumn
*/
private void InvMixColumn()
{
long r0, r1, r2, r3;
r0 = r1 = r2 = r3 = 0;
for (int j = 0; j < BC; j += 8)
{
int a0 = (int)((A0 >> j) & 0xff);
int a1 = (int)((A1 >> j) & 0xff);
int a2 = (int)((A2 >> j) & 0xff);
int a3 = (int)((A3 >> j) & 0xff);
//
// pre-lookup the log table
//
a0 = (a0 != 0) ? (Logtable[a0 & 0xff] & 0xff) : -1;
a1 = (a1 != 0) ? (Logtable[a1 & 0xff] & 0xff) : -1;
a2 = (a2 != 0) ? (Logtable[a2 & 0xff] & 0xff) : -1;
a3 = (a3 != 0) ? (Logtable[a3 & 0xff] & 0xff) : -1;
r0 |= (long)((Mul0xe(a0) ^ Mul0xb(a1) ^ Mul0xd(a2) ^ Mul0x9(a3)) & 0xff) << j;
r1 |= (long)((Mul0xe(a1) ^ Mul0xb(a2) ^ Mul0xd(a3) ^ Mul0x9(a0)) & 0xff) << j;
r2 |= (long)((Mul0xe(a2) ^ Mul0xb(a3) ^ Mul0xd(a0) ^ Mul0x9(a1)) & 0xff) << j;
r3 |= (long)((Mul0xe(a3) ^ Mul0xb(a0) ^ Mul0xd(a1) ^ Mul0x9(a2)) & 0xff) << j;
}
A0 = r0;
A1 = r1;
A2 = r2;
A3 = r3;
}
/**
* Calculate the necessary round keys
* The number of calculations depends on keyBits and blockBits
*/
private long[][] GenerateWorkingKey(
byte[] key)
{
int KC;
int t, rconpointer = 0;
int keyBits = key.Length * 8;
byte[,] tk = new byte[4,MAXKC];
//long[,] W = new long[MAXROUNDS+1,4];
long[][] W = new long[MAXROUNDS+1][];
for (int i = 0; i < MAXROUNDS+1; i++) W[i] = new long[4];
switch (keyBits)
{
case 128:
KC = 4;
break;
case 160:
KC = 5;
break;
case 192:
KC = 6;
break;
case 224:
KC = 7;
break;
case 256:
KC = 8;
break;
default :
throw new ArgumentException("Key length not 128/160/192/224/256 bits.");
}
if (keyBits >= blockBits)
{
ROUNDS = KC + 6;
}
else
{
ROUNDS = (BC / 8) + 6;
}
//
// copy the key into the processing area
//
int index = 0;
for (int i = 0; i < key.Length; i++)
{
tk[i % 4,i / 4] = key[index++];
}
t = 0;
//
// copy values into round key array
//
for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC / 8)); j++, t++)
{
for (int i = 0; i < 4; i++)
{
W[t / (BC / 8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % BC);
}
}
//
// while not enough round key material calculated
// calculate new values
//
while (t < (ROUNDS+1)*(BC/8))
{
for (int i = 0; i < 4; i++)
{
tk[i,0] ^= S[tk[(i+1)%4,KC-1] & 0xff];
}
tk[0,0] ^= (byte) rcon[rconpointer++];
if (KC <= 6)
{
for (int j = 1; j < KC; j++)
{
for (int i = 0; i < 4; i++)
{
tk[i,j] ^= tk[i,j-1];
}
}
}
else
{
for (int j = 1; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
tk[i,j] ^= tk[i,j-1];
}
}
for (int i = 0; i < 4; i++)
{
tk[i,4] ^= S[tk[i,3] & 0xff];
}
for (int j = 5; j < KC; j++)
{
for (int i = 0; i < 4; i++)
{
tk[i,j] ^= tk[i,j-1];
}
}
}
//
// copy values into round key array
//
for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC/8)); j++, t++)
{
for (int i = 0; i < 4; i++)
{
W[t / (BC/8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % (BC));
}
}
}
return W;
}
private int BC;
private long BC_MASK;
private int ROUNDS;
private int blockBits;
private long[][] workingKey;
private long A0, A1, A2, A3;
private bool forEncryption;
private byte[] shifts0SC;
private byte[] shifts1SC;
/**
* default constructor - 128 bit block size.
*/
public RijndaelEngine() : this(128) {}
/**
* basic constructor - set the cipher up for a given blocksize
*
* @param blocksize the blocksize in bits, must be 128, 192, or 256.
*/
public RijndaelEngine(
int blockBits)
{
switch (blockBits)
{
case 128:
BC = 32;
BC_MASK = 0xffffffffL;
shifts0SC = shifts0[0];
shifts1SC = shifts1[0];
break;
case 160:
BC = 40;
BC_MASK = 0xffffffffffL;
shifts0SC = shifts0[1];
shifts1SC = shifts1[1];
break;
case 192:
BC = 48;
BC_MASK = 0xffffffffffffL;
shifts0SC = shifts0[2];
shifts1SC = shifts1[2];
break;
case 224:
BC = 56;
BC_MASK = 0xffffffffffffffL;
shifts0SC = shifts0[3];
shifts1SC = shifts1[3];
break;
case 256:
BC = 64;
BC_MASK = unchecked( (long)0xffffffffffffffffL);
shifts0SC = shifts0[4];
shifts1SC = shifts1[4];
break;
default:
throw new ArgumentException("unknown blocksize to Rijndael");
}
this.blockBits = blockBits;
}
/**
* initialise a Rijndael cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (typeof(KeyParameter).IsInstanceOfType(parameters))
{
workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey());
this.forEncryption = forEncryption;
return;
}
throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString());
}
public string AlgorithmName
{
get { return "Rijndael"; }
}
public bool IsPartialBlockOkay
{
get { return false; }
}
public int GetBlockSize()
{
return BC / 2;
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if (workingKey == null)
{
throw new InvalidOperationException("Rijndael engine not initialised");
}
if ((inOff + (BC / 2)) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + (BC / 2)) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
UnPackBlock(input, inOff);
if (forEncryption)
{
EncryptBlock(workingKey);
}
else
{
DecryptBlock(workingKey);
}
PackBlock(output, outOff);
return BC / 2;
}
public void Reset()
{
}
private void UnPackBlock(
byte[] bytes,
int off)
{
int index = off;
A0 = (long)(bytes[index++] & 0xff);
A1 = (long)(bytes[index++] & 0xff);
A2 = (long)(bytes[index++] & 0xff);
A3 = (long)(bytes[index++] & 0xff);
for (int j = 8; j != BC; j += 8)
{
A0 |= (long)(bytes[index++] & 0xff) << j;
A1 |= (long)(bytes[index++] & 0xff) << j;
A2 |= (long)(bytes[index++] & 0xff) << j;
A3 |= (long)(bytes[index++] & 0xff) << j;
}
}
private void PackBlock(
byte[] bytes,
int off)
{
int index = off;
for (int j = 0; j != BC; j += 8)
{
bytes[index++] = (byte)(A0 >> j);
bytes[index++] = (byte)(A1 >> j);
bytes[index++] = (byte)(A2 >> j);
bytes[index++] = (byte)(A3 >> j);
}
}
private void EncryptBlock(
long[][] rk)
{
int r;
//
// begin with a key addition
//
KeyAddition(rk[0]);
//
// ROUNDS-1 ordinary rounds
//
for (r = 1; r < ROUNDS; r++)
{
Substitution(S);
ShiftRow(shifts0SC);
MixColumn();
KeyAddition(rk[r]);
}
//
// Last round is special: there is no MixColumn
//
Substitution(S);
ShiftRow(shifts0SC);
KeyAddition(rk[ROUNDS]);
}
private void DecryptBlock(
long[][] rk)
{
int r;
// To decrypt: apply the inverse operations of the encrypt routine,
// in opposite order
//
// (KeyAddition is an involution: it 's equal to its inverse)
// (the inverse of Substitution with table S is Substitution with the inverse table of S)
// (the inverse of Shiftrow is Shiftrow over a suitable distance)
//
// First the special round:
// without InvMixColumn
// with extra KeyAddition
//
KeyAddition(rk[ROUNDS]);
Substitution(Si);
ShiftRow(shifts1SC);
//
// ROUNDS-1 ordinary rounds
//
for (r = ROUNDS-1; r > 0; r--)
{
KeyAddition(rk[r]);
InvMixColumn();
Substitution(Si);
ShiftRow(shifts1SC);
}
//
// End with the extra key addition
//
KeyAddition(rk[0]);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Globalization
{
public partial class CompareInfo
{
[NonSerialized]
private Interop.GlobalizationInterop.SafeSortHandle _sortHandle;
[NonSerialized]
private bool _isAsciiEqualityOrdinal;
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
if (_invariantMode)
{
_isAsciiEqualityOrdinal = true;
}
else
{
Interop.GlobalizationInterop.ResultCode resultCode = Interop.GlobalizationInterop.GetSortHandle(GetNullTerminatedUtf8String(_sortName), out _sortHandle);
if (resultCode != Interop.GlobalizationInterop.ResultCode.Success)
{
_sortHandle.Dispose();
if (resultCode == Interop.GlobalizationInterop.ResultCode.OutOfMemory)
throw new OutOfMemoryException();
throw new ExternalException(SR.Arg_ExternalException);
}
_isAsciiEqualityOrdinal = (_sortName == "en-US" || _sortName == "");
}
}
internal static unsafe int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
internal static unsafe int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
Debug.Assert(!GlobalizationMode.Invariant);
return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(string1 != null);
Debug.Assert(string2 != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
fixed (char* pString2 = string2)
{
return Interop.GlobalizationInterop.CompareString(_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
}
}
}
internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
int index;
if (target.Length == 0)
{
if(matchLengthPtr != null)
*matchLengthPtr = 0;
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
index = IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
if(index != -1)
{
if(matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return index;
}
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
index = IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
if(index != -1)
{
if(matchLengthPtr != null)
*matchLengthPtr = target.Length;
}
return index;
}
fixed (char* pSource = source)
{
index = Interop.GlobalizationInterop.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options, matchLengthPtr);
return index != -1 ? index + startIndex : -1;
}
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinalCore(source, target, startIndex, count, ignoreCase: false);
}
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(prefix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
{
return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.StartsWith(_sortHandle, prefix, prefix.Length, source, source.Length, options);
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(suffix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
{
return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options);
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
Debug.Assert(!_invariantMode);
if (source==null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<Byte>();
}
else
{
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
keyData = new byte[sortKeyLength];
fixed (byte* pSortKey = keyData)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
}
}
return new SortKey(Name, source, options, keyData);
}
private unsafe static bool IsSortable(char *text, int length)
{
Debug.Assert(!GlobalizationMode.Invariant);
int index = 0;
UnicodeCategory uc;
while (index < length)
{
if (Char.IsHighSurrogate(text[index]))
{
if (index == length - 1 || !Char.IsLowSurrogate(text[index+1]))
return false; // unpaired surrogate
uc = CharUnicodeInfo.InternalGetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1]));
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
return false;
index += 2;
continue;
}
if (Char.IsLowSurrogate(text[index]))
{
return false; // unpaired surrogate
}
uc = CharUnicodeInfo.GetUnicodeCategory(text[index]);
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
{
return false;
}
index++;
}
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source != null);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
// As an optimization, for small sort keys we allocate the buffer on the stack.
if (sortKeyLength <= 256)
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
byte[] sortKey = new byte[sortKeyLength];
fixed (byte* pSortKey = sortKey)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
}
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
private static byte[] GetNullTerminatedUtf8String(string s)
{
int byteLen = System.Text.Encoding.UTF8.GetByteCount(s);
// Allocate an extra byte (which defaults to 0) as the null terminator.
byte[] buffer = new byte[byteLen + 1];
int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
Debug.Assert(bytesWritten == byteLen);
return buffer;
}
private SortVersion GetSortVersion()
{
Debug.Assert(!_invariantMode);
int sortVersion = Interop.GlobalizationInterop.GetSortVersion();
return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0,
(byte) (LCID >> 24),
(byte) ((LCID & 0x00FF0000) >> 16),
(byte) ((LCID & 0x0000FF00) >> 8),
(byte) (LCID & 0xFF)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using RegTesting.Tests.Framework.Elements;
using RegTesting.Tests.Framework.Enums;
using RegTesting.Tests.Framework.Logic.PageSettings;
using RegTesting.Tests.Framework.Properties;
namespace RegTesting.Tests.Framework.Logic.Extensions
{
/// <summary>
/// A extensions class for the WebDriver. Here we have some more useful functions we use often on a WebDriver
/// </summary>
public static class WebDriverExtensions
{
/// <summary>
/// Perfom a safe click on an element
/// </summary>
/// <param name="webDriver">the webdriver</param>
/// <param name="pageElement">the webelement to click</param>
public static void ClickElement(this IWebDriver webDriver, BasicPageElement pageElement)
{
Stopwatch startNew = Stopwatch.StartNew();
Click(FindAndScrollToElement(pageElement.By, Visibility.Visible, pageElement.ParentPageObject.PageSettings), pageElement);
startNew.Stop();
TestLog.Add("Waited " + startNew.ElapsedMilliseconds + " milliseconds to scroll and click element '" + pageElement.By + "'.");
}
/// <summary>
/// Perfom a safe click on an element
/// </summary>
/// <param name="webDriver">the webdriver</param>
/// <param name="pageElement">the webelement to click</param>
public static void ClickElementWithoutScrolling(this IWebDriver webDriver, BasicPageElement pageElement)
{
Stopwatch startNew = Stopwatch.StartNew();
Click(Find(pageElement.By, Visibility.Visible), pageElement);
startNew.Stop();
TestLog.Add("Waited " + startNew.ElapsedMilliseconds + " milliseconds to click element '" + pageElement.By + "'.");
}
private static void Click(Func<IWebDriver, IWebElement> findFunction, BasicPageElement pageElement)
{
IWebElement element = null;
TimeSpan timeout = new TimeSpan(0, 0, Settings.Default.TestTimeout);
WebDriverWait wait = new WebDriverWait(pageElement.WebDriver, timeout);
if (pageElement.ParentPageObject.PageSettings.PageUsesJquery && !pageElement.ParentPageObject.PageSettings.HasEndlessJQueryAnimation)
{
string errorMessage = null;
try
{
Stopwatch stopwatch = Stopwatch.StartNew();
wait.Timeout = new TimeSpan(0, 0, 0, 0, Settings.Default.WatiForAnimationsToComplete);
wait.Until(driver => AllAnimationsFinished(driver, pageElement.ParentPageObject.PageSettings, out errorMessage));
TestLog.Add("Waited " + stopwatch.ElapsedMilliseconds + " milliseconds for all anmiations to complete.");
}
catch (WebDriverTimeoutException e)
{
throw new TimeoutException(errorMessage + " Waited " + Settings.Default.WatiForAnimationsToComplete + " milliseconds to complete animations. Inner-exception: ", e);
}
}
try
{
wait.Timeout = timeout;
element = wait.Until(findFunction);
}
catch (WebDriverTimeoutException e)
{
string timeoutMessage = BuildTimeoutMessage(pageElement.By, Visibility.Hidden, e.Message, Settings.Default.TestTimeout, element);
throw new TimeoutException(timeoutMessage, e);
}
element.Click();
}
private static string GetAnimatedObjectMessage(IEnumerable<object> animatedObjects)
{
if (animatedObjects == null)
return String.Empty;
StringBuilder stringBuilder = new StringBuilder();
foreach (IWebElement animatedObject in animatedObjects)
{
string id = animatedObject.GetAttribute("id");
if (!string.IsNullOrEmpty(id))
{
stringBuilder.Append("Element with id: " + id);
}
else
{
stringBuilder.Append("A element with TagName: " + animatedObject.TagName);
}
stringBuilder.Append(", ");
}
return stringBuilder.ToString();
}
private static Func<IWebDriver, IWebElement> Find(By locator, Visibility visibilityFilter)
{
if (TestStatusManager.IsCanceled)
throw new TaskCanceledException("Canceled test.");
return d =>
{
try
{
IWebElement webElement = d.FindElement(locator);
if (FilterForVisibility(visibilityFilter, webElement))
return webElement;
return null;
}
catch (StaleElementReferenceException)
{
//For the case, that the objectreference we have, is no longer valid
}
catch (InvalidOperationException)
{
//For older IE: Sometimes we get an 'Error determining if element is displayed' error, so we can go around this error.
}
catch (WebDriverException)
{
//For some cases, our node is not responding (OpenQA.Selenium.WebDriverException: No response from server for url ...)
}
return null;
};
}
private static Func<IWebDriver, IWebElement> FindAndScrollToElement(By locator, Visibility visibilityFilter, AbstractPageSettings pageSettings)
{
if (TestStatusManager.IsCanceled)
throw new TaskCanceledException("Canceled test.");
return driver =>
{
IWebElement webElement = Find(locator, visibilityFilter).Invoke(driver);
if (webElement != null)
{
ScrollIntoView(driver, webElement, pageSettings);
TimeSpan timeout = new TimeSpan(0, 0, 3);
WebDriverWait wait = new WebDriverWait(driver, timeout)
{
Message = "Element by " + locator + " was not present in the viewport after timeout."
};
wait.Until(d => ElementIsInViewPort(d, locator));
return webElement;
}
return null;
};
}
/// <summary>
/// Waits for an element to get visible and then returns the element.
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="byLocator">The Locator of the element</param>
/// <param name="visibility">Wait until the element has this visibility.</param>
/// <returns>A IWebElement if we found the searched element. Fails with an TimeoutException else.</returns>
internal static IWebElement WaitForElement(this IWebDriver webDriver, By byLocator, Visibility visibility = Visibility.Visible)
{
return WaitForElementImpl(webDriver, byLocator, new TimeSpan(0, 0, Settings.Default.TestTimeout), visibility);
}
/// <summary>
/// Waits for an element to get visible and then returns the element.
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="byLocator">The Locator of the element</param>
/// <param name="timeout">A optional custom timeout (how long should we wait?)</param>
/// <param name="visibility">Wait until the element has this visibility.</param>
/// <returns>A IWebElement if we found the searched element. Fails with an TimeoutException else.</returns>
public static IWebElement WaitForElement(this IWebDriver webDriver, By byLocator, TimeSpan? timeout, Visibility visibility = Visibility.Visible)
{
return WaitForElementImpl(webDriver, byLocator, timeout != null ? (TimeSpan)timeout : new TimeSpan(0, 0, Settings.Default.TestTimeout), visibility);
}
private static IWebElement WaitForElementImpl(IWebDriver webDriver, By locator, TimeSpan timeout, Visibility visibilityFilter)
{
IWebElement element = null;
WebDriverWait wait = new WebDriverWait(new SystemClock(), webDriver, timeout, new TimeSpan(0,0,0,0,500));
try
{
Stopwatch startNew = Stopwatch.StartNew();
element = wait.Until(Find(locator, visibilityFilter));
startNew.Stop();
TestLog.Add("Waited " + startNew.ElapsedMilliseconds + " milliseconds to find element '" + locator + "'.");
}
catch (WebDriverTimeoutException e)
{
string timeoutMessage = BuildTimeoutMessage(locator, visibilityFilter, e.Message, Settings.Default.TestTimeout, element);
throw new TimeoutException(timeoutMessage, e);
}
return element;
}
private static string BuildTimeoutMessage(By byLocator, Visibility visibility, string errorMessage, int timeoutInSeconds, IWebElement webElement)
{
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.AppendFormat("({0}s): ", timeoutInSeconds);
if (errorMessage != null)
messageBuilder.Append(errorMessage + " ");
if (webElement == null)
messageBuilder.AppendFormat("Element still not " + visibility.ToString().ToLower() + " or was never present. Desired element: {0}", byLocator);
else
messageBuilder.AppendFormat("Element found {0}, but Element.Displayed={1}, Element.Enabled={2}" ,byLocator, webElement.Displayed, webElement.Enabled);
string messageBuilt = messageBuilder.ToString();
return messageBuilt;
}
private static void ScrollIntoView(IWebDriver webDriver, IWebElement webElement, AbstractPageSettings pageSettings)
{
if (webElement == null || !webElement.Displayed)
return;
try
{
webDriver.ExecuteScript(pageSettings, "arguments[0].scrollIntoView(true);", webElement);
}
catch (StaleElementReferenceException)
{
//For the case, that the objectreference we have, is no longer valid
}
catch (InvalidOperationException)
{
//For older IE: Sometimes we get an 'Error determining if element is displayed' error, so we can go around this error.
}
catch (WebDriverException)
{
//For some cases, our node is not responding (OpenQA.Selenium.WebDriverException: No response from server for url ...)
}
}
private static bool ElementIsInViewPort(IWebDriver webDriver, By byLocator)
{
IWebElement element = Find(byLocator, Visibility.Visible).Invoke(webDriver);
if (element == null)
return false;
if (element.Location.Y >= 0)
return true;
return false;
}
private static bool FilterForVisibility(Visibility visibilityFilter, IWebElement element)
{
return visibilityFilter == Visibility.Any ||
(visibilityFilter == Visibility.Visible && element.Displayed && element.Enabled) ||
(visibilityFilter == Visibility.Hidden && !element.Displayed);
}
/// <summary>
/// Waits for elements to get visible and then returns the elements.
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="byLocator">The Locator of the element</param>
/// <param name="expectedMinimumCountOfElements">The minimum count of elements to expect</param>
/// <returns>A IWebElement if we found the searched element. Fails with an TimeoutException else.</returns>
public static ReadOnlyCollection<IWebElement> WaitForElements(this IWebDriver webDriver, By byLocator, int expectedMinimumCountOfElements = 1)
{
return WaitForElementsImpl(webDriver, byLocator, expectedMinimumCountOfElements, null, -1);
}
/// <summary>
/// Waits for elements to get visible and then returns the elements.
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="byLocator">The Locator of the element</param>
/// <param name="expectedMinimumCountOfElements">The minimum count of elements to expect</param>
/// <param name="strErrorMessage">A Optional alternative message if we run in a timeout.</param>
/// <param name="intTimeout">A optional custom timeout (how long should we wait?)</param>
/// <returns>A IWebElement if we found the searched element. Fails with an TimeoutException else.</returns>
public static ReadOnlyCollection<IWebElement> WaitForElements(this IWebDriver webDriver, By byLocator, int expectedMinimumCountOfElements, string strErrorMessage, int intTimeout = -1)
{
return WaitForElementsImpl(webDriver, byLocator, expectedMinimumCountOfElements, strErrorMessage, intTimeout);
}
/// <summary>
/// Waits for elements to get visible and then returns the elements.
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="byLocator">The Locator of the element</param>
/// <param name="expectedMinimumCountOfElements">The minimum count of elements to expect</param>
/// <param name="intTimeout">A optional custom timeout (how long should we wait?)</param>
/// <returns>A IWebElement if we found the searched element. Fails with an TimeoutException else.</returns>
public static ReadOnlyCollection<IWebElement> WaitForElements(this IWebDriver webDriver, By byLocator, int expectedMinimumCountOfElements, int intTimeout)
{
return WaitForElementsImpl(webDriver, byLocator, expectedMinimumCountOfElements, null, intTimeout);
}
private static ReadOnlyCollection<IWebElement> WaitForElementsImpl(IWebDriver webDriver, By byLocator, int expectedMinimumCountOfElements, string errorMessage, int timeoutInSeconds)
{
if (timeoutInSeconds == -1) timeoutInSeconds = Settings.Default.TestTimeout;
for (int intSecond = 0;; intSecond++)
{
if (intSecond == timeoutInSeconds)
throw new TimeoutException(errorMessage ?? string.Format("({0}s): Still not {1} elements located by: {2}", timeoutInSeconds, expectedMinimumCountOfElements, byLocator));
try
{
if (TestStatusManager.IsCanceled)
throw new TaskCanceledException("Canceled test.");
ReadOnlyCollection<IWebElement> objElements = webDriver.FindElements(byLocator);
if (objElements.Count >= expectedMinimumCountOfElements)
return objElements;
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception)
{
}
Thread.Sleep(1000);
}
}
/// <summary>
/// Returns if an element is present. If no element is found the function returns false, there is no timeout and retry.
/// </summary>
/// <param name="objDriver">Extension hook</param>
/// <param name="objBy">The Locator of the element</param>
/// <returns>A boolean if the element is present</returns>
public static bool IsElementPresent(this IWebDriver objDriver, By objBy)
{
try
{
if (TestStatusManager.IsCanceled) throw new TaskCanceledException("Canceled test.");
objDriver.FindElement(objBy);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
/// <summary>
/// Returns if an element is present and display. If no element is found the function returns false, there is no retry.
/// </summary>
/// <param name="driver">Extension hook</param>
/// <param name="locator">The Locator of the element</param>
/// <param name="timeoutInSeconds">An optional timeout.</param>
/// <returns>A boolean if the element is present</returns>
public static bool IsElementDisplayed(this IWebDriver driver, By locator, int timeoutInSeconds = 3)
{
try
{
WaitForElement(driver, locator, new TimeSpan(0,0,timeoutInSeconds));
}
catch (TimeoutException)
{
return false;
}
try
{
if (TestStatusManager.IsCanceled) throw new TaskCanceledException("Canceled test.");
IWebElement objElement = driver.FindElement(locator);
return objElement.Displayed;
}
catch (NoSuchElementException)
{
return false;
}
}
/// <summary>
/// Handle a alert and click on accept (if accept=true) or dismiss (if accept=false)
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="accept">If we should accept or dismiss the alert.</param>
public static void HandleAlert(this IWebDriver webDriver, bool accept)
{
HandleAlertImpl(webDriver, accept, null, -1);
}
/// <summary>
/// Handle a alert and click on accept (if accept=true) or dismiss (if accept=false)
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="accept">If we should accept or dismiss the alert.</param>
/// <param name="errorMessage">A Optional alternative message if we run in a timeout.</param>
/// <param name="timeoutInSeconds">A optional custom timeout (how long should we wait?)</param>
public static void HandleAlert(this IWebDriver webDriver, bool accept, string errorMessage, int timeoutInSeconds = -1)
{
HandleAlertImpl(webDriver, accept, errorMessage, timeoutInSeconds);
}
/// <summary>
/// Handle a alert and click on accept (if accept=true) or dismiss (if accept=false)
/// </summary>
/// <param name="webDriver">Extension hook</param>
/// <param name="accept">If we should accept or dismiss the alert.</param>
/// <param name="timeoutInSeconds">A optional custom timeout (how long should we wait?)</param>
public static void HandleAlert(this IWebDriver webDriver, bool accept, int timeoutInSeconds)
{
HandleAlertImpl(webDriver, accept, null, timeoutInSeconds);
}
private static void HandleAlertImpl(IWebDriver webDriver, bool accept, string errorMessage, int timeoutInSeconds)
{
if (timeoutInSeconds == -1) timeoutInSeconds = Settings.Default.TestTimeout;
for (int second = 0;; second++)
{
Thread.Sleep(1000);
if (second == timeoutInSeconds) throw new NoAlertPresentException(errorMessage ?? ("Timeout: No alert."));
try
{
if (TestStatusManager.IsCanceled) throw new TaskCanceledException("Canceled test.");
if (accept) webDriver.SwitchTo().Alert().Accept();
else webDriver.SwitchTo().Alert().Dismiss();
break;
}
catch (NoAlertPresentException)
{
//No Alert Present, wait and try again until timeout
}
}
}
public static void SwitchToTab(this IWebDriver webDriver, string urlSegment)
{
if (string.IsNullOrWhiteSpace(urlSegment))
throw new ArgumentNullException();
AsyncWebDriverCalls asyncCalls = new AsyncWebDriverCalls();
Task<ReadOnlyCollection<string>> getWindowHandlesTask = asyncCalls.GetWindowHandlesAsync(webDriver);
getWindowHandlesTask.Wait();
ReadOnlyCollection<string> windowHandles = getWindowHandlesTask.Result;
if (windowHandles.Count <= 1)
{
TestLog.Add("Only one Tab recognized. Cancelling tabswitch => unnecessary.");
return;
}
TestLog.Add("Try switching to tab with url containing '" + urlSegment + "'. tabcount: " + windowHandles.Count);
bool tabFound = false;
int currentTabWindowIndex = windowHandles.IndexOf(webDriver.CurrentWindowHandle);
for (int index = currentTabWindowIndex; index <= windowHandles.Count; index++)
{
int realIndex = (index + currentTabWindowIndex + 1)%windowHandles.Count;
if (DoTabSwitchWithIndex(realIndex, webDriver, urlSegment, asyncCalls, windowHandles))
{
tabFound = true;
break;
}
}
if (tabFound)
return;
TestLog.Add("No window with url containing: " + urlSegment);
TestLog.Add("Current WindowHandle-Url: " + webDriver.Url);
throw new Exception("No window with url-segment: '" + urlSegment + "'");
}
private static bool DoTabSwitchWithIndex(int index, IWebDriver webDriver, string urlSegment, AsyncWebDriverCalls asyncCalls,
ReadOnlyCollection<string> windowHandles)
{
string windowHandle = windowHandles[index];
Task<string> getCurrentUrlTask = asyncCalls.GetCurrentUrlTask(webDriver);
getCurrentUrlTask.Wait();
webDriver.SwitchTo().Window(windowHandle);
Task<bool> nextUrlTask = asyncCalls.TabActuallySwitched(webDriver, urlSegment, getCurrentUrlTask.Result);
nextUrlTask.Wait();
if (!nextUrlTask.Result)
{
return false;
}
Task<string> task = asyncCalls.GetCurrentUrlTask(webDriver);
task.Wait();
string urlAfterSwitch = task.Result;
TestLog.Add("Switched to tab with url-segment " + urlSegment + ". Full url = " + urlAfterSwitch);
asyncCalls.WaitWindowMaximize(webDriver);
return true;
}
public static TResult ExecuteJavaScriptAsync<TResult>(this IWebDriver webDriver, AbstractPageSettings pageSettings, string script, params object[] args)
{
WaitForJQueryIsLoaded(webDriver, pageSettings);
return (TResult)GetJavaScriptExecutor(webDriver).ExecuteAsyncScript(script, args);
}
public static TResult ExecuteScript<TResult>(this IWebDriver webDriver, AbstractPageSettings pageSettings, string script, params object[] args)
{
WaitForJQueryIsLoaded(webDriver, pageSettings);
dynamic objectToCast = GetJavaScriptExecutor(webDriver).ExecuteScript(script, args);
if (objectToCast != null)
{
// ReSharper disable once SuspiciousTypeConversion.Global
//The Webdriver casts Collection<object> when the list is empty but when it detects that the elements can be castet to IWebElement it will do so.
//Therefore the ExecuteScript will give you for an empty javascript list a ReadOnlyCollection<object>
//but a ReadOnlyCollection<IWebElements> when there is at least one element within the JavaScript array/object!
if (objectToCast is ReadOnlyCollection<object> && objectToCast.Count == 0)
{
var genericTypeArgument = typeof(TResult).GetGenericArguments()[0];
Type paraType = typeof(List<>).MakeGenericType(genericTypeArgument);
var para = Activator.CreateInstance(paraType);
Type readonlyType = typeof(ReadOnlyCollection<>);
Type result = readonlyType.MakeGenericType(genericTypeArgument);
return (TResult)Activator.CreateInstance(result, para);
}
}
return (TResult)objectToCast;
}
public static void ExecuteScript(this IWebDriver webDriver, AbstractPageSettings pageSettings, string script, params object[] args)
{
WaitForJQueryIsLoaded(webDriver, pageSettings);
ExecuteScript<object>(webDriver, pageSettings, script, args);
}
private static IJavaScriptExecutor GetJavaScriptExecutor(this IWebDriver driver)
{
return driver as IJavaScriptExecutor;
}
/// <summary>
/// Wait for all animations to be finished.
/// </summary>
private static bool AllAnimationsFinished(IWebDriver driver, AbstractPageSettings pageSettings, out string errorMessage)
{
if (pageSettings.PageUsesJquery && pageSettings.HasEndlessJQueryAnimation)
{
errorMessage = "Page has a endless animation. Cannot wait for animations finished.";
return true;
}
bool jqueryIsLoaded;
if (pageSettings.PageUsesJquery)
{
jqueryIsLoaded = JQueryIsLoaded(driver);
}
else
{
errorMessage = "Cannot wait for animations, page uses no JQuery. ";
return true;
}
if (jqueryIsLoaded)
{
TestLog.Add("Get all running JQuery animations...");
ReadOnlyCollection<IWebElement> animatedObjects = driver.ExecuteScript<ReadOnlyCollection<IWebElement>>(pageSettings, "return $(':animated').toArray();");
if (animatedObjects.Count != 0)
{
errorMessage = "Tried to click but there were still running JQuery animations on the webpage which are not excluded from waiting for them to finish."
+ " || Objects still animated: " + GetAnimatedObjectMessage(animatedObjects) + " ||.";
return false;
}
errorMessage = string.Empty;
return true;
}
errorMessage = "JQuery was not loaded. Cannot wait for Animations";
return false;
}
private static void WaitForJQueryIsLoaded(this IWebDriver webDriver, AbstractPageSettings pageSettings)
{
if (!pageSettings.PageUsesJquery)
return;
TimeSpan timeout = new TimeSpan(0, 0, 5);
WebDriverWait wait = new WebDriverWait(webDriver, timeout) { Message = "JQuery was not loaded after " + timeout.Seconds + " seconds." };
wait.Until(JQueryIsLoaded);
}
private static bool JQueryIsLoaded(IWebDriver webDriver)
{
return (bool)webDriver.GetJavaScriptExecutor().ExecuteScript("return typeof($)==='function'");
}
}
}
| |
// Copyright 2011 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.
namespace Microsoft.Data.OData.Atom
{
#region Namespaces
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Xml;
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Metadata;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// Reader for the EPM syndication-only. Read the EPM properties from ATOM metadata OM.
/// </summary>
internal sealed class EpmSyndicationReader : EpmReader
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="entryState">The reader entry state for the entry to which the EPM is applied.</param>
/// <param name="inputContext">The input context currently in use.</param>
private EpmSyndicationReader(
IODataAtomReaderEntryState entryState,
ODataAtomInputContext inputContext)
: base(entryState, inputContext)
{
}
/// <summary>
/// Reads the syndication EPM for an entry.
/// </summary>
/// <param name="entryState">The reader entry state for the entry to which the EPM is applied.</param>
/// <param name="inputContext">The input context currently in use.</param>
internal static void ReadEntryEpm(
IODataAtomReaderEntryState entryState,
ODataAtomInputContext inputContext)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(entryState != null, "entryState != null");
Debug.Assert(entryState.CachedEpm != null, "To read entry EPM, the entity type must have an EPM annotation.");
Debug.Assert(inputContext != null, "inputContext != null");
EpmSyndicationReader epmSyndicationReader = new EpmSyndicationReader(entryState, inputContext);
epmSyndicationReader.ReadEntryEpm();
}
/// <summary>
/// Reads an EPM for the entire entry.
/// </summary>
private void ReadEntryEpm()
{
// Note that this property access will create empty entry metadata if none were read yet.
AtomEntryMetadata entryMetadata = this.EntryState.AtomEntryMetadata;
Debug.Assert(entryMetadata != null, "entryMetadata != null");
// If there are no syndication mappings, just return null.
EpmTargetPathSegment syndicationRootSegment = this.EntryState.CachedEpm.EpmTargetTree.SyndicationRoot;
Debug.Assert(syndicationRootSegment != null, "EPM Target tree must always have syndication root.");
if (syndicationRootSegment.SubSegments.Count == 0)
{
return;
}
foreach (EpmTargetPathSegment targetSegment in syndicationRootSegment.SubSegments)
{
if (targetSegment.HasContent)
{
this.ReadPropertyValueSegment(targetSegment, entryMetadata);
}
else
{
this.ReadParentSegment(targetSegment, entryMetadata);
}
}
}
/// <summary>
/// Reads a leaf segment which maps to a property value.
/// </summary>
/// <param name="targetSegment">The segment being read.</param>
/// <param name="entryMetadata">The ATOM entry metadata to read from.</param>
private void ReadPropertyValueSegment(EpmTargetPathSegment targetSegment, AtomEntryMetadata entryMetadata)
{
Debug.Assert(targetSegment != null, "targetSegment != null");
Debug.Assert(entryMetadata != null, "entryMetadata != null");
EntityPropertyMappingInfo epmInfo = targetSegment.EpmInfo;
Debug.Assert(
epmInfo != null && epmInfo.Attribute != null,
"If the segment has content it must have EpmInfo which in turn must have the Epm attribute");
switch (epmInfo.Attribute.TargetSyndicationItem)
{
case SyndicationItemProperty.Updated:
if (this.MessageReaderSettings.ReaderBehavior.FormatBehaviorKind == ODataBehaviorKind.WcfDataServicesClient)
{
if (entryMetadata.UpdatedString != null)
{
this.SetEntryEpmValue(targetSegment.EpmInfo, entryMetadata.UpdatedString);
}
}
else if (entryMetadata.Updated.HasValue)
{
this.SetEntryEpmValue(targetSegment.EpmInfo, XmlConvert.ToString(entryMetadata.Updated.Value));
}
break;
case SyndicationItemProperty.Published:
if (this.MessageReaderSettings.ReaderBehavior.FormatBehaviorKind == ODataBehaviorKind.WcfDataServicesClient)
{
if (entryMetadata.PublishedString != null)
{
this.SetEntryEpmValue(targetSegment.EpmInfo, entryMetadata.PublishedString);
}
}
else if (entryMetadata.Published.HasValue)
{
this.SetEntryEpmValue(targetSegment.EpmInfo, XmlConvert.ToString(entryMetadata.Published.Value));
}
break;
case SyndicationItemProperty.Rights:
this.ReadTextConstructEpm(targetSegment, entryMetadata.Rights);
break;
case SyndicationItemProperty.Summary:
this.ReadTextConstructEpm(targetSegment, entryMetadata.Summary);
break;
case SyndicationItemProperty.Title:
this.ReadTextConstructEpm(targetSegment, entryMetadata.Title);
break;
default:
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.EpmSyndicationReader_ReadEntryEpm_ContentTarget));
}
}
/// <summary>
/// Reads a non-leaf segment which has sub segments.
/// </summary>
/// <param name="targetSegment">The segment being read.</param>
/// <param name="entryMetadata">The ATOM entry metadata to read from.</param>
private void ReadParentSegment(EpmTargetPathSegment targetSegment, AtomEntryMetadata entryMetadata)
{
Debug.Assert(targetSegment != null, "targetSegment != null");
Debug.Assert(entryMetadata != null, "entryMetadata != null");
switch (targetSegment.SegmentName)
{
case AtomConstants.AtomAuthorElementName:
// If a singleton property (non-collection) is mapped to author and there are multiple authors
// EPM uses the first author.
AtomPersonMetadata authorMetadata = entryMetadata.Authors.FirstOrDefault();
if (authorMetadata != null)
{
this.ReadPersonEpm(
ReaderUtils.GetPropertiesList(this.EntryState.Entry.Properties),
this.EntryState.EntityType.ToTypeReference(),
targetSegment,
authorMetadata);
}
break;
case AtomConstants.AtomContributorElementName:
// If a singleton property (non-collection) is mapped to contributor and there are multiple contributors
// EPM uses the first contributor.
AtomPersonMetadata contributorMetadata = entryMetadata.Contributors.FirstOrDefault();
if (contributorMetadata != null)
{
this.ReadPersonEpm(
ReaderUtils.GetPropertiesList(this.EntryState.Entry.Properties),
this.EntryState.EntityType.ToTypeReference(),
targetSegment,
contributorMetadata);
}
break;
default:
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.EpmSyndicationReader_ReadParentSegment_TargetSegmentName));
}
}
/// <summary>
/// Reads EPM values from a person construct (author or contributor).
/// </summary>
/// <param name="targetList">The target list, this can be either a list of properties (on entry or complex value),
/// or a list of items (for a collection of primitive types).</param>
/// <param name="targetTypeReference">The type of the value on which to set the property (can be entity, complex or primitive).</param>
/// <param name="targetSegment">The target segment which points to either author or contributor element.</param>
/// <param name="personMetadata">The person ATOM metadata to read from.</param>
private void ReadPersonEpm(IList targetList, IEdmTypeReference targetTypeReference, EpmTargetPathSegment targetSegment, AtomPersonMetadata personMetadata)
{
Debug.Assert(targetList != null, "targetList != null");
Debug.Assert(targetTypeReference != null, "targetTypeReference != null");
Debug.Assert(targetSegment != null, "targetSegment != null");
Debug.Assert(
targetSegment.SegmentName == AtomConstants.AtomAuthorElementName || targetSegment.SegmentName == AtomConstants.AtomContributorElementName,
"targetSegment must be author or contributor.");
Debug.Assert(personMetadata != null, "personMetadata != null");
foreach (EpmTargetPathSegment subSegment in targetSegment.SubSegments)
{
Debug.Assert(subSegment.HasContent, "sub segment of author segment must have content, there are no subsegments which don't have content under author.");
Debug.Assert(
subSegment.EpmInfo != null && subSegment.EpmInfo.Attribute != null && subSegment.EpmInfo.Attribute.TargetSyndicationItem != SyndicationItemProperty.CustomProperty,
"We should never find a subsegment without EPM attribute or for custom mapping when writing syndication person EPM.");
switch (subSegment.EpmInfo.Attribute.TargetSyndicationItem)
{
case SyndicationItemProperty.AuthorName:
case SyndicationItemProperty.ContributorName:
// Note that person name can never specify true null in EPM, since it can't have the m:null attribute on it.
string personName = personMetadata.Name;
if (personName != null)
{
this.SetEpmValue(targetList, targetTypeReference, subSegment.EpmInfo, personName);
}
break;
case SyndicationItemProperty.AuthorEmail:
case SyndicationItemProperty.ContributorEmail:
string personEmail = personMetadata.Email;
if (personEmail != null)
{
this.SetEpmValue(targetList, targetTypeReference, subSegment.EpmInfo, personEmail);
}
break;
case SyndicationItemProperty.AuthorUri:
case SyndicationItemProperty.ContributorUri:
string personUri = personMetadata.UriFromEpm;
if (personUri != null)
{
this.SetEpmValue(targetList, targetTypeReference, subSegment.EpmInfo, personUri);
}
break;
default:
// Unhandled EpmTargetPathSegment.SegmentName.
throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.EpmSyndicationReader_ReadPersonEpm));
}
}
}
/// <summary>
/// Reads the value of the ATOM text construct and sets it to the EPM.
/// </summary>
/// <param name="targetSegment">The EPM target segment for the value to read.</param>
/// <param name="textConstruct">The text construct to read it from (can be null).</param>
private void ReadTextConstructEpm(EpmTargetPathSegment targetSegment, AtomTextConstruct textConstruct)
{
Debug.Assert(targetSegment != null, "targetSegment != null");
Debug.Assert(targetSegment.HasContent, "We can only read text construct values into segments which are mapped to a leaf property.");
if (textConstruct != null)
{
if (textConstruct.Text != null)
{
this.SetEntryEpmValue(targetSegment.EpmInfo, textConstruct.Text);
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Multiplayer.MatchTypes.TeamVersus;
using osu.Game.Online.Rooms;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.OnlinePlay.Multiplayer.Spectate;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osu.Game.Screens.Play.PlayerSettings;
using osu.Game.Tests.Beatmaps.IO;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiSpectatorScreen : MultiplayerTestScene
{
[Resolved]
private OsuGameBase game { get; set; }
[Resolved]
private OsuConfigManager config { get; set; }
[Resolved]
private BeatmapManager beatmapManager { get; set; }
private MultiSpectatorScreen spectatorScreen;
private readonly List<MultiplayerRoomUser> playingUsers = new List<MultiplayerRoomUser>();
private BeatmapSetInfo importedSet;
private BeatmapInfo importedBeatmap;
private int importedBeatmapId;
[BackgroundDependencyLoader]
private void load()
{
importedSet = BeatmapImportHelper.LoadOszIntoOsu(game, virtualTrack: true).GetResultSafely();
importedBeatmap = importedSet.Beatmaps.First(b => b.Ruleset.OnlineID == 0);
importedBeatmapId = importedBeatmap.OnlineID;
}
[SetUp]
public new void Setup() => Schedule(() => playingUsers.Clear());
[Test]
public void TestDelayedStart()
{
AddStep("start players silently", () =>
{
OnlinePlayDependencies.MultiplayerClient.AddUser(new APIUser { Id = PLAYER_1_ID }, true);
OnlinePlayDependencies.MultiplayerClient.AddUser(new APIUser { Id = PLAYER_2_ID }, true);
playingUsers.Add(new MultiplayerRoomUser(PLAYER_1_ID));
playingUsers.Add(new MultiplayerRoomUser(PLAYER_2_ID));
});
loadSpectateScreen(false);
AddWaitStep("wait a bit", 10);
AddStep("load player first_player_id", () => SpectatorClient.SendStartPlay(PLAYER_1_ID, importedBeatmapId));
AddUntilStep("one player added", () => spectatorScreen.ChildrenOfType<Player>().Count() == 1);
AddWaitStep("wait a bit", 10);
AddStep("load player second_player_id", () => SpectatorClient.SendStartPlay(PLAYER_2_ID, importedBeatmapId));
AddUntilStep("two players added", () => spectatorScreen.ChildrenOfType<Player>().Count() == 2);
}
[Test]
public void TestGeneral()
{
int[] userIds = getPlayerIds(4);
start(userIds);
loadSpectateScreen();
sendFrames(userIds, 1000);
AddWaitStep("wait a bit", 20);
}
[Test]
public void TestSpectatorPlayerInteractiveElementsHidden()
{
HUDVisibilityMode originalConfigValue = default;
AddStep("get original config hud visibility", () => originalConfigValue = config.Get<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode));
AddStep("set config hud visibility to always", () => config.SetValue(OsuSetting.HUDVisibilityMode, HUDVisibilityMode.Always));
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen(false);
AddUntilStep("wait for player loaders", () => this.ChildrenOfType<PlayerLoader>().Count() == 2);
AddAssert("all player loader settings hidden", () => this.ChildrenOfType<PlayerLoader>().All(l => !l.ChildrenOfType<FillFlowContainer<PlayerSettingsGroup>>().Any()));
AddUntilStep("wait for players to load", () => spectatorScreen.AllPlayersLoaded);
// components wrapped in skinnable target containers load asynchronously, potentially taking more than one frame to load.
// therefore use until step rather than direct assert to account for that.
AddUntilStep("all interactive elements removed", () => this.ChildrenOfType<Player>().All(p =>
!p.ChildrenOfType<PlayerSettingsOverlay>().Any() &&
!p.ChildrenOfType<HoldForMenuButton>().Any() &&
p.ChildrenOfType<SongProgressBar>().SingleOrDefault()?.ShowHandle == false));
AddStep("restore config hud visibility", () => config.SetValue(OsuSetting.HUDVisibilityMode, originalConfigValue));
}
[Test]
public void TestTeamDisplay()
{
AddStep("start players", () =>
{
var player1 = OnlinePlayDependencies.MultiplayerClient.AddUser(new APIUser { Id = PLAYER_1_ID }, true);
player1.MatchState = new TeamVersusUserState
{
TeamID = 0,
};
var player2 = OnlinePlayDependencies.MultiplayerClient.AddUser(new APIUser { Id = PLAYER_2_ID }, true);
player2.MatchState = new TeamVersusUserState
{
TeamID = 1,
};
SpectatorClient.SendStartPlay(player1.UserID, importedBeatmapId);
SpectatorClient.SendStartPlay(player2.UserID, importedBeatmapId);
playingUsers.Add(player1);
playingUsers.Add(player2);
});
loadSpectateScreen();
sendFrames(PLAYER_1_ID, 1000);
sendFrames(PLAYER_2_ID, 1000);
AddWaitStep("wait a bit", 20);
}
[Test]
public void TestTimeDoesNotProgressWhileAllPlayersPaused()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
sendFrames(PLAYER_1_ID, 40);
sendFrames(PLAYER_2_ID, 20);
checkPaused(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID, false);
AddAssert("master clock still running", () => this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning);
checkPaused(PLAYER_1_ID, true);
AddUntilStep("master clock paused", () => !this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning);
}
[Test]
public void TestPlayersMustStartSimultaneously()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
// Send frames for one player only, both should remain paused.
sendFrames(PLAYER_1_ID, 20);
checkPausedInstant(PLAYER_1_ID, true);
checkPausedInstant(PLAYER_2_ID, true);
// Send frames for the other player, both should now start playing.
sendFrames(PLAYER_2_ID, 20);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, false);
}
[Test]
public void TestPlayersDoNotStartSimultaneouslyIfBufferingForMaximumStartDelay()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
// Send frames for one player only, both should remain paused.
sendFrames(PLAYER_1_ID, 1000);
checkPausedInstant(PLAYER_1_ID, true);
checkPausedInstant(PLAYER_2_ID, true);
// Wait for the start delay seconds...
AddWaitStep("wait maximum start delay seconds", (int)(CatchUpSyncManager.MAXIMUM_START_DELAY / TimePerAction));
// Player 1 should start playing by itself, player 2 should remain paused.
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, true);
}
[Test]
public void TestPlayersContinueWhileOthersBuffer()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
// Send initial frames for both players. A few more for player 1.
sendFrames(PLAYER_1_ID, 20);
sendFrames(PLAYER_2_ID);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, false);
// Eventually player 2 will pause, player 1 must remain running.
checkPaused(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID, false);
// Eventually both players will run out of frames and should pause.
checkPaused(PLAYER_1_ID, true);
checkPausedInstant(PLAYER_2_ID, true);
// Send more frames for the first player only. Player 1 should start playing with player 2 remaining paused.
sendFrames(PLAYER_1_ID, 20);
checkPausedInstant(PLAYER_2_ID, true);
checkPausedInstant(PLAYER_1_ID, false);
// Send more frames for the second player. Both should be playing
sendFrames(PLAYER_2_ID, 20);
checkPausedInstant(PLAYER_2_ID, false);
checkPausedInstant(PLAYER_1_ID, false);
}
[Test]
public void TestPlayersCatchUpAfterFallingBehind()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
// Send initial frames for both players. A few more for player 1.
sendFrames(PLAYER_1_ID, 1000);
sendFrames(PLAYER_2_ID, 30);
checkPausedInstant(PLAYER_1_ID, false);
checkPausedInstant(PLAYER_2_ID, false);
// Eventually player 2 will run out of frames and should pause.
checkPaused(PLAYER_2_ID, true);
AddWaitStep("wait a few more frames", 10);
// Send more frames for player 2. It should unpause.
sendFrames(PLAYER_2_ID, 1000);
checkPausedInstant(PLAYER_2_ID, false);
// Player 2 should catch up to player 1 after unpausing.
waitForCatchup(PLAYER_2_ID);
AddWaitStep("wait a bit", 10);
}
[Test]
public void TestMostInSyncUserIsAudioSource()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
loadSpectateScreen();
assertMuted(PLAYER_1_ID, true);
assertMuted(PLAYER_2_ID, true);
sendFrames(PLAYER_1_ID);
sendFrames(PLAYER_2_ID, 20);
checkPaused(PLAYER_1_ID, false);
assertOneNotMuted();
checkPaused(PLAYER_1_ID, true);
assertMuted(PLAYER_1_ID, true);
assertMuted(PLAYER_2_ID, false);
sendFrames(PLAYER_1_ID, 100);
waitForCatchup(PLAYER_1_ID);
checkPaused(PLAYER_2_ID, true);
assertMuted(PLAYER_1_ID, false);
assertMuted(PLAYER_2_ID, true);
sendFrames(PLAYER_2_ID, 100);
waitForCatchup(PLAYER_2_ID);
assertMuted(PLAYER_1_ID, false);
assertMuted(PLAYER_2_ID, true);
}
[Test]
public void TestSpectatingDuringGameplay()
{
int[] players = { PLAYER_1_ID, PLAYER_2_ID };
start(players);
sendFrames(players, 300);
loadSpectateScreen();
sendFrames(players, 300);
AddUntilStep("playing from correct point in time", () => this.ChildrenOfType<DrawableRuleset>().All(r => r.FrameStableClock.CurrentTime > 30000));
}
[Test]
public void TestSpectatingDuringGameplayWithLateFrames()
{
start(new[] { PLAYER_1_ID, PLAYER_2_ID });
sendFrames(new[] { PLAYER_1_ID, PLAYER_2_ID }, 300);
loadSpectateScreen();
sendFrames(PLAYER_1_ID, 300);
AddWaitStep("wait maximum start delay seconds", (int)(CatchUpSyncManager.MAXIMUM_START_DELAY / TimePerAction));
checkPaused(PLAYER_1_ID, false);
sendFrames(PLAYER_2_ID, 300);
AddUntilStep("player 2 playing from correct point in time", () => getPlayer(PLAYER_2_ID).ChildrenOfType<DrawableRuleset>().Single().FrameStableClock.CurrentTime > 30000);
}
[Test]
public void TestPlayersLeaveWhileSpectating()
{
start(getPlayerIds(4));
sendFrames(getPlayerIds(4), 300);
loadSpectateScreen();
for (int count = 3; count >= 0; count--)
{
int id = PLAYER_1_ID + count;
end(id);
AddUntilStep($"{id} area grayed", () => getInstance(id).Colour != Color4.White);
AddUntilStep($"{id} score quit set", () => getLeaderboardScore(id).HasQuit.Value);
sendFrames(getPlayerIds(count), 300);
}
Player player = null;
AddStep($"get {PLAYER_1_ID} player instance", () => player = getInstance(PLAYER_1_ID).ChildrenOfType<Player>().Single());
start(new[] { PLAYER_1_ID });
sendFrames(PLAYER_1_ID, 300);
AddAssert($"{PLAYER_1_ID} player instance still same", () => getInstance(PLAYER_1_ID).ChildrenOfType<Player>().Single() == player);
AddAssert($"{PLAYER_1_ID} area still grayed", () => getInstance(PLAYER_1_ID).Colour != Color4.White);
AddAssert($"{PLAYER_1_ID} score quit still set", () => getLeaderboardScore(PLAYER_1_ID).HasQuit.Value);
}
/// <summary>
/// Tests spectating with a gameplay start time set to a negative value.
/// Simulating beatmaps with high <see cref="BeatmapInfo.AudioLeadIn"/> or negative time storyboard elements.
/// </summary>
[Test]
public void TestNegativeGameplayStartTime()
{
start(PLAYER_1_ID);
loadSpectateScreen(false, -500);
// to ensure negative gameplay start time does not affect spectator, send frames exactly after StartGameplay().
// (similar to real spectating sessions in which the first frames get sent between StartGameplay() and player load complete)
AddStep("send frames at gameplay start", () => getInstance(PLAYER_1_ID).OnGameplayStarted += () => SpectatorClient.SendFramesFromUser(PLAYER_1_ID, 100));
AddUntilStep("wait for player load", () => spectatorScreen.AllPlayersLoaded);
AddWaitStep("wait for progression", 3);
assertNotCatchingUp(PLAYER_1_ID);
assertRunning(PLAYER_1_ID);
}
private void loadSpectateScreen(bool waitForPlayerLoad = true, double? gameplayStartTime = null)
{
AddStep(!gameplayStartTime.HasValue ? "load screen" : $"load screen (start = {gameplayStartTime}ms)", () =>
{
Beatmap.Value = beatmapManager.GetWorkingBeatmap(importedBeatmap);
Ruleset.Value = importedBeatmap.Ruleset;
LoadScreen(spectatorScreen = new TestMultiSpectatorScreen(SelectedRoom.Value, playingUsers.ToArray(), gameplayStartTime));
});
AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded && (!waitForPlayerLoad || spectatorScreen.AllPlayersLoaded));
}
private void start(int userId, int? beatmapId = null) => start(new[] { userId }, beatmapId);
private void start(int[] userIds, int? beatmapId = null)
{
AddStep("start play", () =>
{
foreach (int id in userIds)
{
var user = new MultiplayerRoomUser(id)
{
User = new APIUser { Id = id },
};
OnlinePlayDependencies.MultiplayerClient.AddUser(user.User, true);
SpectatorClient.SendStartPlay(id, beatmapId ?? importedBeatmapId);
playingUsers.Add(user);
}
});
}
private void end(int userId)
{
AddStep($"end play for {userId}", () =>
{
var user = playingUsers.Single(u => u.UserID == userId);
OnlinePlayDependencies.MultiplayerClient.RemoveUser(user.User.AsNonNull());
SpectatorClient.SendEndPlay(userId);
playingUsers.Remove(user);
});
}
private void sendFrames(int userId, int count = 10) => sendFrames(new[] { userId }, count);
private void sendFrames(int[] userIds, int count = 10)
{
AddStep("send frames", () =>
{
foreach (int id in userIds)
SpectatorClient.SendFramesFromUser(id, count);
});
}
private void checkPaused(int userId, bool state)
=> AddUntilStep($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state);
private void checkPausedInstant(int userId, bool state)
{
checkPaused(userId, state);
// Todo: The following should work, but is broken because SpectatorScreen retrieves the WorkingBeatmap via the BeatmapManager, bypassing the test scene clock and running real-time.
// AddAssert($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state);
}
private void assertOneNotMuted() => AddAssert("one player not muted", () => spectatorScreen.ChildrenOfType<PlayerArea>().Count(p => !p.Mute) == 1);
private void assertMuted(int userId, bool muted)
=> AddAssert($"{userId} {(muted ? "is" : "is not")} muted", () => getInstance(userId).Mute == muted);
private void assertRunning(int userId)
=> AddAssert($"{userId} clock running", () => getInstance(userId).GameplayClock.IsRunning);
private void assertNotCatchingUp(int userId)
=> AddAssert($"{userId} in sync", () => !getInstance(userId).GameplayClock.IsCatchingUp);
private void waitForCatchup(int userId)
=> AddUntilStep($"{userId} not catching up", () => !getInstance(userId).GameplayClock.IsCatchingUp);
private Player getPlayer(int userId) => getInstance(userId).ChildrenOfType<Player>().Single();
private PlayerArea getInstance(int userId) => spectatorScreen.ChildrenOfType<PlayerArea>().Single(p => p.UserId == userId);
private GameplayLeaderboardScore getLeaderboardScore(int userId) => spectatorScreen.ChildrenOfType<GameplayLeaderboardScore>().Single(s => s.User?.Id == userId);
private int[] getPlayerIds(int count) => Enumerable.Range(PLAYER_1_ID, count).ToArray();
private class TestMultiSpectatorScreen : MultiSpectatorScreen
{
private readonly double? gameplayStartTime;
public TestMultiSpectatorScreen(Room room, MultiplayerRoomUser[] users, double? gameplayStartTime = null)
: base(room, users)
{
this.gameplayStartTime = gameplayStartTime;
}
protected override MasterGameplayClockContainer CreateMasterGameplayClockContainer(WorkingBeatmap beatmap)
=> new MasterGameplayClockContainer(beatmap, gameplayStartTime ?? 0, gameplayStartTime.HasValue);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for exception handling on various task execution stages.
/// </summary>
public class IgniteExceptionTaskSelfTest : AbstractTaskTest
{
/** Error mode. */
private static ErrorMode _mode;
/** Observed job errors. */
private static readonly ICollection<Exception> JobErrs = new List<Exception>();
/// <summary>
/// Constructor.
/// </summary>
public IgniteExceptionTaskSelfTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected IgniteExceptionTaskSelfTest(bool fork) : base(fork) { }
/// <summary>
/// Test error occurred during map step.
/// </summary>
[Test]
public void TestMapError()
{
_mode = ErrorMode.MapErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.MapErr, e.Mode);
}
/// <summary>
/// Test not-marshalable error occurred during map step.
/// </summary>
[Test]
public void TestMapNotMarshalableError()
{
_mode = ErrorMode.MapErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.MapErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test task behavior when job produced by mapper is not marshalable.
/// </summary>
[Test]
public void TestMapNotMarshalableJob()
{
_mode = ErrorMode.MapJobNotMarshalable;
Assert.IsInstanceOf<BinaryObjectException>(ExecuteWithError());
}
/// <summary>
/// Test local job error.
/// </summary>
[Test]
public void TestLocalJobError()
{
_mode = ErrorMode.LocJobErr;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
var goodEx = JobErrs.First().InnerException as GoodException;
Assert.IsNotNull(goodEx);
Assert.AreEqual(ErrorMode.LocJobErr, goodEx.Mode);
}
/// <summary>
/// Test local not-marshalable job error.
/// </summary>
[Test]
public void TestLocalJobErrorNotMarshalable()
{
_mode = ErrorMode.LocJobErrNotMarshalable;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsInstanceOf<BadException>(JobErrs.First().InnerException); // Local job exception is not marshalled.
}
/// <summary>
/// Test local not-marshalable job result.
/// </summary>
[Test]
public void TestLocalJobResultNotMarshalable()
{
_mode = ErrorMode.LocJobResNotMarshalable;
int res = Execute();
Assert.AreEqual(2, res); // Local job result is not marshalled.
Assert.AreEqual(0, JobErrs.Count);
}
/// <summary>
/// Test remote job error.
/// </summary>
[Test]
public void TestRemoteJobError()
{
_mode = ErrorMode.RmtJobErr;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
var goodEx = JobErrs.First().InnerException as GoodException;
Assert.IsNotNull(goodEx);
Assert.AreEqual(ErrorMode.RmtJobErr, goodEx.Mode);
}
/// <summary>
/// Test remote not-marshalable job error.
/// </summary>
[Test]
public void TestRemoteJobErrorNotMarshalable()
{
_mode = ErrorMode.RmtJobErrNotMarshalable;
Assert.Throws<SerializationException>(() => Execute());
}
/// <summary>
/// Test local not-marshalable job result.
/// </summary>
[Test]
public void TestRemoteJobResultNotMarshalable()
{
_mode = ErrorMode.RmtJobResNotMarshalable;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsNotNull(JobErrs.ElementAt(0) as IgniteException);
}
/// <summary>
/// Test local result error.
/// </summary>
[Test]
public void TestLocalResultError()
{
_mode = ErrorMode.LocResErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.LocResErr, e.Mode);
}
/// <summary>
/// Test local result not-marshalable error.
/// </summary>
[Test]
public void TestLocalResultErrorNotMarshalable()
{
_mode = ErrorMode.LocResErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.LocResErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test remote result error.
/// </summary>
[Test]
public void TestRemoteResultError()
{
_mode = ErrorMode.RmtResErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.RmtResErr, e.Mode);
}
/// <summary>
/// Test remote result not-marshalable error.
/// </summary>
[Test]
public void TestRemoteResultErrorNotMarshalable()
{
_mode = ErrorMode.RmtResErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.RmtResErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test reduce with error.
/// </summary>
[Test]
public void TestReduceError()
{
_mode = ErrorMode.ReduceErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.ReduceErr, e.Mode);
}
/// <summary>
/// Test reduce with not-marshalable error.
/// </summary>
[Test]
public void TestReduceErrorNotMarshalable()
{
_mode = ErrorMode.ReduceErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.ReduceErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test reduce with not-marshalable result.
/// </summary>
[Test]
public void TestReduceResultNotMarshalable()
{
_mode = ErrorMode.ReduceResNotMarshalable;
int res = Execute();
Assert.AreEqual(2, res);
}
/// <summary>
/// Execute task successfully.
/// </summary>
/// <returns>Task result.</returns>
private int Execute()
{
JobErrs.Clear();
Func<object, int> getRes = r => r is GoodTaskResult ? ((GoodTaskResult) r).Res : ((BadTaskResult) r).Res;
var res1 = getRes(Grid1.GetCompute().Execute(new Task()));
var res2 = getRes(Grid1.GetCompute().Execute<object, object>(typeof(Task)));
var resAsync1 = getRes(Grid1.GetCompute().ExecuteAsync(new Task()).Result);
var resAsync2 = getRes(Grid1.GetCompute().ExecuteAsync<object, object>(typeof(Task)).Result);
Assert.AreEqual(res1, res2);
Assert.AreEqual(res2, resAsync1);
Assert.AreEqual(resAsync1, resAsync2);
return res1;
}
/// <summary>
/// Execute task with error.
/// </summary>
/// <returns>Task</returns>
private Exception ExecuteWithError()
{
JobErrs.Clear();
return Assert.Catch(() => Grid1.GetCompute().Execute(new Task()));
}
/// <summary>
/// Error modes.
/// </summary>
private enum ErrorMode
{
/** Error during map step. */
MapErr,
/** Error during map step which is not marshalable. */
MapErrNotMarshalable,
/** Job created by mapper is not marshalable. */
MapJobNotMarshalable,
/** Error occurred in local job. */
LocJobErr,
/** Error occurred in local job and is not marshalable. */
LocJobErrNotMarshalable,
/** Local job result is not marshalable. */
LocJobResNotMarshalable,
/** Error occurred in remote job. */
RmtJobErr,
/** Error occurred in remote job and is not marshalable. */
RmtJobErrNotMarshalable,
/** Remote job result is not marshalable. */
RmtJobResNotMarshalable,
/** Error occurred during local result processing. */
LocResErr,
/** Error occurred during local result processing and is not marshalable. */
LocResErrNotMarshalable,
/** Error occurred during remote result processing. */
RmtResErr,
/** Error occurred during remote result processing and is not marshalable. */
RmtResErrNotMarshalable,
/** Error during reduce step. */
ReduceErr,
/** Error during reduce step and is not marshalable. */
ReduceErrNotMarshalable,
/** Reduce result is not marshalable. */
ReduceResNotMarshalable
}
/// <summary>
/// Task.
/// </summary>
private class Task : IComputeTask<object, object>
{
/** Grid. */
[InstanceResource]
private readonly IIgnite _grid = null;
/** Result. */
private int _res;
/** <inheritDoc /> */
public IDictionary<IComputeJob<object>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg)
{
switch (_mode)
{
case ErrorMode.MapErr:
throw new GoodException(ErrorMode.MapErr);
case ErrorMode.MapErrNotMarshalable:
throw new BadException(ErrorMode.MapErrNotMarshalable);
case ErrorMode.MapJobNotMarshalable:
{
var badJobs = new Dictionary<IComputeJob<object>, IClusterNode>();
foreach (IClusterNode node in subgrid)
badJobs.Add(new BadJob(), node);
return badJobs;
}
}
// Map completes sucessfully and we spread jobs to all nodes.
var jobs = new Dictionary<IComputeJob<object>, IClusterNode>();
foreach (IClusterNode node in subgrid)
jobs.Add(new GoodJob(!_grid.GetCluster().GetLocalNode().Id.Equals(node.Id)), node);
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<object> res, IList<IComputeJobResult<object>> rcvd)
{
if (res.Exception != null)
{
JobErrs.Add(res.Exception);
}
else
{
object res0 = res.Data;
var result = res0 as GoodJobResult;
bool rmt = result != null ? result.Rmt : ((BadJobResult) res0).Rmt;
if (rmt)
{
switch (_mode)
{
case ErrorMode.RmtResErr:
throw new GoodException(ErrorMode.RmtResErr);
case ErrorMode.RmtResErrNotMarshalable:
throw new BadException(ErrorMode.RmtResErrNotMarshalable);
}
}
else
{
switch (_mode)
{
case ErrorMode.LocResErr:
throw new GoodException(ErrorMode.LocResErr);
case ErrorMode.LocResErrNotMarshalable:
throw new BadException(ErrorMode.LocResErrNotMarshalable);
}
}
_res += 1;
}
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public object Reduce(IList<IComputeJobResult<object>> results)
{
switch (_mode)
{
case ErrorMode.ReduceErr:
throw new GoodException(ErrorMode.ReduceErr);
case ErrorMode.ReduceErrNotMarshalable:
throw new BadException(ErrorMode.ReduceErrNotMarshalable);
case ErrorMode.ReduceResNotMarshalable:
return new BadTaskResult(_res);
}
return new GoodTaskResult(_res);
}
}
/// <summary>
///
/// </summary>
[Serializable]
private class GoodJob : IComputeJob<object>, ISerializable
{
/** Whether the job is remote. */
private readonly bool _rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public GoodJob(bool rmt)
{
_rmt = rmt;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodJob(SerializationInfo info, StreamingContext context)
{
_rmt = info.GetBoolean("rmt");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("rmt", _rmt);
}
/** <inheritDoc /> */
public object Execute()
{
if (_rmt)
{
switch (_mode)
{
case ErrorMode.RmtJobErr:
throw new GoodException(ErrorMode.RmtJobErr);
case ErrorMode.RmtJobErrNotMarshalable:
throw new BadException(ErrorMode.RmtJobErr);
case ErrorMode.RmtJobResNotMarshalable:
return new BadJobResult(_rmt);
}
}
else
{
switch (_mode)
{
case ErrorMode.LocJobErr:
throw new GoodException(ErrorMode.LocJobErr);
case ErrorMode.LocJobErrNotMarshalable:
throw new BadException(ErrorMode.LocJobErr);
case ErrorMode.LocJobResNotMarshalable:
return new BadJobResult(_rmt);
}
}
return new GoodJobResult(_rmt);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
/// <summary>
///
/// </summary>
private class BadJob : IComputeJob<object>, IBinarizable
{
[InstanceResource]
/** <inheritDoc /> */
public object Execute()
{
throw new NotImplementedException();
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
///
/// </summary>
[Serializable]
private class GoodJobResult : ISerializable
{
/** */
public readonly bool Rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public GoodJobResult(bool rmt)
{
Rmt = rmt;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodJobResult(SerializationInfo info, StreamingContext context)
{
Rmt = info.GetBoolean("rmt");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("rmt", Rmt);
}
}
/// <summary>
///
/// </summary>
private class BadJobResult : IBinarizable
{
/** */
public readonly bool Rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public BadJobResult(bool rmt)
{
Rmt = rmt;
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
///
/// </summary>
[Serializable]
private class GoodTaskResult : ISerializable
{
/** */
public readonly int Res;
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public GoodTaskResult(int res)
{
Res = res;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodTaskResult(SerializationInfo info, StreamingContext context)
{
Res = info.GetInt32("res");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("res", Res);
}
}
/// <summary>
///
/// </summary>
private class BadTaskResult
{
/** */
public readonly int Res;
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public BadTaskResult(int res)
{
Res = res;
}
}
/// <summary>
/// Marshalable exception.
/// </summary>
[Serializable]
private class GoodException : Exception
{
/** */
public readonly ErrorMode Mode;
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public GoodException(ErrorMode mode)
{
Mode = mode;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodException(SerializationInfo info, StreamingContext context)
{
Mode = (ErrorMode)info.GetInt32("mode");
}
/** <inheritDoc /> */
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("mode", (int)Mode);
base.GetObjectData(info, context);
}
}
/// <summary>
/// Not marshalable exception.
/// </summary>
private class BadException : Exception
{
/** */
public readonly ErrorMode Mode;
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public BadException(ErrorMode mode)
{
Mode = mode;
}
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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.
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace Picodex.Render.Unity
{
/// <summary>
/// Represents a 3x3 matrix containing 3D rotation and scale with double-precision components.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Matrix3d : IEquatable<Matrix3d>
{
#region Fields
/// <summary>
/// First row of the matrix.
/// </summary>
public Vector3d Row0;
/// <summary>
/// Second row of the matrix.
/// </summary>
public Vector3d Row1;
/// <summary>
/// Third row of the matrix.
/// </summary>
public Vector3d Row2;
/// <summary>
/// The identity matrix.
/// </summary>
public static Matrix3d Identity = new Matrix3d(Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ);
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="row0">Top row of the matrix</param>
/// <param name="row1">Second row of the matrix</param>
/// <param name="row2">Bottom row of the matrix</param>
public Matrix3d(Vector3d row0, Vector3d row1, Vector3d row2)
{
Row0 = row0;
Row1 = row1;
Row2 = row2;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="m00">First item of the first row of the matrix.</param>
/// <param name="m01">Second item of the first row of the matrix.</param>
/// <param name="m02">Third item of the first row of the matrix.</param>
/// <param name="m10">First item of the second row of the matrix.</param>
/// <param name="m11">Second item of the second row of the matrix.</param>
/// <param name="m12">Third item of the second row of the matrix.</param>
/// <param name="m20">First item of the third row of the matrix.</param>
/// <param name="m21">Second item of the third row of the matrix.</param>
/// <param name="m22">Third item of the third row of the matrix.</param>
public Matrix3d(
double m00, double m01, double m02,
double m10, double m11, double m12,
double m20, double m21, double m22)
{
Row0 = new Vector3d(m00, m01, m02);
Row1 = new Vector3d(m10, m11, m12);
Row2 = new Vector3d(m20, m21, m22);
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="matrix">A Matrix4d to take the upper-left 3x3 from.</param>
public Matrix3d(Matrix4d matrix)
{
Row0 = matrix.Row0.Xyz;
Row1 = matrix.Row1.Xyz;
Row2 = matrix.Row2.Xyz;
}
#endregion
#region Public Members
#region Properties
/// <summary>
/// Gets the determinant of this matrix.
/// </summary>
public double Determinant
{
get
{
double m11 = Row0.X, m12 = Row0.Y, m13 = Row0.Z,
m21 = Row1.X, m22 = Row1.Y, m23 = Row1.Z,
m31 = Row2.X, m32 = Row2.Y, m33 = Row2.Z;
return
m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32
- m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33;
}
}
/// <summary>
/// Gets the first column of this matrix.
/// </summary>
public Vector3d Column0
{
get { return new Vector3d(Row0.X, Row1.X, Row2.X); }
}
/// <summary>
/// Gets the second column of this matrix.
/// </summary>
public Vector3d Column1
{
get { return new Vector3d(Row0.Y, Row1.Y, Row2.Y); }
}
/// <summary>
/// Gets the third column of this matrix.
/// </summary>
public Vector3d Column2
{
get { return new Vector3d(Row0.Z, Row1.Z, Row2.Z); }
}
/// <summary>
/// Gets or sets the value at row 1, column 1 of this instance.
/// </summary>
public double M11 { get { return Row0.X; } set { Row0.X = value; } }
/// <summary>
/// Gets or sets the value at row 1, column 2 of this instance.
/// </summary>
public double M12 { get { return Row0.Y; } set { Row0.Y = value; } }
/// <summary>
/// Gets or sets the value at row 1, column 3 of this instance.
/// </summary>
public double M13 { get { return Row0.Z; } set { Row0.Z = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 1 of this instance.
/// </summary>
public double M21 { get { return Row1.X; } set { Row1.X = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 2 of this instance.
/// </summary>
public double M22 { get { return Row1.Y; } set { Row1.Y = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 3 of this instance.
/// </summary>
public double M23 { get { return Row1.Z; } set { Row1.Z = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 1 of this instance.
/// </summary>
public double M31 { get { return Row2.X; } set { Row2.X = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 2 of this instance.
/// </summary>
public double M32 { get { return Row2.Y; } set { Row2.Y = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 3 of this instance.
/// </summary>
public double M33 { get { return Row2.Z; } set { Row2.Z = value; } }
/// <summary>
/// Gets or sets the values along the main diagonal of the matrix.
/// </summary>
public Vector3d Diagonal
{
get
{
return new Vector3d(Row0.X, Row1.Y, Row2.Z);
}
set
{
Row0.X = value.X;
Row1.Y = value.Y;
Row2.Z = value.Z;
}
}
/// <summary>
/// Gets the trace of the matrix, the sum of the values along the diagonal.
/// </summary>
public double Trace { get { return Row0.X + Row1.Y + Row2.Z; } }
#endregion
#region Indexers
/// <summary>
/// Gets or sets the value at a specified row and column.
/// </summary>
public double this[int rowIndex, int columnIndex]
{
get
{
if (rowIndex == 0) return Row0[columnIndex];
else if (rowIndex == 1) return Row1[columnIndex];
else if (rowIndex == 2) return Row2[columnIndex];
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
if (rowIndex == 0) Row0[columnIndex] = value;
else if (rowIndex == 1) Row1[columnIndex] = value;
else if (rowIndex == 2) Row2[columnIndex] = value;
else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
}
#endregion
#region Instance
#region public void Invert()
/// <summary>
/// Converts this instance into its inverse.
/// </summary>
public void Invert()
{
this = Matrix3d.Invert(this);
}
#endregion
#region public void Transpose()
/// <summary>
/// Converts this instance into its transpose.
/// </summary>
public void Transpose()
{
this = Matrix3d.Transpose(this);
}
#endregion
/// <summary>
/// Returns a normalised copy of this instance.
/// </summary>
public Matrix3d Normalized()
{
Matrix3d m = this;
m.Normalize();
return m;
}
/// <summary>
/// Divides each element in the Matrix by the <see cref="Determinant"/>.
/// </summary>
public void Normalize()
{
var determinant = this.Determinant;
Row0 /= determinant;
Row1 /= determinant;
Row2 /= determinant;
}
/// <summary>
/// Returns an inverted copy of this instance.
/// </summary>
public Matrix3d Inverted()
{
Matrix3d m = this;
if (m.Determinant != 0)
m.Invert();
return m;
}
/// <summary>
/// Returns a copy of this Matrix3 without scale.
/// </summary>
public Matrix3d ClearScale()
{
Matrix3d m = this;
m.Row0 = m.Row0.Normalized();
m.Row1 = m.Row1.Normalized();
m.Row2 = m.Row2.Normalized();
return m;
}
/// <summary>
/// Returns a copy of this Matrix3 without rotation.
/// </summary>
public Matrix3d ClearRotation()
{
Matrix3d m = this;
m.Row0 = new Vector3d(m.Row0.Length, 0, 0);
m.Row1 = new Vector3d(0, m.Row1.Length, 0);
m.Row2 = new Vector3d(0, 0, m.Row2.Length);
return m;
}
/// <summary>
/// Returns the scale component of this instance.
/// </summary>
public Vector3d ExtractScale() { return new Vector3d(Row0.Length, Row1.Length, Row2.Length); }
/// <summary>
/// Returns the rotation component of this instance. Quite slow.
/// </summary>
/// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param>
public Quaterniond ExtractRotation(){
return ExtractRotation(true);
}
public Quaterniond ExtractRotation(bool row_normalise)
{
var row0 = Row0;
var row1 = Row1;
var row2 = Row2;
if (row_normalise)
{
row0 = row0.Normalized();
row1 = row1.Normalized();
row2 = row2.Normalized();
}
// code below adapted from Blender
Quaterniond q = new Quaterniond();
double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0);
if (trace > 0)
{
double sq = Math.Sqrt(trace);
q.W = sq;
sq = 1.0 / (4.0 * sq);
q.X = (row1[2] - row2[1]) * sq;
q.Y = (row2[0] - row0[2]) * sq;
q.Z = (row0[1] - row1[0]) * sq;
}
else if (row0[0] > row1[1] && row0[0] > row2[2])
{
double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]);
q.X = 0.25 * sq;
sq = 1.0 / sq;
q.W = (row2[1] - row1[2]) * sq;
q.Y = (row1[0] + row0[1]) * sq;
q.Z = (row2[0] + row0[2]) * sq;
}
else if (row1[1] > row2[2])
{
double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]);
q.Y = 0.25 * sq;
sq = 1.0 / sq;
q.W = (row2[0] - row0[2]) * sq;
q.X = (row1[0] + row0[1]) * sq;
q.Z = (row2[1] + row1[2]) * sq;
}
else
{
double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]);
q.Z = 0.25 * sq;
sq = 1.0 / sq;
q.W = (row1[0] - row0[1]) * sq;
q.X = (row2[0] + row0[2]) * sq;
q.Y = (row2[1] + row1[2]) * sq;
}
q.Normalize();
return q;
}
#endregion
#region Static
#region CreateFromAxisAngle
/// <summary>
/// Build a rotation matrix from the specified axis/angle rotation.
/// </summary>
/// <param name="axis">The axis to rotate about.</param>
/// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
/// <param name="result">A matrix instance.</param>
public static void CreateFromAxisAngle(Vector3d axis, double angle, out Matrix3d result)
{
//normalize and create a local copy of the vector.
axis.Normalize();
double axisX = axis.X, axisY = axis.Y, axisZ = axis.Z;
//calculate angles
double cos = System.Math.Cos(-angle);
double sin = System.Math.Sin(-angle);
double t = 1.0f - cos;
//do the conversion math once
double tXX = t * axisX * axisX,
tXY = t * axisX * axisY,
tXZ = t * axisX * axisZ,
tYY = t * axisY * axisY,
tYZ = t * axisY * axisZ,
tZZ = t * axisZ * axisZ;
double sinX = sin * axisX,
sinY = sin * axisY,
sinZ = sin * axisZ;
result.Row0.X = tXX + cos;
result.Row0.Y = tXY - sinZ;
result.Row0.Z = tXZ + sinY;
result.Row1.X = tXY + sinZ;
result.Row1.Y = tYY + cos;
result.Row1.Z = tYZ - sinX;
result.Row2.X = tXZ - sinY;
result.Row2.Y = tYZ + sinX;
result.Row2.Z = tZZ + cos;
}
/// <summary>
/// Build a rotation matrix from the specified axis/angle rotation.
/// </summary>
/// <param name="axis">The axis to rotate about.</param>
/// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
/// <returns>A matrix instance.</returns>
public static Matrix3d CreateFromAxisAngle(Vector3d axis, double angle)
{
Matrix3d result;
CreateFromAxisAngle(axis, angle, out result);
return result;
}
#endregion
#region CreateFromQuaternion
/// <summary>
/// Build a rotation matrix from the specified quaternion.
/// </summary>
/// <param name="q">Quaternion to translate.</param>
/// <param name="result">Matrix result.</param>
public static void CreateFromQuaternion(ref Quaterniond q, out Matrix3d result)
{
Vector3d axis;
double angle;
q.ToAxisAngle(out axis, out angle);
CreateFromAxisAngle(axis, angle, out result);
}
/// <summary>
/// Build a rotation matrix from the specified quaternion.
/// </summary>
/// <param name="q">Quaternion to translate.</param>
/// <returns>A matrix instance.</returns>
public static Matrix3d CreateFromQuaternion(Quaterniond q)
{
Matrix3d result;
CreateFromQuaternion(ref q, out result);
return result;
}
#endregion
#region CreateRotation[XYZ]
/// <summary>
/// Builds a rotation matrix for a rotation around the x-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3d instance.</param>
public static void CreateRotationX(double angle, out Matrix3d result)
{
double cos = System.Math.Cos(angle);
double sin = System.Math.Sin(angle);
result = Identity;
result.Row1.Y = cos;
result.Row1.Z = sin;
result.Row2.Y = -sin;
result.Row2.Z = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the x-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3d instance.</returns>
public static Matrix3d CreateRotationX(double angle)
{
Matrix3d result;
CreateRotationX(angle, out result);
return result;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the y-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3d instance.</param>
public static void CreateRotationY(double angle, out Matrix3d result)
{
double cos = System.Math.Cos(angle);
double sin = System.Math.Sin(angle);
result = Identity;
result.Row0.X = cos;
result.Row0.Z = -sin;
result.Row2.X = sin;
result.Row2.Z = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the y-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3d instance.</returns>
public static Matrix3d CreateRotationY(double angle)
{
Matrix3d result;
CreateRotationY(angle, out result);
return result;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the z-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3d instance.</param>
public static void CreateRotationZ(double angle, out Matrix3d result)
{
double cos = System.Math.Cos(angle);
double sin = System.Math.Sin(angle);
result = Identity;
result.Row0.X = cos;
result.Row0.Y = sin;
result.Row1.X = -sin;
result.Row1.Y = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the z-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3d instance.</returns>
public static Matrix3d CreateRotationZ(double angle)
{
Matrix3d result;
CreateRotationZ(angle, out result);
return result;
}
#endregion
#region CreateScale
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Single scale factor for the x, y, and z axes.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3d CreateScale(double scale)
{
Matrix3d result;
CreateScale(scale, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Scale factors for the x, y, and z axes.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3d CreateScale(Vector3d scale)
{
Matrix3d result;
CreateScale(ref scale, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="x">Scale factor for the x axis.</param>
/// <param name="y">Scale factor for the y axis.</param>
/// <param name="z">Scale factor for the z axis.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3d CreateScale(double x, double y, double z)
{
Matrix3d result;
CreateScale(x, y, z, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Single scale factor for the x, y, and z axes.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(double scale, out Matrix3d result)
{
result = Identity;
result.Row0.X = scale;
result.Row1.Y = scale;
result.Row2.Z = scale;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Scale factors for the x, y, and z axes.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(ref Vector3d scale, out Matrix3d result)
{
result = Identity;
result.Row0.X = scale.X;
result.Row1.Y = scale.Y;
result.Row2.Z = scale.Z;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="x">Scale factor for the x axis.</param>
/// <param name="y">Scale factor for the y axis.</param>
/// <param name="z">Scale factor for the z axis.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(double x, double y, double z, out Matrix3d result)
{
result = Identity;
result.Row0.X = x;
result.Row1.Y = y;
result.Row2.Z = z;
}
#endregion
#region Multiply Functions
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The left operand of the multiplication.</param>
/// <param name="right">The right operand of the multiplication.</param>
/// <returns>A new instance that is the result of the multiplication</returns>
public static Matrix3d Mult(Matrix3d left, Matrix3d right)
{
Matrix3d result;
Mult(ref left, ref right, out result);
return result;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The left operand of the multiplication.</param>
/// <param name="right">The right operand of the multiplication.</param>
/// <param name="result">A new instance that is the result of the multiplication</param>
public static void Mult(ref Matrix3d left, ref Matrix3d right, out Matrix3d result)
{
double lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z,
lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z,
lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z,
rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z,
rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z,
rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z;
result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31);
result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32);
result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33);
result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31);
result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32);
result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33);
result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31);
result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32);
result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33);
}
#endregion
#region Invert Functions
/// <summary>
/// Calculate the inverse of the given matrix
/// </summary>
/// <param name="mat">The matrix to invert</param>
/// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param>
/// <exception cref="InvalidOperationException">Thrown if the Matrix3d is singular.</exception>
public static void Invert(ref Matrix3d mat, out Matrix3d result)
{
int[] colIdx = { 0, 0, 0 };
int[] rowIdx = { 0, 0, 0 };
int[] pivotIdx = { -1, -1, -1 };
double[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z},
{mat.Row1.X, mat.Row1.Y, mat.Row1.Z},
{mat.Row2.X, mat.Row2.Y, mat.Row2.Z}};
int icol = 0;
int irow = 0;
for (int i = 0; i < 3; i++)
{
double maxPivot = 0.0;
for (int j = 0; j < 3; j++)
{
if (pivotIdx[j] != 0)
{
for (int k = 0; k < 3; ++k)
{
if (pivotIdx[k] == -1)
{
double absVal = System.Math.Abs(inverse[j, k]);
if (absVal > maxPivot)
{
maxPivot = absVal;
irow = j;
icol = k;
}
}
else if (pivotIdx[k] > 0)
{
result = mat;
return;
}
}
}
}
++(pivotIdx[icol]);
if (irow != icol)
{
for (int k = 0; k < 3; ++k)
{
double f = inverse[irow, k];
inverse[irow, k] = inverse[icol, k];
inverse[icol, k] = f;
}
}
rowIdx[i] = irow;
colIdx[i] = icol;
double pivot = inverse[icol, icol];
if (pivot == 0.0)
{
throw new InvalidOperationException("Matrix is singular and cannot be inverted.");
}
double oneOverPivot = 1.0 / pivot;
inverse[icol, icol] = 1.0;
for (int k = 0; k < 3; ++k)
inverse[icol, k] *= oneOverPivot;
for (int j = 0; j < 3; ++j)
{
if (icol != j)
{
double f = inverse[j, icol];
inverse[j, icol] = 0.0;
for (int k = 0; k < 3; ++k)
inverse[j, k] -= inverse[icol, k] * f;
}
}
}
for (int j = 2; j >= 0; --j)
{
int ir = rowIdx[j];
int ic = colIdx[j];
for (int k = 0; k < 3; ++k)
{
double f = inverse[k, ir];
inverse[k, ir] = inverse[k, ic];
inverse[k, ic] = f;
}
}
result.Row0.X = inverse[0, 0];
result.Row0.Y = inverse[0, 1];
result.Row0.Z = inverse[0, 2];
result.Row1.X = inverse[1, 0];
result.Row1.Y = inverse[1, 1];
result.Row1.Z = inverse[1, 2];
result.Row2.X = inverse[2, 0];
result.Row2.Y = inverse[2, 1];
result.Row2.Z = inverse[2, 2];
}
/// <summary>
/// Calculate the inverse of the given matrix
/// </summary>
/// <param name="mat">The matrix to invert</param>
/// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns>
/// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception>
public static Matrix3d Invert(Matrix3d mat)
{
Matrix3d result;
Invert(ref mat, out result);
return result;
}
#endregion
#region Transpose
/// <summary>
/// Calculate the transpose of the given matrix
/// </summary>
/// <param name="mat">The matrix to transpose</param>
/// <returns>The transpose of the given matrix</returns>
public static Matrix3d Transpose(Matrix3d mat)
{
return new Matrix3d(mat.Column0, mat.Column1, mat.Column2);
}
/// <summary>
/// Calculate the transpose of the given matrix
/// </summary>
/// <param name="mat">The matrix to transpose</param>
/// <param name="result">The result of the calculation</param>
public static void Transpose(ref Matrix3d mat, out Matrix3d result)
{
result.Row0 = mat.Column0;
result.Row1 = mat.Column1;
result.Row2 = mat.Column2;
}
#endregion
#endregion
#region Operators
/// <summary>
/// Matrix multiplication
/// </summary>
/// <param name="left">left-hand operand</param>
/// <param name="right">right-hand operand</param>
/// <returns>A new Matrix3d which holds the result of the multiplication</returns>
public static Matrix3d operator *(Matrix3d left, Matrix3d right)
{
return Matrix3d.Mult(left, right);
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Matrix3d left, Matrix3d right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equal right; false otherwise.</returns>
public static bool operator !=(Matrix3d left, Matrix3d right)
{
return !left.Equals(right);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Matrix3d.
/// </summary>
/// <returns>The string representation of the matrix.</returns>
public override string ToString()
{
return String.Format("{0}\n{1}\n{2}", Row0, Row1, Row2);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Matrix3d))
return false;
return this.Equals((Matrix3d)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Matrix3d> Members
/// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
/// <param name="other">A matrix to compare with this matrix.</param>
/// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
public bool Equals(Matrix3d other)
{
return
Row0 == other.Row0 &&
Row1 == other.Row1 &&
Row2 == other.Row2;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Palaso.Lift.Validation;
namespace Palaso.Lift.Merging
{
/// <summary>
/// Class to merge two or more LIFT files that are created incrementally, such that
/// 1) the data in previous ones is overwritten by data in newer ones
/// 2) the *entire contents* of the new entry element replaces the previous contents
/// I.e., merging is only on an entry level.
/// </summary>
public class SynchronicMerger
{
// private string _pathToBaseLiftFile;
///<summary></summary>
public const string ExtensionOfIncrementalFiles = ".lift.update";
/// <summary>
///
/// </summary>
/// <exception cref="IOException">If file is locked</exception>
/// <exception cref="LiftFormatException">If there is an error and then file is found to be non-conformant.</exception>
/// <param name="pathToBaseLiftFile"></param>
public bool MergeUpdatesIntoFile(string pathToBaseLiftFile)
{
// _pathToBaseLiftFile = pathToBaseLiftFile;
FileInfo[] files = GetPendingUpdateFiles(pathToBaseLiftFile);
return MergeUpdatesIntoFile(pathToBaseLiftFile, files);
}
/// <summary>
/// Given a LIFT file and a set of .lift.update files, apply the changes to the LIFT file and delete the .lift.update files.
/// </summary>
/// <param name="pathToBaseLiftFile">The LIFT file containing all the lexical entries for a paticular language project</param>
/// <param name="files">These files contain the changes the user has made. Changes to entries; New entries; Deleted entries</param>
/// <returns></returns>
/// <exception cref="IOException">If file is locked</exception>
/// <exception cref="LiftFormatException">If there is an error and then file is found to be non-conformant.</exception>
///
public bool MergeUpdatesIntoFile(string pathToBaseLiftFile, FileInfo[] files)
{
if (files.Length < 1)
{
return false;
}
Array.Sort(files, new FileInfoLastWriteTimeComparer());
int count = files.Length;
string pathToMergeInTo = pathToBaseLiftFile; // files[0].FullName;
FileAttributes fa = File.GetAttributes(pathToBaseLiftFile);
if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
return false;
}
for (int i = 0; i < count; i++)
{
if (files[i].IsReadOnly)
{
//todo: "Cannot merge safely because at least one file is read only: {0}
return true;
}
}
bool mergedAtLeastOne = false;
List<string> filesToDelete = new List<string>();
for (int i = 0; i < count; i++)
{
//let empty files be as if they didn't exist. They do represent that something
//went wrong, but (at least in WeSay) we can detect that something by a more
//accurate means, and these just get in the way
if (files[i].Length < 100) //sometimes empty files register as having a few bytes
{
string contents = File.ReadAllText(files[i].FullName);
if (contents.Trim().Length == 0)
{
File.Delete(files[i].FullName);
continue;
}
}
string outputPath = Path.GetTempFileName();
try
{
MergeInNewFile(pathToMergeInTo, files[i].FullName, outputPath);
}
catch (IOException)
{
// todo: "Cannot most likely one of the files is locked
File.Delete(outputPath);
throw;
}
catch (Exception)
{
try
{
Validator.CheckLiftWithPossibleThrow(files[i].FullName);
}
catch (Exception e2)
{
File.Delete(outputPath);
throw new BadUpdateFileException(pathToMergeInTo, files[i].FullName, e2);
}
//eventually we'll just check everything before-hand. But for now our rng
//validator is painfully slow in files which have date stamps,
//because two formats are allowed an our mono rng validator
//throws non-fatal exceptions for each one
Validator.CheckLiftWithPossibleThrow(pathToBaseLiftFile);
throw; //must have been something else
}
pathToMergeInTo = outputPath;
filesToDelete.Add(outputPath);
mergedAtLeastOne = true;
}
if (!mergedAtLeastOne)
{
return false;
}
//string pathToBaseLiftFile = Path.Combine(directory, BaseLiftFileName);
Debug.Assert(File.Exists(pathToMergeInTo));
MakeBackup(pathToBaseLiftFile, pathToMergeInTo);
//delete all the non-base paths
foreach (FileInfo file in files)
{
if (file.FullName != pathToBaseLiftFile && File.Exists(file.FullName))
{
file.Delete();
}
}
//delete all our temporary files
foreach (string s in filesToDelete)
{
File.Delete(s);
}
return true;
}
private static void MakeBackup(string pathToBaseLiftFile, string pathToMergeInTo)
{
// File.Move works across volumes but the destination cannot exist.
if (File.Exists(pathToBaseLiftFile))
{
string backupOfBackup;
do
{
backupOfBackup = pathToBaseLiftFile + Path.GetRandomFileName();
}
while(File.Exists(backupOfBackup));
string bakPath = pathToBaseLiftFile+".bak";
if (File.Exists(bakPath))
{
// move the backup out of the way, if something fails here we have nothing to do
if ((File.GetAttributes(bakPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
bakPath = GetNextAvailableBakPath(bakPath);
}
else
{
try
{
File.Move(bakPath, backupOfBackup);
}
catch (IOException)
{
// back file is Locked. Create the next available backup Path
bakPath = GetNextAvailableBakPath(bakPath);
}
}
}
try
{
File.Move(pathToBaseLiftFile, bakPath);
try
{
File.Move(pathToMergeInTo, pathToBaseLiftFile);
}
catch
{
// roll back to prior state
File.Move(bakPath, pathToBaseLiftFile);
throw;
}
}
catch
{
// roll back to prior state
if (File.Exists(backupOfBackup))
{
File.Move(backupOfBackup, bakPath);
}
throw;
}
//everything was successful so can get rid of backupOfBackup
if (File.Exists(backupOfBackup))
{
File.Delete(backupOfBackup);
}
}
else
{
File.Move(pathToMergeInTo, pathToBaseLiftFile);
}
}
///<summary>
///</summary>
///<exception cref="ArgumentException"></exception>
public static FileInfo[] GetPendingUpdateFiles(string pathToBaseLiftFile)
{
//see ws-1035
if(!pathToBaseLiftFile.Contains(Path.DirectorySeparatorChar.ToString()))
{
throw new ArgumentException("pathToBaseLiftFile must be a full path, not just a file name. Path was "+pathToBaseLiftFile);
}
// ReSharper disable AssignNullToNotNullAttribute
var di = new DirectoryInfo(Path.GetDirectoryName(pathToBaseLiftFile));
// ReSharper restore AssignNullToNotNullAttribute
var files = di.GetFiles("*"+ExtensionOfIncrementalFiles, SearchOption.TopDirectoryOnly);
//files comes back unsorted, sort by creation time before returning.
Array.Sort(files, new Comparison<FileInfo>((a, b) => a.CreationTime.CompareTo(b.CreationTime)));
return files;
}
static private void TestWriting(XmlWriter w)
{
// w.WriteStartDocument();
w.WriteStartElement("start");
w.WriteElementString("one", "hello");
w.WriteElementString("two", "bye");
w.WriteEndElement();
// w.WriteEndDocument();
}
///<summary></summary>
static public void TestWritingFile()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
// nb: don't use XmlTextWriter.Create, that's broken. Ignores the indent setting
using (XmlWriter writer = XmlWriter.Create("C:\\test.xml", settings))
{
TestWriting(writer);
}
}
private static string GetNextAvailableBakPath(string bakPath) {
int i = 0;
string newBakPath;
do
{
i++;
newBakPath = bakPath + i;
}
while (File.Exists(newBakPath));
bakPath = newBakPath;
return bakPath;
}
private void MergeInNewFile(string olderFilePath, string newerFilePath, string outputPath)
{
XmlDocument newerDoc = new XmlDocument();
newerDoc.Load(newerFilePath);
XmlWriterSettings settings = new XmlWriterSettings();
settings.NewLineOnAttributes = true; //ugly, but great for merging with revision control systems
settings.NewLineChars = "\r\n";
settings.Indent = true;
settings.IndentChars = "\t";
settings.CheckCharacters = false;
// nb: don't use XmlTextWriter.Create, that's broken. Ignores the indent setting
using (XmlWriter writer = XmlWriter.Create(outputPath /*Console.Out*/, settings))
{
//For each entry in the new guy, read through the whole base file
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CheckCharacters = false;//without this, we die if we simply encounter a (properly escaped) other-wise illegal unicode character, e.g. 
readerSettings.IgnoreWhitespace = true; //if the reader returns whitespace, the writer ceases to format xml after that point
using (XmlReader olderReader = XmlReader.Create(olderFilePath, readerSettings))
{
//bool elementWasReplaced = false;
while (!olderReader.EOF)
{
ProcessOlderNode(olderReader, newerDoc, writer);
}
}
}
}
private void ProcessOlderNode(XmlReader olderReader, XmlDocument newerDoc, XmlWriter writer)
{
switch (olderReader.NodeType)
{
case XmlNodeType.EndElement:
case XmlNodeType.Element:
ProcessElement(olderReader, writer, newerDoc);
break;
default:
Utilities.WriteShallowNode(olderReader, writer);
break;
}
}
private void ProcessElement(XmlReader olderReader, XmlWriter writer, XmlDocument newerDoc)
{
//empty lift file, write new elements
if ( olderReader.Name == "lift" && olderReader.IsEmptyElement) //i.e., <lift/>
{
writer.WriteStartElement("lift");
writer.WriteAttributes(olderReader, true);
if (newerDoc != null)
{
var nodes = newerDoc.SelectNodes("//entry");
if (nodes != null)
{
foreach (XmlNode n in nodes)
{
writer.WriteNode(n.CreateNavigator(), true /*REVIEW*/); //REVIEW CreateNavigator
}
}
}
//write out the closing lift element
writer.WriteEndElement();
olderReader.Read();
}
//hit the end, write out any remaing new elements
else if (olderReader.Name == "lift" &&
olderReader.NodeType == XmlNodeType.EndElement)
{
var nodes = newerDoc.SelectNodes("//entry");
if (nodes != null)
{
foreach (XmlNode n in nodes) //REVIEW CreateNavigator
{
writer.WriteNode(n.CreateNavigator(), true /*REVIEW*/);
}
}
//write out the closing lift element
writer.WriteNode(olderReader, true);
}
else
{
if (olderReader.Name == "entry")
{
MergeLiftUpdateEntryIntoLiftFile(olderReader, writer, newerDoc);
}
else
{
Utilities.WriteShallowNode(olderReader, writer);
}
}
}
protected virtual void MergeLiftUpdateEntryIntoLiftFile(XmlReader olderReader, XmlWriter writer, XmlDocument newerDoc)
{
string oldId = olderReader.GetAttribute("guid");
if (String.IsNullOrEmpty(oldId))
{
throw new ApplicationException("All entries must have guid attributes in order for merging to work. " +
olderReader.Value);
}
XmlNode match = newerDoc.SelectSingleNode("//entry[@guid='" + oldId + "']");
if (match != null)
{
olderReader.Skip(); //skip the old one
writer.WriteNode(match.CreateNavigator(), true); //REVIEW CreateNavigator
if (match.ParentNode != null)
match.ParentNode.RemoveChild(match);
}
else
{
writer.WriteNode(olderReader, true);
}
}
internal class FileInfoLastWriteTimeComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
int timecomparison = DateTime.Compare(x.LastWriteTimeUtc, y.LastWriteTimeUtc);
if (timecomparison == 0)
{
// if timestamps are the same, then sort by name
return StringComparer.OrdinalIgnoreCase.Compare(x.FullName, y.FullName);
}
return timecomparison;
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
[System.Serializable]
public class CutsceneTrackGroup
{
#region Constants
const int MaxChildren = 3;
#endregion
#region Variables
public string GroupName = "";
[HideInInspector]
public bool Expanded;
[HideInInspector]
public bool EditingName;
[HideInInspector]
public bool Hidden;
[HideInInspector]
public bool Muted;
[HideInInspector]
public Rect GroupNamePosition = new Rect();
[HideInInspector]
public bool IsSelected = false;
[HideInInspector]
public Rect TrackPosition = new Rect();
[HideInInspector]
public string UniqueId = "";
//[HideInInspector]
// IMPORTANT: this had to be removed in order to get rid of the unity 4.5 nested class error
//List<CutsceneTrackGroup> m_Children = new List<CutsceneTrackGroup>();
//public CutsceneTrackGroup[] m_Children = new CutsceneTrackGroup[MaxChildren];
//public CutsceneTrackGroup m_Children;
// the GUID's of the events that are on the track
[HideInInspector]
public List<string> m_TrackItems = new List<string>();
#endregion
#region Properties
public bool HasChildren
{
get { return NumChildren > 0; }
//get { return m_Children.Length > 0; }
//get { return m_Children != null; }
}
public int NumChildren
{
get { return 0; }
//get { return m_Children.Count; }
//get { return m_Children.Length; }
//get { return m_Children != null ? 1 : 0; }
}
public List<CutsceneTrackGroup> Children
{
get { return null; }
//get { return new List<CutsceneTrackGroup>(); }
}
#endregion
#region Functions
public CutsceneTrackGroup() { }
public CutsceneTrackGroup(Rect trackPosition, string groupName, bool expanded)
{
GroupName = groupName;
Expanded = expanded;
TrackPosition = trackPosition;
UniqueId = Guid.NewGuid().ToString();
}
public List<CutsceneTrackGroup> ConvertChildrenToList()
{
//return new List<CutsceneTrackGroup>(m_Children);
List<CutsceneTrackGroup> children = new List<CutsceneTrackGroup>();
return children;
}
public void AddChildGroup(CutsceneTrackGroup child)
{
if (!ContainsChild(child))
{
AddChild(child);
//m_Children.Add(child);
Expanded = true;
//Debug.Log(string.Format("{0} now has child {1}", GroupName, child.GroupName));
}
}
public bool ContainsChild(CutsceneTrackGroup child)
{
return true;
//return Array.Find<CutsceneTrackGroup>(m_Children, c => c== child) != null;
//return child == m_Children;
}
void AddChild(CutsceneTrackGroup child)
{
//m_Children = child;
//int newSize = 1;
//if (m_Children == null || m_Children.Length == 0)
//{
// m_Children = new CutsceneTrackGroup[newSize];
//}
//else
//{
// // deep copy the array
// newSize = m_Children.Length + 1;
// CutsceneTrackGroup[] clonedArray = (CutsceneTrackGroup[])m_Children.Clone();
// m_Children = new CutsceneTrackGroup[newSize];
// for (int i = 0; i < clonedArray.Length; i++)
// {
// m_Children[i] = clonedArray[i];
// }
//}
//m_Children[newSize - 1] = child;
}
public void RemoveChild(CutsceneTrackGroup child)
{
//if (child == m_Children)
//{
// m_Children = null;
//}
//int index = Array.FindIndex<CutsceneTrackGroup>(m_Children, c => c == child);
//if (index != -1)
//{
// m_Children[index] = null;
// CutsceneTrackGroup[] clonedArray = (CutsceneTrackGroup[])m_Children.Clone();
// m_Children = new CutsceneTrackGroup[clonedArray.Length - 1];
// for (int i = 0; i < clonedArray.Length; i++)
// {
// if (clonedArray[i] != null)
// {
// m_Children[i] = clonedArray[i];
// }
// }
//}
}
public void SetStartingPosition(Rect pos)
{
SetTrackWidthHeight(pos.width, pos.height);
}
public void SetTrackPosition(float x, float y)
{
TrackPosition.x = x;
TrackPosition.y = y;
}
public void SetTrackWidthHeight(float w, float h)
{
TrackPosition.width = w;
TrackPosition.height = h;
}
/// <summary>
/// Returns true if you clicked in the track area
/// </summary>
/// <param name="selectionPoint"></param>
/// <returns></returns>
public bool TrackContainsPosition(Vector2 selectionPoint)
{
Rect tempTrackPosition = TrackPosition;
// this is a hack to make sure that when we drag events off the right side of the screen,
// the track appears to be infinite in width so that events know what track they are on.
// Without this, quickly dragging events to the right will cause errors about the event not
// being on any track
tempTrackPosition.width = 1000000;
return tempTrackPosition.Contains(selectionPoint);
}
/// <summary>
/// Returns true if you clicked in the track area
/// </summary>
/// <param name="posX"></param>
/// <param name="posY"></param>
/// <returns></returns>
public bool TrackContainsPosition(float posX, float posY)
{
return TrackContainsPosition(new Vector2(posX, posY));
}
/// <summary>
/// Returns true if the trackItem is part of this track group
/// </summary>
/// <param name="trackItem"></param>
/// <returns></returns>
public bool TrackContainsItem(CutsceneTrackItem trackItem)
{
// return m_TrackItems.Find(t => t.UniqueId == trackItem.UniqueId) != null;
return (int)trackItem.GuiPosition.y == (int)TrackPosition.y;
}
/// <summary>
/// Returns true if you click the name of the group
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool GroupNameContainsPosition(Vector2 position)
{
return GroupNamePosition.Contains(position);
}
/// <summary>
/// Highlights the track at the specified location
/// </summary>
/// <param name="selectionPoint"></param>
/// <param name="clearPreviousSelections"></param>
public void SelectTrack(bool selected)
{
IsSelected = selected;
}
public void Draw(Rect drawPosition)
{
Color original = GUI.color;
TrackPosition.y = drawPosition.y;
if (IsSelected)
{
GUI.color = CutsceneEvent.SelectedColor;
}
GUI.Box(drawPosition, "");
// restore
GUI.color = original;
}
/// <summary>
/// Returns true if the potentialChild is a child. This checks recursively through child tracks
/// </summary>
/// <param name="potentialChild"></param>
/// <returns></returns>
public bool IsAncestorOf(CutsceneTrackGroup potentialChild)
{
Stack<CutsceneTrackGroup> groupStack = new Stack<CutsceneTrackGroup>();
foreach (CutsceneTrackGroup group in Children)
{
groupStack.Clear();
groupStack.Push(group);
while (groupStack.Count > 0)
{
CutsceneTrackGroup currGroup = groupStack.Pop();
if (currGroup == potentialChild)
{
return true;
}
foreach (CutsceneTrackGroup child in currGroup.Children)
{
groupStack.Push(child);
}
}
}
return false;
}
/// <summary>
/// Returns true if this track has potentialAncestor in it's hierarchy
/// </summary>
/// <param name="potentialAncestor"></param>
/// <returns></returns>
public bool IsChildOf(CutsceneTrackGroup potentialAncestor)
{
return potentialAncestor.IsAncestorOf(this);
}
#endregion
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Globalization;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
#if !(DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0
[Serializable]
public struct Ratio : IConvertible, IFormattable, ISerializable
{
private readonly int _numerator;
private readonly int _denominator;
public Ratio(int numerator, int denominator)
{
_numerator = numerator;
_denominator = denominator;
}
#region Properties
public int Numerator
{
get { return _numerator; }
}
public int Denominator
{
get { return _denominator; }
}
public bool IsNan
{
get { return _denominator == 0; }
}
#endregion
#region Serialization operations
public Ratio(SerializationInfo info, StreamingContext context)
{
_numerator = info.GetInt32("n");
_denominator = info.GetInt32("d");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("n", _numerator);
info.AddValue("d", _denominator);
}
#endregion
#region IConvertible Members
public TypeCode GetTypeCode()
{
return TypeCode.Object;
}
public bool ToBoolean(IFormatProvider provider)
{
return _numerator == 0;
}
public byte ToByte(IFormatProvider provider)
{
return (byte)(_numerator / _denominator);
}
public char ToChar(IFormatProvider provider)
{
return Convert.ToChar(_numerator / _denominator);
}
public DateTime ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(_numerator / _denominator);
}
public decimal ToDecimal(IFormatProvider provider)
{
return (decimal)_numerator / _denominator;
}
public double ToDouble(IFormatProvider provider)
{
return _denominator == 0
? double.NaN
: (double)_numerator / _denominator;
}
public short ToInt16(IFormatProvider provider)
{
return (short)(_numerator / _denominator);
}
public int ToInt32(IFormatProvider provider)
{
return _numerator / _denominator;
}
public long ToInt64(IFormatProvider provider)
{
return _numerator / _denominator;
}
public sbyte ToSByte(IFormatProvider provider)
{
return (sbyte)(_numerator / _denominator);
}
public float ToSingle(IFormatProvider provider)
{
return _denominator == 0
? float.NaN
: (float)_numerator / _denominator;
}
public string ToString(IFormatProvider provider)
{
return _denominator == 1
? _numerator.ToString(provider)
: _numerator.ToString(provider) + "/" + _denominator.ToString(provider);
}
public object ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(ToDouble(provider), conversionType, provider);
}
public ushort ToUInt16(IFormatProvider provider)
{
return (ushort)(_numerator / _denominator);
}
public uint ToUInt32(IFormatProvider provider)
{
return (uint)(_numerator / _denominator);
}
public ulong ToUInt64(IFormatProvider provider)
{
return (ulong)(_numerator / _denominator);
}
#endregion
#region String operations
public override string ToString()
{
return ToString(CultureInfo.InvariantCulture);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return ToString(CultureInfo.InvariantCulture);
}
public static Ratio Parse(string input)
{
return Parse(input, CultureInfo.InvariantCulture);
}
public static Ratio Parse(string input, IFormatProvider formatProvider)
{
Ratio result;
if (!TryParse(input, formatProvider, out result))
{
throw new FormatException(
string.Format(
CultureInfo.InvariantCulture,
"Text '{0}' is invalid text representation of ratio",
input));
}
return result;
}
public static bool TryParse(string input, out Ratio result)
{
return TryParse(input, CultureInfo.InvariantCulture, out result);
}
public static bool TryParse(string input, IFormatProvider formatProvider, out Ratio result)
{
if (input != null)
{
var fractionIndex = input.IndexOf('/');
int numerator;
if (fractionIndex < 0)
{
if (int.TryParse(input, NumberStyles.Integer, formatProvider, out numerator))
{
result = new Ratio(numerator, 1);
return true;
}
}
else
{
int denominator;
if (int.TryParse(input.Substring(0, fractionIndex), NumberStyles.Integer, formatProvider, out numerator) &&
int.TryParse(input.Substring(fractionIndex + 1), NumberStyles.Integer, formatProvider, out denominator))
{
result = new Ratio(numerator, denominator);
return true;
}
}
}
result = default(Ratio);
return false;
}
#endregion
}
#endif
}
| |
namespace android.speech.tts
{
[global::MonoJavaBridge.JavaClass()]
public partial class TextToSpeech : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected TextToSpeech(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public partial class Engine : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Engine(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public Engine(android.speech.tts.TextToSpeech arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.speech.tts.TextToSpeech.Engine._m0.native == global::System.IntPtr.Zero)
global::android.speech.tts.TextToSpeech.Engine._m0 = @__env.GetMethodIDNoThrow(global::android.speech.tts.TextToSpeech.Engine.staticClass, "<init>", "(Landroid/speech/tts/TextToSpeech;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.speech.tts.TextToSpeech.Engine.staticClass, global::android.speech.tts.TextToSpeech.Engine._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int DEFAULT_STREAM
{
get
{
return 3;
}
}
public static int CHECK_VOICE_DATA_PASS
{
get
{
return 1;
}
}
public static int CHECK_VOICE_DATA_FAIL
{
get
{
return 0;
}
}
public static int CHECK_VOICE_DATA_BAD_DATA
{
get
{
return -1;
}
}
public static int CHECK_VOICE_DATA_MISSING_DATA
{
get
{
return -2;
}
}
public static int CHECK_VOICE_DATA_MISSING_VOLUME
{
get
{
return -3;
}
}
public static global::java.lang.String ACTION_INSTALL_TTS_DATA
{
get
{
return "android.speech.tts.engine.INSTALL_TTS_DATA";
}
}
public static global::java.lang.String ACTION_TTS_DATA_INSTALLED
{
get
{
return "android.speech.tts.engine.TTS_DATA_INSTALLED";
}
}
public static global::java.lang.String ACTION_CHECK_TTS_DATA
{
get
{
return "android.speech.tts.engine.CHECK_TTS_DATA";
}
}
public static global::java.lang.String EXTRA_VOICE_DATA_ROOT_DIRECTORY
{
get
{
return "dataRoot";
}
}
public static global::java.lang.String EXTRA_VOICE_DATA_FILES
{
get
{
return "dataFiles";
}
}
public static global::java.lang.String EXTRA_VOICE_DATA_FILES_INFO
{
get
{
return "dataFilesInfo";
}
}
public static global::java.lang.String EXTRA_AVAILABLE_VOICES
{
get
{
return "availableVoices";
}
}
public static global::java.lang.String EXTRA_UNAVAILABLE_VOICES
{
get
{
return "unavailableVoices";
}
}
public static global::java.lang.String EXTRA_CHECK_VOICE_DATA_FOR
{
get
{
return "checkVoiceDataFor";
}
}
public static global::java.lang.String EXTRA_TTS_DATA_INSTALLED
{
get
{
return "dataInstalled";
}
}
public static global::java.lang.String KEY_PARAM_STREAM
{
get
{
return "streamType";
}
}
public static global::java.lang.String KEY_PARAM_UTTERANCE_ID
{
get
{
return "utteranceId";
}
}
static Engine()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.tts.TextToSpeech.Engine.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/tts/TextToSpeech$Engine"));
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.speech.tts.TextToSpeech.OnInitListener_))]
public partial interface OnInitListener : global::MonoJavaBridge.IJavaObject
{
void onInit(int arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.speech.tts.TextToSpeech.OnInitListener))]
internal sealed partial class OnInitListener_ : java.lang.Object, OnInitListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnInitListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.speech.tts.TextToSpeech.OnInitListener.onInit(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.speech.tts.TextToSpeech.OnInitListener_.staticClass, "onInit", "(I)V", ref global::android.speech.tts.TextToSpeech.OnInitListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static OnInitListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.tts.TextToSpeech.OnInitListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/tts/TextToSpeech$OnInitListener"));
}
}
public delegate void OnInitListenerDelegate(int arg0);
internal partial class OnInitListenerDelegateWrapper : java.lang.Object, OnInitListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnInitListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnInitListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper.staticClass, global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnInitListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/tts/TextToSpeech_OnInitListenerDelegateWrapper"));
}
}
internal partial class OnInitListenerDelegateWrapper
{
private OnInitListenerDelegate myDelegate;
public void onInit(int arg0)
{
myDelegate(arg0);
}
public static implicit operator OnInitListenerDelegateWrapper(OnInitListenerDelegate d)
{
global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper ret = new global::android.speech.tts.TextToSpeech.OnInitListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListener_))]
public partial interface OnUtteranceCompletedListener : global::MonoJavaBridge.IJavaObject
{
void onUtteranceCompleted(java.lang.String arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListener))]
internal sealed partial class OnUtteranceCompletedListener_ : java.lang.Object, OnUtteranceCompletedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnUtteranceCompletedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.speech.tts.TextToSpeech.OnUtteranceCompletedListener.onUtteranceCompleted(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListener_.staticClass, "onUtteranceCompleted", "(Ljava/lang/String;)V", ref global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static OnUtteranceCompletedListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/tts/TextToSpeech$OnUtteranceCompletedListener"));
}
}
public delegate void OnUtteranceCompletedListenerDelegate(java.lang.String arg0);
internal partial class OnUtteranceCompletedListenerDelegateWrapper : java.lang.Object, OnUtteranceCompletedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnUtteranceCompletedListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnUtteranceCompletedListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper.staticClass, global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnUtteranceCompletedListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/tts/TextToSpeech_OnUtteranceCompletedListenerDelegateWrapper"));
}
}
internal partial class OnUtteranceCompletedListenerDelegateWrapper
{
private OnUtteranceCompletedListenerDelegate myDelegate;
public void onUtteranceCompleted(java.lang.String arg0)
{
myDelegate(arg0);
}
public static implicit operator OnUtteranceCompletedListenerDelegateWrapper(OnUtteranceCompletedListenerDelegate d)
{
global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper ret = new global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void shutdown()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "shutdown", "()V", ref global::android.speech.tts.TextToSpeech._m0);
}
public new global::java.util.Locale Language
{
get
{
return getLanguage();
}
set
{
setLanguage(value);
}
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::java.util.Locale getLanguage()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.util.Locale>(this, global::android.speech.tts.TextToSpeech.staticClass, "getLanguage", "()Ljava/util/Locale;", ref global::android.speech.tts.TextToSpeech._m1) as java.util.Locale;
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual int stop()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "stop", "()I", ref global::android.speech.tts.TextToSpeech._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual int addSpeech(java.lang.String arg0, java.lang.String arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "addSpeech", "(Ljava/lang/String;Ljava/lang/String;I)I", ref global::android.speech.tts.TextToSpeech._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual int addSpeech(java.lang.String arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "addSpeech", "(Ljava/lang/String;Ljava/lang/String;)I", ref global::android.speech.tts.TextToSpeech._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual int addEarcon(java.lang.String arg0, java.lang.String arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "addEarcon", "(Ljava/lang/String;Ljava/lang/String;I)I", ref global::android.speech.tts.TextToSpeech._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual int addEarcon(java.lang.String arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "addEarcon", "(Ljava/lang/String;Ljava/lang/String;)I", ref global::android.speech.tts.TextToSpeech._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual int speak(java.lang.String arg0, int arg1, java.util.HashMap arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "speak", "(Ljava/lang/String;ILjava/util/HashMap;)I", ref global::android.speech.tts.TextToSpeech._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual int playEarcon(java.lang.String arg0, int arg1, java.util.HashMap arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "playEarcon", "(Ljava/lang/String;ILjava/util/HashMap;)I", ref global::android.speech.tts.TextToSpeech._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual int playSilence(long arg0, int arg1, java.util.HashMap arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "playSilence", "(JILjava/util/HashMap;)I", ref global::android.speech.tts.TextToSpeech._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual bool isSpeaking()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "isSpeaking", "()Z", ref global::android.speech.tts.TextToSpeech._m10);
}
public new float SpeechRate
{
set
{
setSpeechRate(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual int setSpeechRate(float arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "setSpeechRate", "(F)I", ref global::android.speech.tts.TextToSpeech._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float Pitch
{
set
{
setPitch(value);
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual int setPitch(float arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "setPitch", "(F)I", ref global::android.speech.tts.TextToSpeech._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual int setLanguage(java.util.Locale arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "setLanguage", "(Ljava/util/Locale;)I", ref global::android.speech.tts.TextToSpeech._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual int isLanguageAvailable(java.util.Locale arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "isLanguageAvailable", "(Ljava/util/Locale;)I", ref global::android.speech.tts.TextToSpeech._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual int synthesizeToFile(java.lang.String arg0, java.util.HashMap arg1, java.lang.String arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "synthesizeToFile", "(Ljava/lang/String;Ljava/util/HashMap;Ljava/lang/String;)I", ref global::android.speech.tts.TextToSpeech._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual int setOnUtteranceCompletedListener(android.speech.tts.TextToSpeech.OnUtteranceCompletedListener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "setOnUtteranceCompletedListener", "(Landroid/speech/tts/TextToSpeech$OnUtteranceCompletedListener;)I", ref global::android.speech.tts.TextToSpeech._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public int setOnUtteranceCompletedListener(global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegate arg0)
{
return setOnUtteranceCompletedListener((global::android.speech.tts.TextToSpeech.OnUtteranceCompletedListenerDelegateWrapper)arg0);
}
public new global::java.lang.String EngineByPackageName
{
set
{
setEngineByPackageName(value);
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual int setEngineByPackageName(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "setEngineByPackageName", "(Ljava/lang/String;)I", ref global::android.speech.tts.TextToSpeech._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.String DefaultEngine
{
get
{
return getDefaultEngine();
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual global::java.lang.String getDefaultEngine()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.speech.tts.TextToSpeech.staticClass, "getDefaultEngine", "()Ljava/lang/String;", ref global::android.speech.tts.TextToSpeech._m18) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual bool areDefaultsEnforced()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.speech.tts.TextToSpeech.staticClass, "areDefaultsEnforced", "()Z", ref global::android.speech.tts.TextToSpeech._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public TextToSpeech(android.content.Context arg0, android.speech.tts.TextToSpeech.OnInitListener arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.speech.tts.TextToSpeech._m20.native == global::System.IntPtr.Zero)
global::android.speech.tts.TextToSpeech._m20 = @__env.GetMethodIDNoThrow(global::android.speech.tts.TextToSpeech.staticClass, "<init>", "(Landroid/content/Context;Landroid/speech/tts/TextToSpeech$OnInitListener;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.speech.tts.TextToSpeech.staticClass, global::android.speech.tts.TextToSpeech._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
public static int SUCCESS
{
get
{
return 0;
}
}
public static int ERROR
{
get
{
return -1;
}
}
public static int QUEUE_FLUSH
{
get
{
return 0;
}
}
public static int QUEUE_ADD
{
get
{
return 1;
}
}
public static int LANG_COUNTRY_VAR_AVAILABLE
{
get
{
return 2;
}
}
public static int LANG_COUNTRY_AVAILABLE
{
get
{
return 1;
}
}
public static int LANG_AVAILABLE
{
get
{
return 0;
}
}
public static int LANG_MISSING_DATA
{
get
{
return -1;
}
}
public static int LANG_NOT_SUPPORTED
{
get
{
return -2;
}
}
public static global::java.lang.String ACTION_TTS_QUEUE_PROCESSING_COMPLETED
{
get
{
return "android.speech.tts.TTS_QUEUE_PROCESSING_COMPLETED";
}
}
static TextToSpeech()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.speech.tts.TextToSpeech.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/tts/TextToSpeech"));
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Core.Strings;
using umbraco.DataLayer;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
namespace umbraco.cms.businesslogic.template
{
/// <summary>
/// Summary description for Template.
/// </summary>
[Obsolete("Obsolete, Use IFileService and ITemplate to work with templates instead")]
public class Template : CMSNode
{
#region Private members
private readonly ViewHelper _viewHelper = new ViewHelper(FileSystemProviderManager.Current.MvcViewsFileSystem);
private readonly MasterPageHelper _masterPageHelper = new MasterPageHelper(FileSystemProviderManager.Current.MasterPagesFileSystem);
internal ITemplate TemplateEntity;
private int? _mastertemplate;
#endregion
#region Static members
public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master";
private static Hashtable _templateAliases = new Hashtable();
#endregion
[Obsolete("Use TemplateFilePath instead")]
public string MasterPageFile
{
get { return TemplateFilePath; }
}
/// <summary>
/// Returns the file path for the current template
/// </summary>
public string TemplateFilePath
{
get
{
switch (ApplicationContext.Current.Services.FileService.DetermineTemplateRenderingEngine(TemplateEntity))
{
case RenderingEngine.Mvc:
return _viewHelper.GetPhysicalFilePath(TemplateEntity);
case RenderingEngine.WebForms:
return _masterPageHelper.GetPhysicalFilePath(TemplateEntity);
default:
throw new ArgumentOutOfRangeException();
}
}
}
[Obsolete("This is not used at all, do not use this")]
public static Hashtable TemplateAliases
{
get { return _templateAliases; }
set { _templateAliases = value; }
}
#region Constructors
internal Template(ITemplate template)
: base(template)
{
TemplateEntity = template;
}
public Template(int id) : base(id) { }
public Template(Guid id) : base(id) { }
#endregion
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
SaveEventArgs e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
ApplicationContext.Current.Services.FileService.SaveTemplate(TemplateEntity);
//base.Save();
FireAfterSave(e);
}
}
public string GetRawText()
{
return TemplateEntity.Name;
//return base.Text;
}
//TODO: This is the name of the template, which can apparenlty be localized using the umbraco dictionary, so we need to cater for this but that
// shoud really be done as part of mapping logic for models that are being consumed in the UI, not at the business logic layer.
public override string Text
{
get
{
var tempText = TemplateEntity.Name;
//string tempText = base.Text;
if (!tempText.StartsWith("#"))
return tempText;
else
{
language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(tempText.Substring(1, tempText.Length - 1)))
{
Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(tempText.Substring(1, tempText.Length - 1));
if (di != null)
return di.Value(lang.id);
}
}
return "[" + tempText + "]";
}
}
set
{
FlushCache();
TemplateEntity.Name = value;
}
}
[Obsolete("This is not used whatsoever")]
public string OutputContentType { get; set; }
protected override void setupNode()
{
TemplateEntity = ApplicationContext.Current.Services.FileService.GetTemplate(Id);
if (TemplateEntity == null)
{
throw new ArgumentException(string.Format("No node exists with id '{0}'", Id));
}
}
public new string Path
{
get
{
return TemplateEntity.Path;
}
set
{
TemplateEntity.Path = value;
}
}
public string Alias
{
get { return TemplateEntity.Alias; }
set { TemplateEntity.Alias = value; }
}
public bool HasMasterTemplate
{
get { return (_mastertemplate > 0); }
}
public override bool HasChildren
{
get { return TemplateEntity.IsMasterTemplate; }
set
{
//Do nothing!
}
}
public int MasterTemplate
{
get
{
if (_mastertemplate.HasValue == false)
{
var master = ApplicationContext.Current.Services.FileService.GetTemplate(TemplateEntity.MasterTemplateAlias);
if (master != null)
{
_mastertemplate = master.Id;
}
else
{
_mastertemplate = -1;
}
}
return _mastertemplate.Value;
}
set
{
//set to null if it's zero
if (value == 0)
{
TemplateEntity.SetMasterTemplate(null);
}
else
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(value);
if (found != null)
{
TemplateEntity.SetMasterTemplate(found);
_mastertemplate = found.Id;
}
}
}
}
public string Design
{
get
{
return TemplateEntity.Content;
}
set
{
TemplateEntity.Content = value;
}
}
public XmlNode ToXml(XmlDocument doc)
{
var serializer = new EntityXmlSerializer();
var serialized = serializer.Serialize(TemplateEntity);
return serialized.GetXmlNode(doc);
}
/// <summary>
/// Removes any references to this templates from child templates, documenttypes and documents
/// </summary>
public void RemoveAllReferences()
{
if (HasChildren)
{
foreach (var t in GetAllAsList().FindAll(t => t.MasterTemplate == Id))
{
t.MasterTemplate = 0;
t.Save();
}
}
RemoveFromDocumentTypes();
// remove from documents
Document.RemoveTemplateFromDocument(this.Id);
//save it
Save();
}
public void RemoveFromDocumentTypes()
{
foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)))
{
dt.RemoveTemplate(this.Id);
dt.Save();
}
}
[Obsolete("This method should have never existed here")]
public IEnumerable<DocumentType> GetDocumentTypes()
{
return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id));
}
public static Template MakeNew(string Name, User u, Template master)
{
return MakeNew(Name, u, master, null);
}
private static Template MakeNew(string name, User u, string design)
{
return MakeNew(name, u, null, design);
}
public static Template MakeNew(string name, User u)
{
return MakeNew(name, u, design: null);
}
private static Template MakeNew(string name, User u, Template master, string design)
{
var foundMaster = master == null ? null : ApplicationContext.Current.Services.FileService.GetTemplate(master.Id);
var template = ApplicationContext.Current.Services.FileService.CreateTemplateWithIdentity(name, design, foundMaster, u.Id);
var legacyTemplate = new Template(template);
var e = new NewEventArgs();
legacyTemplate.OnNew(e);
return legacyTemplate;
}
public static Template GetByAlias(string Alias)
{
return GetByAlias(Alias, false);
}
[Obsolete("this overload is the same as the other one, the useCache has no affect")]
public static Template GetByAlias(string Alias, bool useCache)
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(Alias);
return found == null ? null : new Template(found);
}
[Obsolete("Obsolete, please use GetAllAsList() method instead", true)]
public static Template[] getAll()
{
return GetAllAsList().ToArray();
}
public static List<Template> GetAllAsList()
{
return ApplicationContext.Current.Services.FileService.GetTemplates().Select(x => new Template(x)).ToList();
}
public static int GetTemplateIdFromAlias(string alias)
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(alias);
return found == null ? -1 : found.Id;
}
public override void delete()
{
// don't allow template deletion if it has child templates
if (this.HasChildren)
{
var ex = new InvalidOperationException("Can't delete a master template. Remove any bindings from child templates first.");
LogHelper.Error<Template>("Can't delete a master template. Remove any bindings from child templates first.", ex);
throw ex;
}
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
//remove refs from documents
using (var sqlHelper = Application.SqlHelper)
sqlHelper.ExecuteNonQuery("UPDATE cmsDocument SET templateId = NULL WHERE templateId = " + this.Id);
ApplicationContext.Current.Services.FileService.DeleteTemplate(TemplateEntity.Alias);
FireAfterDelete(e);
}
}
[Obsolete("This method, doesnt actually do anything, as the file is created when the design is set", false)]
public void _SaveAsMasterPage()
{
}
public string GetMasterContentElement(int masterTemplateId)
{
if (masterTemplateId != 0)
{
string masterAlias = new Template(masterTemplateId).Alias.Replace(" ", "");
return
String.Format("<asp:Content ContentPlaceHolderID=\"{1}ContentPlaceHolder\" runat=\"server\">",
Alias.Replace(" ", ""), masterAlias);
}
else
return
String.Format("<asp:Content ContentPlaceHolderID=\"ContentPlaceHolderDefault\" runat=\"server\">",
Alias.Replace(" ", ""));
}
public List<string> contentPlaceholderIds()
{
return MasterPageHelper.GetContentPlaceholderIds(TemplateEntity).ToList();
}
public string ConvertToMasterPageSyntax(string templateDesign)
{
string masterPageContent = GetMasterContentElement(MasterTemplate) + Environment.NewLine;
masterPageContent += templateDesign;
// Parse the design for getitems
masterPageContent = EnsureMasterPageSyntax(masterPageContent);
// append ending asp:content element
masterPageContent += Environment.NewLine
+ "</asp:Content>"
+ Environment.NewLine;
return masterPageContent;
}
public string EnsureMasterPageSyntax(string masterPageContent)
{
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", false);
// Parse the design for macros
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", false);
// Parse the design for load childs
masterPageContent = masterPageContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>", GetAspNetMasterPageContentContainer()).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", GetAspNetMasterPageContentContainer());
// Parse the design for aspnet forms
GetAspNetMasterPageForm(ref masterPageContent);
masterPageContent = masterPageContent.Replace("</?ASPNET_FORM>", "</form>");
// Parse the design for aspnet heads
masterPageContent = masterPageContent.Replace("</ASPNET_HEAD>", String.Format("<head id=\"{0}Head\" runat=\"server\">", Alias.Replace(" ", "")));
masterPageContent = masterPageContent.Replace("</?ASPNET_HEAD>", "</head>");
return masterPageContent;
}
public void ImportDesign(string design)
{
Design = design;
}
public void SaveMasterPageFile(string masterPageContent)
{
//this will trigger the helper and store everything
this.Design = masterPageContent;
}
private void GetAspNetMasterPageForm(ref string design)
{
Match formElement = Regex.Match(design, GetElementRegExp("?ASPNET_FORM", false), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
if (formElement != null && formElement.Value != "")
{
string formReplace = String.Format("<form id=\"{0}Form\" runat=\"server\">", Alias.Replace(" ", ""));
if (formElement.Groups.Count == 0)
{
formReplace += "<asp:scriptmanager runat=\"server\"></asp:scriptmanager>";
}
design = design.Replace(formElement.Value, formReplace);
}
}
private string GetAspNetMasterPageContentContainer()
{
return String.Format(
"<asp:ContentPlaceHolder ID=\"{0}ContentPlaceHolder\" runat=\"server\"></asp:ContentPlaceHolder>",
Alias.Replace(" ", ""));
}
private void ReplaceElement(ref string design, string elementName, string newElementName, bool checkForQuotes)
{
MatchCollection m =
Regex.Matches(design, GetElementRegExp(elementName, checkForQuotes),
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match match in m)
{
GroupCollection groups = match.Groups;
// generate new element (compensate for a closing trail on single elements ("/"))
string elementAttributes = groups[1].Value;
// test for macro alias
if (elementName == "?UMBRACO_MACRO")
{
Hashtable tags = helpers.xhtml.ReturnAttributes(match.Value);
if (tags["macroAlias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroAlias"].ToString()) + elementAttributes;
else if (tags["macroalias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroalias"].ToString()) + elementAttributes;
}
string newElement = "<" + newElementName + " runat=\"server\" " + elementAttributes.Trim() + ">";
if (elementAttributes.EndsWith("/"))
{
elementAttributes = elementAttributes.Substring(0, elementAttributes.Length - 1);
}
else if (groups[0].Value.StartsWith("</"))
// It's a closing element, so generate that instead of a starting element
newElement = "</" + newElementName + ">";
if (checkForQuotes)
{
// if it's inside quotes, we'll change element attribute quotes to single quotes
newElement = newElement.Replace("\"", "'");
newElement = String.Format("\"{0}\"", newElement);
}
design = design.Replace(match.Value, newElement);
}
}
private string GetElementRegExp(string elementName, bool checkForQuotes)
{
if (checkForQuotes)
return String.Format("\"<[^>\\s]*\\b{0}(\\b[^>]*)>\"", elementName);
else
return String.Format("<[^>\\s]*\\b{0}(\\b[^>]*)>", elementName);
}
[Obsolete("Umbraco automatically ensures that template cache is cleared when saving or deleting")]
protected virtual void FlushCache()
{
//ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id));
}
public static Template GetTemplate(int id)
{
var found = ApplicationContext.Current.Services.FileService.GetTemplate(id);
return found == null ? null : new Template(found);
}
public static Template Import(XmlNode n, User u)
{
var element = System.Xml.Linq.XElement.Parse(n.OuterXml);
var templates = ApplicationContext.Current.Services.PackagingService.ImportTemplates(element, u.Id);
return new Template(templates.First().Id);
}
#region Events
//EVENTS
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Template sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Template sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Template sender, DeleteEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
public new static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
/// <summary>
/// Occurs when [after save].
/// </summary>
public new static event SaveEventHandler AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public new static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public new static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected override void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
//
// 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.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
namespace Mono.Security.Protocol.Tls.Handshake.Client
{
internal class TlsClientCertificateVerify : HandshakeMessage
{
#region Constructors
public TlsClientCertificateVerify(Context context)
: base(context, HandshakeType.CertificateVerify)
{
}
#endregion
#region Methods
public override void Update()
{
base.Update();
this.Reset();
}
#endregion
#region Protected Methods
protected override void ProcessAsSsl3()
{
AsymmetricAlgorithm privKey = null;
ClientContext context = (ClientContext)this.Context;
privKey = context.SslStream.RaisePrivateKeySelection(
context.ClientSettings.ClientCertificate,
context.ClientSettings.TargetHost);
if (privKey == null)
{
throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable.");
}
else
{
SslHandshakeHash hash = new SslHandshakeHash(context.MasterSecret);
hash.TransformFinalBlock(
context.HandshakeMessages.ToArray(),
0,
(int)context.HandshakeMessages.Length);
// CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented
// in RSACryptoServiceProvider. Other implementations likely implement DecryptValue
// so we will try the CreateSignature method.
byte[] signature = null;
if (!(privKey is RSACryptoServiceProvider))
{
try
{
signature = hash.CreateSignature((RSA)privKey);
}
catch (NotImplementedException)
{ }
}
// If DecryptValue is not implemented, then try to export the private
// key and let the RSAManaged class do the DecryptValue
if (signature == null)
{
// RSAManaged of the selected ClientCertificate
// (at this moment the first one)
RSA rsa = this.getClientCertRSA((RSA)privKey);
// Write message
signature = hash.CreateSignature(rsa);
}
this.Write((short)signature.Length);
this.Write(signature, 0, signature.Length);
}
}
protected override void ProcessAsTls1()
{
AsymmetricAlgorithm privKey = null;
ClientContext context = (ClientContext)this.Context;
privKey = context.SslStream.RaisePrivateKeySelection(
context.ClientSettings.ClientCertificate,
context.ClientSettings.TargetHost);
if (privKey == null)
{
throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable.");
}
else
{
// Compute handshake messages hash
MD5SHA1 hash = new MD5SHA1();
hash.ComputeHash(
context.HandshakeMessages.ToArray(),
0,
(int)context.HandshakeMessages.Length);
// CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented
// in RSACryptoServiceProvider. Other implementations likely implement DecryptValue
// so we will try the CreateSignature method.
byte[] signature = null;
if (!(privKey is RSACryptoServiceProvider))
{
try
{
signature = hash.CreateSignature((RSA)privKey);
}
catch (NotImplementedException)
{ }
}
// If DecryptValue is not implemented, then try to export the private
// key and let the RSAManaged class do the DecryptValue
if (signature == null)
{
// RSAManaged of the selected ClientCertificate
// (at this moment the first one)
RSA rsa = this.getClientCertRSA((RSA)privKey);
// Write message
signature = hash.CreateSignature(rsa);
}
this.Write((short)signature.Length);
this.Write(signature, 0, signature.Length);
}
}
#endregion
#region Private methods
private RSA getClientCertRSA(RSA privKey)
{
RSAParameters rsaParams = new RSAParameters();
RSAParameters privateParams = privKey.ExportParameters(true);
// for RSA m_publickey contains 2 ASN.1 integers
// the modulus and the public exponent
ASN1 pubkey = new ASN1 (this.Context.ClientSettings.Certificates[0].GetPublicKey());
ASN1 modulus = pubkey [0];
if ((modulus == null) || (modulus.Tag != 0x02))
{
return null;
}
ASN1 exponent = pubkey [1];
if (exponent.Tag != 0x02)
{
return null;
}
rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value);
rsaParams.Exponent = exponent.Value;
// Set private key parameters
rsaParams.D = privateParams.D;
rsaParams.DP = privateParams.DP;
rsaParams.DQ = privateParams.DQ;
rsaParams.InverseQ = privateParams.InverseQ;
rsaParams.P = privateParams.P;
rsaParams.Q = privateParams.Q;
// BUG: MS BCL 1.0 can't import a key which
// isn't the same size as the one present in
// the container.
int keySize = (rsaParams.Modulus.Length << 3);
RSAManaged rsa = new RSAManaged(keySize);
rsa.ImportParameters (rsaParams);
return (RSA)rsa;
}
private byte[] getUnsignedBigInteger(byte[] integer)
{
if (integer [0] == 0x00)
{
// this first byte is added so we're sure it's an unsigned integer
// however we can't feed it into RSAParameters or DSAParameters
int length = integer.Length - 1;
byte[] uinteger = new byte [length];
Buffer.BlockCopy (integer, 1, uinteger, 0, length);
return uinteger;
}
else
{
return integer;
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SafeList.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Security.AntiXss {
using System.Collections;
using System.Globalization;
/// <summary>
/// Provides safe list utility functions.
/// </summary>
internal static class SafeList {
/// <summary>
/// Generates a safe character array representing the specified value.
/// </summary>
/// <returns>A safe character array representing the specified value.</returns>
/// <param name="value">The value to generate a safe representation for.</param>
internal delegate char[] GenerateSafeValue(int value);
/// <summary>
/// Generates a new safe list of the specified size, using the specified function to produce safe values.
/// </summary>
/// <param name="length">The length of the safe list to generate.</param>
/// <param name="generateSafeValue">The <see cref="GenerateSafeValue"/> function to use.</param>
/// <returns>A new safe list.</returns>
internal static char[][] Generate(int length, GenerateSafeValue generateSafeValue) {
char[][] allCharacters = new char[length + 1][];
for (int i = 0; i <= length; i++) {
allCharacters[i] = generateSafeValue(i);
}
return allCharacters;
}
/// <summary>
/// Marks characters from the specified languages as safe.
/// </summary>
/// <param name="safeList">The safe list to punch holes in.</param>
/// <param name="lowerCodeCharts">The combination of lower code charts to use.</param>
/// <param name="lowerMidCodeCharts">The combination of lower mid code charts to use.</param>
/// <param name="midCodeCharts">The combination of mid code charts to use.</param>
/// <param name="upperMidCodeCharts">The combination of upper mid code charts to use.</param>
/// <param name="upperCodeCharts">The combination of upper code charts to use.</param>
internal static void PunchUnicodeThrough(
ref char[][] safeList,
LowerCodeCharts lowerCodeCharts,
LowerMidCodeCharts lowerMidCodeCharts,
MidCodeCharts midCodeCharts,
UpperMidCodeCharts upperMidCodeCharts,
UpperCodeCharts upperCodeCharts) {
if (lowerCodeCharts != LowerCodeCharts.None) {
PunchCodeCharts(ref safeList, lowerCodeCharts);
}
if (lowerMidCodeCharts != LowerMidCodeCharts.None) {
PunchCodeCharts(ref safeList, lowerMidCodeCharts);
}
if (midCodeCharts != MidCodeCharts.None) {
PunchCodeCharts(ref safeList, midCodeCharts);
}
if (upperMidCodeCharts != UpperMidCodeCharts.None) {
PunchCodeCharts(ref safeList, upperMidCodeCharts);
}
if (upperCodeCharts != UpperCodeCharts.None) {
PunchCodeCharts(ref safeList, upperCodeCharts);
}
}
/// <summary>
/// Punches holes as necessary.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="----edCharacters">The list of character positions to punch.</param>
internal static void PunchSafeList(ref char[][] safeList, IEnumerable whiteListedCharacters) {
PunchHolesIfNeeded(ref safeList, true, whiteListedCharacters);
}
/// <summary>
/// Generates a hash prefixed character array representing the specified value.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>#1</description></item>
/// <item><term>10</term><description>#10</description></item>
/// <item><term>100</term><description>#100</description></item>
/// </list>
/// </remarks>
internal static char[] HashThenValueGenerator(int value) {
return StringToCharArrayWithHashPrefix(value.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a hash prefixed character array representing the specified value in hexadecimal.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>#1</description></item>
/// <item><term>10</term><description>#0a</description></item>
/// <item><term>100</term><description>#64</description></item>
/// </list>
/// </remarks>
internal static char[] HashThenHexValueGenerator(int value) {
return StringToCharArrayWithHashPrefix(value.ToString("x2", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a percent prefixed character array representing the specified value in hexadecimal.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>%01</description></item>
/// <item><term>10</term><description>%0A</description></item>
/// <item><term>100</term><description>%64</description></item>
/// </list>
/// </remarks>
internal static char[] PercentThenHexValueGenerator(int value) {
return StringToCharArrayWithPercentPrefix(value.ToString("X2", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a slash prefixed character array representing the specified value in hexadecimal.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>\01</description></item>
/// <item><term>10</term><description>\0a</description></item>
/// <item><term>100</term><description>\64</description></item>
/// </list>
/// </remarks>
internal static char[] SlashThenHexValueGenerator(int value) {
return StringToCharArrayWithSlashPrefix(value.ToString("x2", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a slash prefixed character array representing the specified value in hexadecimal.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>\000001</description></item>
/// <item><term>10</term><description>\000000A</description></item>
/// <item><term>100</term><description>\000064</description></item>
/// </list>
/// </remarks>
internal static char[] SlashThenSixDigitHexValueGenerator(long value) {
return StringToCharArrayWithSlashPrefix(value.ToString("X6", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a slash prefixed character array representing the specified value in hexadecimal.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>\000001</description></item>
/// <item><term>10</term><description>\000000A</description></item>
/// <item><term>100</term><description>\000064</description></item>
/// </list>
/// </remarks>
internal static char[] SlashThenSixDigitHexValueGenerator(int value) {
return StringToCharArrayWithSlashPrefix(value.ToString("X6", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a hash prefixed character array representing the specified value.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>#1</description></item>
/// <item><term>10</term><description>#10</description></item>
/// <item><term>100</term><description>#100</description></item>
/// </list>
/// </remarks>
internal static char[] HashThenValueGenerator(long value) {
return StringToCharArrayWithHashPrefix(value.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates a hash prefixed character array from the specified string.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>#1</description></item>
/// <item><term>10</term><description>#10</description></item>
/// <item><term>100</term><description>#100</description></item>
/// </list>
/// </remarks>
private static char[] StringToCharArrayWithHashPrefix(string value) {
return StringToCharArrayWithPrefix(value, '#');
}
/// <summary>
/// Generates a percent prefixed character array from the specified string.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>%1</description></item>
/// <item><term>10</term><description>%10</description></item>
/// <item><term>100</term><description>%100</description></item>
/// </list>
/// </remarks>
private static char[] StringToCharArrayWithPercentPrefix(string value) {
return StringToCharArrayWithPrefix(value, '%');
}
/// <summary>
/// Generates a slash prefixed character array from the specified string.
/// </summary>
/// <param name="value">The source value.</param>
/// <returns>A character array representing the specified value.</returns>
/// <remarks>
/// Example inputs and encoded outputs:
/// <list type="table">
/// <item><term>1</term><description>\1</description></item>
/// <item><term>10</term><description>\10</description></item>
/// <item><term>100</term><description>\100</description></item>
/// </list>
/// </remarks>
private static char[] StringToCharArrayWithSlashPrefix(string value) {
return StringToCharArrayWithPrefix(value, '\\');
}
/// <summary>
/// Generates a prefixed character array from the specified string and prefix.
/// </summary>
/// <param name="value">The source value.</param>
/// <param name="prefix">The prefix to use.</param>
/// <returns>A prefixed character array representing the specified value.</returns>
private static char[] StringToCharArrayWithPrefix(string value, char prefix) {
int valueAsStringLength = value.Length;
char[] valueAsCharArray = new char[valueAsStringLength + 1];
valueAsCharArray[0] = prefix;
for (int j = 0; j < valueAsStringLength; j++) {
valueAsCharArray[j + 1] = value[j];
}
return valueAsCharArray;
}
/// <summary>
/// Punch appropriate holes for the selected code charts.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="codeCharts">The code charts to punch.</param>
private static void PunchCodeCharts(ref char[][] safeList, LowerCodeCharts codeCharts) {
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.BasicLatin), CodeCharts.Lower.BasicLatin());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.C1ControlsAndLatin1Supplement), CodeCharts.Lower.Latin1Supplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.LatinExtendedA), CodeCharts.Lower.LatinExtendedA());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.LatinExtendedB), CodeCharts.Lower.LatinExtendedB());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.IpaExtensions), CodeCharts.Lower.IpaExtensions());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.SpacingModifierLetters), CodeCharts.Lower.SpacingModifierLetters());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.CombiningDiacriticalMarks), CodeCharts.Lower.CombiningDiacriticalMarks());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.GreekAndCoptic), CodeCharts.Lower.GreekAndCoptic());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Cyrillic), CodeCharts.Lower.Cyrillic());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.CyrillicSupplement), CodeCharts.Lower.CyrillicSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Armenian), CodeCharts.Lower.Armenian());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Hebrew), CodeCharts.Lower.Hebrew());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Arabic), CodeCharts.Lower.Arabic());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Syriac), CodeCharts.Lower.Syriac());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.ArabicSupplement), CodeCharts.Lower.ArabicSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Thaana), CodeCharts.Lower.Thaana());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Nko), CodeCharts.Lower.Nko());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Samaritan), CodeCharts.Lower.Samaritan());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Devanagari), CodeCharts.Lower.Devanagari());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Bengali), CodeCharts.Lower.Bengali());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Gurmukhi), CodeCharts.Lower.Gurmukhi());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Gujarati), CodeCharts.Lower.Gujarati());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Oriya), CodeCharts.Lower.Oriya());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Tamil), CodeCharts.Lower.Tamil());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Telugu), CodeCharts.Lower.Telugu());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Kannada), CodeCharts.Lower.Kannada());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Malayalam), CodeCharts.Lower.Malayalam());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Sinhala), CodeCharts.Lower.Sinhala());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Thai), CodeCharts.Lower.Thai());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Lao), CodeCharts.Lower.Lao());
PunchHolesIfNeeded(ref safeList, CodeCharts.Lower.IsFlagSet(codeCharts, LowerCodeCharts.Tibetan), CodeCharts.Lower.Tibetan());
}
/// <summary>
/// Punch appropriate holes for the selected code charts.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="codeCharts">The code charts to punch.</param>
private static void PunchCodeCharts(ref char[][] safeList, LowerMidCodeCharts codeCharts) {
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Myanmar), CodeCharts.LowerMiddle.Myanmar());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Georgian), CodeCharts.LowerMiddle.Georgian());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.HangulJamo), CodeCharts.LowerMiddle.HangulJamo());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Ethiopic), CodeCharts.LowerMiddle.Ethiopic());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.EthiopicSupplement), CodeCharts.LowerMiddle.EthiopicSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Cherokee), CodeCharts.LowerMiddle.Cherokee());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.UnifiedCanadianAboriginalSyllabics), CodeCharts.LowerMiddle.UnifiedCanadianAboriginalSyllabics());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Ogham), CodeCharts.LowerMiddle.Ogham());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Runic), CodeCharts.LowerMiddle.Runic());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Tagalog), CodeCharts.LowerMiddle.Tagalog());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Hanunoo), CodeCharts.LowerMiddle.Hanunoo());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Buhid), CodeCharts.LowerMiddle.Buhid());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Tagbanwa), CodeCharts.LowerMiddle.Tagbanwa());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Khmer), CodeCharts.LowerMiddle.Khmer());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Mongolian), CodeCharts.LowerMiddle.Mongolian());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.UnifiedCanadianAboriginalSyllabicsExtended), CodeCharts.LowerMiddle.UnifiedCanadianAboriginalSyllabicsExtended());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Limbu), CodeCharts.LowerMiddle.Limbu());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.TaiLe), CodeCharts.LowerMiddle.TaiLe());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.NewTaiLue), CodeCharts.LowerMiddle.NewTaiLue());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.KhmerSymbols), CodeCharts.LowerMiddle.KhmerSymbols());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Buginese), CodeCharts.LowerMiddle.Buginese());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.TaiTham), CodeCharts.LowerMiddle.TaiTham());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Balinese), CodeCharts.LowerMiddle.Balinese());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Sudanese), CodeCharts.LowerMiddle.Sudanese());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.Lepcha), CodeCharts.LowerMiddle.Lepcha());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.OlChiki), CodeCharts.LowerMiddle.OlChiki());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.VedicExtensions), CodeCharts.LowerMiddle.VedicExtensions());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.PhoneticExtensions), CodeCharts.LowerMiddle.PhoneticExtensions());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.PhoneticExtensionsSupplement), CodeCharts.LowerMiddle.PhoneticExtensionsSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.CombiningDiacriticalMarksSupplement), CodeCharts.LowerMiddle.CombiningDiacriticalMarksSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.LowerMiddle.IsFlagSet(codeCharts, LowerMidCodeCharts.LatinExtendedAdditional), CodeCharts.LowerMiddle.LatinExtendedAdditional());
}
/// <summary>
/// Punch appropriate holes for the selected code charts.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="codeCharts">The code charts to punch.</param>
private static void PunchCodeCharts(ref char[][] safeList, MidCodeCharts codeCharts) {
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.GreekExtended), CodeCharts.Middle.GreekExtended());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.GeneralPunctuation), CodeCharts.Middle.GeneralPunctuation());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.SuperscriptsAndSubscripts), CodeCharts.Middle.SuperscriptsAndSubscripts());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.CurrencySymbols), CodeCharts.Middle.CurrencySymbols());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.CombiningDiacriticalMarksForSymbols), CodeCharts.Middle.CombiningDiacriticalMarksForSymbols());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.LetterlikeSymbols), CodeCharts.Middle.LetterlikeSymbols());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.NumberForms), CodeCharts.Middle.NumberForms());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.Arrows), CodeCharts.Middle.Arrows());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.MathematicalOperators), CodeCharts.Middle.MathematicalOperators());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.MiscellaneousTechnical), CodeCharts.Middle.MiscellaneousTechnical());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.ControlPictures), CodeCharts.Middle.ControlPictures());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.OpticalCharacterRecognition), CodeCharts.Middle.OpticalCharacterRecognition());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.EnclosedAlphanumerics), CodeCharts.Middle.EnclosedAlphanumerics());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.BoxDrawing), CodeCharts.Middle.BoxDrawing());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.BlockElements), CodeCharts.Middle.BlockElements());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.GeometricShapes), CodeCharts.Middle.GeometricShapes());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.MiscellaneousSymbols), CodeCharts.Middle.MiscellaneousSymbols());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.Dingbats), CodeCharts.Middle.Dingbats());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.MiscellaneousMathematicalSymbolsA), CodeCharts.Middle.MiscellaneousMathematicalSymbolsA());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.SupplementalArrowsA), CodeCharts.Middle.SupplementalArrowsA());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.BraillePatterns), CodeCharts.Middle.BraillePatterns());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.SupplementalArrowsB), CodeCharts.Middle.SupplementalArrowsB());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.MiscellaneousMathematicalSymbolsB), CodeCharts.Middle.MiscellaneousMathematicalSymbolsB());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.SupplementalMathematicalOperators), CodeCharts.Middle.SupplementalMathematicalOperators());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.MiscellaneousSymbolsAndArrows), CodeCharts.Middle.MiscellaneousSymbolsAndArrows());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.Glagolitic), CodeCharts.Middle.Glagolitic());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.LatinExtendedC), CodeCharts.Middle.LatinExtendedC());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.Coptic), CodeCharts.Middle.Coptic());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.GeorgianSupplement), CodeCharts.Middle.GeorgianSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.Tifinagh), CodeCharts.Middle.Tifinagh());
PunchHolesIfNeeded(ref safeList, CodeCharts.Middle.IsFlagSet(codeCharts, MidCodeCharts.EthiopicExtended), CodeCharts.Middle.EthiopicExtended());
}
/// <summary>
/// Punch appropriate holes for the selected code charts.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="codeCharts">The code charts to punch.</param>
private static void PunchCodeCharts(ref char[][] safeList, UpperMidCodeCharts codeCharts) {
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CyrillicExtendedA), CodeCharts.UpperMiddle.CyrillicExtendedA());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.SupplementalPunctuation), CodeCharts.UpperMiddle.SupplementalPunctuation());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CjkRadicalsSupplement), CodeCharts.UpperMiddle.CjkRadicalsSupplement());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.KangxiRadicals), CodeCharts.UpperMiddle.KangxiRadicals());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.IdeographicDescriptionCharacters), CodeCharts.UpperMiddle.IdeographicDescriptionCharacters());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CjkSymbolsAndPunctuation), CodeCharts.UpperMiddle.CjkSymbolsAndPunctuation());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Hiragana), CodeCharts.UpperMiddle.Hiragana());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Katakana), CodeCharts.UpperMiddle.Katakana());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Bopomofo), CodeCharts.UpperMiddle.Bopomofo());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.HangulCompatibilityJamo), CodeCharts.UpperMiddle.HangulCompatibilityJamo());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Kanbun), CodeCharts.UpperMiddle.Kanbun());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.BopomofoExtended), CodeCharts.UpperMiddle.BopomofoExtended());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CjkStrokes), CodeCharts.UpperMiddle.CjkStrokes());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.KatakanaPhoneticExtensions), CodeCharts.UpperMiddle.KatakanaPhoneticExtensions());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.EnclosedCjkLettersAndMonths), CodeCharts.UpperMiddle.EnclosedCjkLettersAndMonths());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CjkCompatibility), CodeCharts.UpperMiddle.CjkCompatibility());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CjkUnifiedIdeographsExtensionA), CodeCharts.UpperMiddle.CjkUnifiedIdeographsExtensionA());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.YijingHexagramSymbols), CodeCharts.UpperMiddle.YijingHexagramSymbols());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CjkUnifiedIdeographs), CodeCharts.UpperMiddle.CjkUnifiedIdeographs());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.YiSyllables), CodeCharts.UpperMiddle.YiSyllables());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.YiRadicals), CodeCharts.UpperMiddle.YiRadicals());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Lisu), CodeCharts.UpperMiddle.Lisu());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Vai), CodeCharts.UpperMiddle.Vai());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CyrillicExtendedB), CodeCharts.UpperMiddle.CyrillicExtendedB());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Bamum), CodeCharts.UpperMiddle.Bamum());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.ModifierToneLetters), CodeCharts.UpperMiddle.ModifierToneLetters());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.LatinExtendedD), CodeCharts.UpperMiddle.LatinExtendedD());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.SylotiNagri), CodeCharts.UpperMiddle.SylotiNagri());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.CommonIndicNumberForms), CodeCharts.UpperMiddle.CommonIndicNumberForms());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Phagspa), CodeCharts.UpperMiddle.Phagspa());
PunchHolesIfNeeded(ref safeList, CodeCharts.UpperMiddle.IsFlagSet(codeCharts, UpperMidCodeCharts.Saurashtra), CodeCharts.UpperMiddle.Saurashtra());
}
/// <summary>
/// Punch appropriate holes for the selected code charts.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="codeCharts">The code charts to punch.</param>
private static void PunchCodeCharts(ref char[][] safeList, UpperCodeCharts codeCharts) {
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.DevanagariExtended), CodeCharts.Upper.DevanagariExtended());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.KayahLi), CodeCharts.Upper.KayahLi());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.Rejang), CodeCharts.Upper.Rejang());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.HangulJamoExtendedA), CodeCharts.Upper.HangulJamoExtendedA());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.Javanese), CodeCharts.Upper.Javanese());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.Cham), CodeCharts.Upper.Cham());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.MyanmarExtendedA), CodeCharts.Upper.MyanmarExtendedA());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.TaiViet), CodeCharts.Upper.TaiViet());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.MeeteiMayek), CodeCharts.Upper.MeeteiMayek());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.HangulSyllables), CodeCharts.Upper.HangulSyllables());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.HangulJamoExtendedB), CodeCharts.Upper.HangulJamoExtendedB());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.CjkCompatibilityIdeographs), CodeCharts.Upper.CjkCompatibilityIdeographs());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.AlphabeticPresentationForms), CodeCharts.Upper.AlphabeticPresentationForms());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.ArabicPresentationFormsA), CodeCharts.Upper.ArabicPresentationFormsA());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.VariationSelectors), CodeCharts.Upper.VariationSelectors());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.VerticalForms), CodeCharts.Upper.VerticalForms());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.CombiningHalfMarks), CodeCharts.Upper.CombiningHalfMarks());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.CjkCompatibilityForms), CodeCharts.Upper.CjkCompatibilityForms());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.SmallFormVariants), CodeCharts.Upper.SmallFormVariants());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.ArabicPresentationFormsB), CodeCharts.Upper.ArabicPresentationFormsB());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.HalfWidthAndFullWidthForms), CodeCharts.Upper.HalfWidthAndFullWidthForms());
PunchHolesIfNeeded(ref safeList, CodeCharts.Upper.IsFlagSet(codeCharts, UpperCodeCharts.Specials), CodeCharts.Upper.Specials());
}
/// <summary>
/// Punches holes as necessary.
/// </summary>
/// <param name="safeList">The safe list to punch through.</param>
/// <param name="isNeeded">Value indicating whether the holes should be punched.</param>
/// <param name="----edCharacters">The list of character positions to punch.</param>
private static void PunchHolesIfNeeded(ref char[][] safeList, bool isNeeded, IEnumerable whiteListedCharacters) {
if (!isNeeded) {
return;
}
foreach (int offset in whiteListedCharacters) {
safeList[offset] = null;
}
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using Nini.Util;
namespace Nini.Config
{
#region ConfigKeyEventArgs class
/// <include file='ConfigKeyEventArgs.xml' path='//Delegate[@name="ConfigKeyEventHandler"]/docs/*' />
public delegate void ConfigKeyEventHandler (object sender, ConfigKeyEventArgs e);
/// <include file='ConfigEventArgs.xml' path='//Class[@name="ConfigEventArgs"]/docs/*' />
public class ConfigKeyEventArgs : EventArgs
{
string keyName = null;
string keyValue = null;
/// <include file='ConfigEventArgs.xml' path='//Constructor[@name="Constructor"]/docs/*' />
public ConfigKeyEventArgs (string keyName, string keyValue)
{
this.keyName = keyName;
this.keyValue = keyValue;
}
/// <include file='ConfigEventArgs.xml' path='//Property[@name="KeyName"]/docs/*' />
public string KeyName
{
get { return keyName; }
}
/// <include file='ConfigEventArgs.xml' path='//Property[@name="KeyValue"]/docs/*' />
public string KeyValue
{
get { return keyValue; }
}
}
#endregion
/// <include file='IConfig.xml' path='//Interface[@name="IConfig"]/docs/*' />
public class ConfigBase : IConfig
{
#region Private variables
string configName = null;
IConfigSource configSource = null;
AliasText aliasText = null;
IFormatProvider format = CultureInfo.InvariantCulture; //NumberFormatInfo.CurrentInfo;
#endregion
#region Protected variables
protected OrderedList keys = new OrderedList ();
#endregion
#region Constructors
/// <include file='ConfigBase.xml' path='//Constructor[@name="ConfigBase"]/docs/*' />
public ConfigBase (string name, IConfigSource source)
{
configName = name;
configSource = source;
aliasText = new AliasText ();
}
#endregion
#region Public properties
/// <include file='IConfig.xml' path='//Property[@name="Name"]/docs/*' />
public string Name
{
get { return configName; }
set {
if (configName != value) {
Rename (value);
}
}
}
/// <include file='IConfig.xml' path='//Property[@name="ConfigSource"]/docs/*' />
public IConfigSource ConfigSource
{
get { return configSource; }
}
/// <include file='IConfig.xml' path='//Property[@name="Alias"]/docs/*' />
public AliasText Alias
{
get { return aliasText; }
}
#endregion
#region Public methods
/// <include file='IConfig.xml' path='//Method[@name="Contains"]/docs/*' />
public bool Contains (string key)
{
return (Get (key) != null);
}
/// <include file='IConfig.xml' path='//Method[@name="Get"]/docs/*' />
public virtual string Get (string key)
{
string result = null;
if (keys.Contains (key)) {
result = keys[key].ToString ();
}
return result;
}
/// <include file='IConfig.xml' path='//Method[@name="GetDefault"]/docs/*' />
public string Get (string key, string defaultValue)
{
string result = Get (key);
return (result == null) ? defaultValue : result;
}
/// <include file='IConfig.xml' path='//Method[@name="GetExpanded"]/docs/*' />
public string GetExpanded (string key)
{
return this.ConfigSource.GetExpanded(this, key);
}
/// <include file='IConfig.xml' path='//Method[@name="Get"]/docs/*' />
public string GetString (string key)
{
return Get (key);
}
/// <include file='IConfig.xml' path='//Method[@name="GetDefault"]/docs/*' />
public string GetString (string key, string defaultValue)
{
return Get (key, defaultValue);
}
/// <include file='IConfig.xml' path='//Method[@name="GetInt"]/docs/*' />
public int GetInt (string key)
{
string text = Get (key);
if (text == null) {
throw new ArgumentException ("Value not found: " + key);
}
return Convert.ToInt32 (text, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetIntAlias"]/docs/*' />
public int GetInt (string key, bool fromAlias)
{
if (!fromAlias) {
return GetInt (key);
}
string result = Get (key);
if (result == null) {
throw new ArgumentException ("Value not found: " + key);
}
return GetIntAlias (key, result);
}
/// <include file='IConfig.xml' path='//Method[@name="GetIntDefault"]/docs/*' />
public int GetInt (string key, int defaultValue)
{
string result = Get (key);
return (result == null)
? defaultValue
: Convert.ToInt32 (result, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetIntDefaultAlias"]/docs/*' />
public int GetInt (string key, int defaultValue, bool fromAlias)
{
if (!fromAlias) {
return GetInt (key, defaultValue);
}
string result = Get (key);
return (result == null) ? defaultValue : GetIntAlias (key, result);
}
/// <include file='IConfig.xml' path='//Method[@name="GetLong"]/docs/*' />
public long GetLong (string key)
{
string text = Get (key);
if (text == null) {
throw new ArgumentException ("Value not found: " + key);
}
return Convert.ToInt64 (text, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetLongDefault"]/docs/*' />
public long GetLong (string key, long defaultValue)
{
string result = Get (key);
return (result == null)
? defaultValue
: Convert.ToInt64 (result, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetBoolean"]/docs/*' />
public bool GetBoolean (string key)
{
string text = Get (key);
if (text == null) {
throw new ArgumentException ("Value not found: " + key);
}
return GetBooleanAlias (text);
}
/// <include file='IConfig.xml' path='//Method[@name="GetBooleanDefault"]/docs/*' />
public bool GetBoolean (string key, bool defaultValue)
{
string text = Get (key);
return (text == null) ? defaultValue : GetBooleanAlias (text);
}
/// <include file='IConfig.xml' path='//Method[@name="GetFloat"]/docs/*' />
public float GetFloat (string key)
{
string text = Get (key);
if (text == null) {
throw new ArgumentException ("Value not found: " + key);
}
return Convert.ToSingle (text, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetFloatDefault"]/docs/*' />
public float GetFloat (string key, float defaultValue)
{
string result = Get (key);
return (result == null)
? defaultValue
: Convert.ToSingle (result, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetDouble"]/docs/*' />
public double GetDouble (string key)
{
string text = Get (key);
if (text == null) {
throw new ArgumentException ("Value not found: " + key);
}
return Convert.ToDouble (text, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetDoubleDefault"]/docs/*' />
public double GetDouble (string key, double defaultValue)
{
string result = Get (key);
return (result == null)
? defaultValue
: Convert.ToDouble (result, format);
}
/// <include file='IConfig.xml' path='//Method[@name="GetKeys"]/docs/*' />
public string[] GetKeys ()
{
string[] result = new string[keys.Keys.Count];
keys.Keys.CopyTo (result, 0);
return result;
}
/// <include file='IConfig.xml' path='//Method[@name="GetValues"]/docs/*' />
public string[] GetValues ()
{
string[] result = new string[keys.Values.Count];
keys.Values.CopyTo (result, 0);
return result;
}
/// <include file='ConfigBase.xml' path='//Method[@name="Add"]/docs/*' />
public void Add (string key, string value)
{
keys.Add (key, value);
}
/// <include file='IConfig.xml' path='//Method[@name="Set"]/docs/*' />
public virtual void Set (string key, object value)
{
if (value == null) {
throw new ArgumentNullException ("Value cannot be null");
}
if (Get (key) == null) {
this.Add (key, value.ToString ());
} else {
keys[key] = value.ToString ();
}
if (ConfigSource.AutoSave) {
ConfigSource.Save ();
}
OnKeySet (new ConfigKeyEventArgs (key, value.ToString ()));
}
/// <include file='IConfig.xml' path='//Method[@name="Remove"]/docs/*' />
public virtual void Remove (string key)
{
if (key == null) {
throw new ArgumentNullException ("Key cannot be null");
}
if (Get (key) != null) {
string keyValue = null;
if (KeySet != null) {
keyValue = Get (key);
}
keys.Remove (key);
OnKeyRemoved (new ConfigKeyEventArgs (key, keyValue));
}
}
#endregion
#region Public events
/// <include file='IConfig.xml' path='//Event[@name="KeySet"]/docs/*' />
public event ConfigKeyEventHandler KeySet;
/// <include file='IConfig.xml' path='//Event[@name="KeyRemoved"]/docs/*' />
public event ConfigKeyEventHandler KeyRemoved;
#endregion
#region Protected methods
/// <include file='ConfigBase.xml' path='//Method[@name="OnKeySet"]/docs/*' />
protected void OnKeySet (ConfigKeyEventArgs e)
{
if (KeySet != null) {
KeySet (this, e);
}
}
/// <include file='ConfigBase.xml' path='//Method[@name="OnKeyRemoved"]/docs/*' />
protected void OnKeyRemoved (ConfigKeyEventArgs e)
{
if (KeyRemoved != null) {
KeyRemoved (this, e);
}
}
#endregion
#region Private methods
/// <summary>
/// Renames the config to the new name.
/// </summary>
private void Rename (string name)
{
this.ConfigSource.Configs.Remove (this);
configName = name;
this.ConfigSource.Configs.Add (this);
}
/// <summary>
/// Returns the integer alias first from this IConfig then
/// the parent if there is none.
/// </summary>
private int GetIntAlias (string key, string alias)
{
int result = -1;
if (aliasText.ContainsInt (key, alias)) {
result = aliasText.GetInt (key, alias);
} else {
result = ConfigSource.Alias.GetInt (key, alias);
}
return result;
}
/// <summary>
/// Returns the boolean alias first from this IConfig then
/// the parent if there is none.
/// </summary>
private bool GetBooleanAlias (string key)
{
bool result = false;
if (aliasText.ContainsBoolean (key)) {
result = aliasText.GetBoolean (key);
} else {
if (ConfigSource.Alias.ContainsBoolean (key)) {
result = ConfigSource.Alias.GetBoolean (key);
} else {
throw new ArgumentException
("Alias value not found: " + key
+ ". Add it to the Alias property.");
}
}
return result;
}
#endregion
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using Leap.Unity.Attributes;
using Leap.Unity.Interaction;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Leap.Unity.Interaction {
/// <summary>
/// AnchorableBehaviours mix well with InteractionBehaviours you'd like to be able to
/// pick up and place in specific locations, specified by other GameObjects with an
/// Anchor component.
/// </summary>
public class AnchorableBehaviour : MonoBehaviour {
[Disable]
[SerializeField]
[Tooltip("Whether or not this AnchorableBehaviour is actively attached to its anchor.")]
private bool _isAttached = false;
public bool isAttached {
get {
return _isAttached;
}
set {
if (_isAttached != value) {
if (value == true) {
if (_anchor != null) {
_isAttached = value;
_anchor.NotifyAttached(this);
OnAttachedToAnchor.Invoke(this, _anchor);
}
else {
Debug.LogWarning("Tried to attach an anchorable behaviour, but it has no assigned anchor.", this.gameObject);
}
}
else {
_isAttached = false;
_isLockedToAnchor = false;
_isRotationLockedToAnchor = false;
OnDetachedFromAnchor.Invoke(this, _anchor);
_anchor.NotifyDetached(this);
_hasTargetPositionLastUpdate = false;
_hasTargetRotationLastUpdate = false;
// TODO: A more robust gravity fix.
if (_reactivateGravityOnDetach) {
if (interactionBehaviour != null) {
interactionBehaviour.rigidbody.useGravity = true;
}
_reactivateGravityOnDetach = false;
}
}
}
}
}
[Tooltip("The current anchor of this AnchorableBehaviour.")]
[OnEditorChange("anchor"), SerializeField]
private Anchor _anchor;
public Anchor anchor {
get {
return _anchor;
}
set {
if (_anchor != value) {
if (IsValidAnchor(value)) {
if (_anchor != null) {
OnDetachedFromAnchor.Invoke(this, _anchor);
_anchor.NotifyDetached(this);
}
_isLockedToAnchor = false;
_isRotationLockedToAnchor = false;
_anchor = value;
_hasTargetPositionLastUpdate = false;
_hasTargetRotationLastUpdate = false;
if (_anchor != null) {
isAttached = true;
}
else {
isAttached = false;
}
}
else {
Debug.LogWarning("The '" + value.name + "' anchor is not in " + this.name + "'s anchor group.", this.gameObject);
}
}
}
}
[Tooltip("The anchor group for this AnchorableBehaviour. If set to null, all Anchors "
+ "will be valid anchors for this object.")]
[OnEditorChange("anchorGroup"), SerializeField]
private AnchorGroup _anchorGroup;
public AnchorGroup anchorGroup {
get { return _anchorGroup; }
set {
if (_anchorGroup != null) _anchorGroup.NotifyAnchorableObjectRemoved(this);
_anchorGroup = value;
if (anchor != null && !_anchorGroup.Contains(anchor)) {
anchor = null;
Debug.LogWarning(this.name + "'s anchor is not within its anchorGroup (setting it to null).", this.gameObject);
}
if (_anchorGroup != null) _anchorGroup.NotifyAnchorableObjectAdded(this);
}
}
[Header("Attachment")]
[Tooltip("Anchors beyond this range are ignored as possible anchors for this object.")]
public float maxAnchorRange = 0.3F;
[Tooltip("Only allowed when an InteractionBehaviour is attached to this object. If enabled, this "
+ "object's Attach() method or its variants will weigh its velocity towards an anchor along "
+ "with its proximity when seeking an anchor to attach to.")]
[DisableIf("_interactionBehaviourIsNull", true)]
public bool useTrajectory = true;
[Tooltip("The fraction of the maximum anchor range to use as the effective max range when "
+ "useTrajectory is enabled, but the object attempts to find an anchor without any "
+ "velocity.")]
[SerializeField]
[Range(0.01F, 1F)]
private float _motionlessRangeFraction = 0.40F;
[SerializeField, Disable]
private float _maxMotionlessRange;
[Tooltip("The maximum angle this object's trajectory can be away from an anchor to consider it as "
+ "an anchor to attach to.")]
[SerializeField]
[Range(20F, 90F)]
private float _maxAttachmentAngle = 60F;
/// <summary> Calculated via _maxAttachmentAngle. </summary>
private float _minAttachmentDotProduct;
[Header("Motion")]
[Tooltip("Should the object move instantly to the anchor position?")]
public bool lockToAnchor = false;
[Tooltip("Should the object move smoothly towards the anchor at first, but lock to it once it reaches the anchor? "
+ "Note: Disabling the AnchorableBehaviour will stop the object from moving towards its anchor, and will "
+ "'release' it from the anchor, so that on re-enable the object will smoothly move to the anchor again.")]
[DisableIf("lockToAnchor", isEqualTo: true)]
public bool lockWhenAttached = true;
[Tooltip("While this object is moving smoothly towards its anchor, should it also inherit the motion of the "
+ "anchor itself if the anchor is not stationary? Otherwise, the anchor might be able to run away from this "
+ "AnchorableBehaviour and prevent it from actually getting to the anchor.")]
[DisableIf("lockToAnchor", isEqualTo: true)]
public bool matchAnchorMotionWhileAttaching = true;
[Tooltip("How fast should the object move towards its target position? Higher values are faster.")]
[DisableIf("lockToAnchor", isEqualTo: true)]
[Range(0, 100F)]
public float anchorLerpCoeffPerSec = 20F;
[Header("Rotation")]
[Tooltip("Should the object also rotate to match its anchor's rotation? If checked, motion settings applied "
+ "to how the anchor translates will also apply to how it rotates.")]
public bool anchorRotation = false;
[Header("Interaction")]
[Tooltip("Additional features are enabled when this GameObject also has an InteractionBehaviour component.")]
[Disable]
public InteractionBehaviour interactionBehaviour;
[SerializeField, HideInInspector]
private bool _interactionBehaviourIsNull = true;
[Tooltip("If the InteractionBehaviour is set, objects will automatically detach from their anchor when grasped.")]
[Disable]
public bool detachWhenGrasped = true;
[Tooltip("Should the AnchorableBehaviour automatically try to anchor itself when a grasp ends? If useTrajectory is enabled, "
+ "this object will automatically attempt to attach to the nearest valid anchor that is in the direction of its trajectory, "
+ "otherwise it will simply attempt to attach to its nearest valid anchor.")]
[SerializeField]
[OnEditorChange("tryAnchorNearestOnGraspEnd")]
private bool _tryAnchorNearestOnGraspEnd = true;
public bool tryAnchorNearestOnGraspEnd {
get {
return _tryAnchorNearestOnGraspEnd;
}
set {
if (interactionBehaviour != null) {
// Prevent duplicate subscription.
interactionBehaviour.OnGraspEnd -= tryToAnchorOnGraspEnd;
}
_tryAnchorNearestOnGraspEnd = value;
if (interactionBehaviour != null && _tryAnchorNearestOnGraspEnd) {
interactionBehaviour.OnGraspEnd += tryToAnchorOnGraspEnd;
}
}
}
[Tooltip("Should the object pull away from its anchor and reach towards the user's hand when the user's hand is nearby?")]
public bool isAttractedByHand = false;
[Tooltip("If the object is attracted to hands, how far should the object be allowed to pull away from its anchor "
+ "towards a nearby InteractionHand? Value is in Unity distance units, WORLD space.")]
public float maxAttractionReach = 0.1F;
[Tooltip("This curve converts the distance of the hand (X axis) to the desired attraction reach distance for the object (Y axis). "
+ "The evaluated value is clamped between 0 and 1, and then scaled by maxAttractionReach.")]
public AnimationCurve attractionReachByDistance;
private Anchor _preferredAnchor = null;
/// <summary>
/// Gets the anchor this AnchorableBehaviour would most prefer to attach to.
/// This value is refreshed every Update() during which the AnchorableBehaviour
/// has no anchor or is detached from its current anchor.
/// </summary>
public Anchor preferredAnchor { get { return _preferredAnchor; } }
#region Events
/// <summary>
/// Called when this AnchorableBehaviour attaches to an Anchor.
/// </summary>
public Action<AnchorableBehaviour, Anchor> OnAttachedToAnchor = (anchObj, anchor) => { };
/// <summary>
/// Called when this AnchorableBehaviour locks to an Anchor.
/// </summary>
public Action<AnchorableBehaviour, Anchor> OnLockedToAnchor = (anchObj, anchor) => { };
/// <summary>
/// Called when this AnchorableBehaviour detaches from an Anchor.
/// </summary>
public Action<AnchorableBehaviour, Anchor> OnDetachedFromAnchor = (anchObj, anchor) => { };
/// <summary>
/// Called during every Update() in which this AnchorableBehaviour is attached to an Anchor.
/// </summary>
public Action<AnchorableBehaviour, Anchor> WhileAttachedToAnchor = (anchObj, anchor) => { };
/// <summary>
/// Called during every Update() in which this AnchorableBehaviour is locked to an Anchor.
/// </summary>
public Action<AnchorableBehaviour, Anchor> WhileLockedToAnchor = (anchObj, anchor) => { };
/// <summary>
/// Called just after this anchorable behaviour's InteractionBehaviour OnObjectGraspEnd for
/// this anchor. This callback will never fire if tryAttachAnchorOnGraspEnd is not enabled.
///
/// If tryAttachAnchorOnGraspEnd is enabled, the anchor will be attached to
/// an anchor only if its preferredAnchor property is false; otherwise, the attempt to
/// anchor failed.
/// </summary>
public Action<AnchorableBehaviour> OnPostTryAnchorOnGraspEnd = (anchObj) => { };
#endregion
private bool _isLockedToAnchor = false;
private Vector3 _offsetTowardsHand = Vector3.zero;
private Vector3 _targetPositionLastUpdate = Vector3.zero;
private bool _hasTargetPositionLastUpdate = false;
private bool _isRotationLockedToAnchor = false;
private Quaternion _targetRotationLastUpdate = Quaternion.identity;
private bool _hasTargetRotationLastUpdate = false;
void OnValidate() {
refreshInteractionBehaviour();
refreshInspectorConveniences();
}
void Reset() {
refreshInteractionBehaviour();
}
void Awake() {
refreshInteractionBehaviour();
refreshInspectorConveniences();
if (interactionBehaviour != null) {
interactionBehaviour.OnGraspBegin += detachAnchorOnGraspBegin;
if (_tryAnchorNearestOnGraspEnd) {
interactionBehaviour.OnGraspEnd += tryToAnchorOnGraspEnd;
}
}
initUnityEvents();
}
void Start() {
if (anchor != null && _isAttached) {
anchor.NotifyAttached(this);
OnAttachedToAnchor(this, anchor);
}
}
private bool _reactivateGravityOnDetach = false;
void Update() {
updateAttractionToHand();
if (anchor != null && isAttached) {
if (interactionBehaviour != null && interactionBehaviour.rigidbody.useGravity) {
// TODO: This is a temporary fix for gravity to be fixed in a future IE PR.
// The proper solution involves switching the behaviour to FixedUpdate and more
// intelligently communicating with the attached InteractionBehaviour.
interactionBehaviour.rigidbody.useGravity = false;
_reactivateGravityOnDetach = true;
}
updateAnchorAttachment();
updateAnchorAttachmentRotation();
WhileAttachedToAnchor.Invoke(this, anchor);
if (_isLockedToAnchor) {
WhileLockedToAnchor.Invoke(this, anchor);
}
}
updateAnchorPreference();
}
void OnDisable() {
if (!this.enabled) {
Detach();
}
// Make sure we don't leave dangling anchor-preference state.
endAnchorPreference();
}
void OnDestroy() {
if (interactionBehaviour != null) {
interactionBehaviour.OnGraspBegin -= detachAnchorOnGraspBegin;
interactionBehaviour.OnGraspEnd -= tryToAnchorOnGraspEnd;
}
// Make sure we don't leave dangling anchor-preference state.
endAnchorPreference();
}
private void refreshInspectorConveniences() {
_minAttachmentDotProduct = Mathf.Cos(_maxAttachmentAngle * Mathf.Deg2Rad);
_maxMotionlessRange = maxAnchorRange * _motionlessRangeFraction;
}
private void refreshInteractionBehaviour() {
interactionBehaviour = GetComponent<InteractionBehaviour>();
_interactionBehaviourIsNull = interactionBehaviour == null;
detachWhenGrasped = !_interactionBehaviourIsNull;
if (_interactionBehaviourIsNull) useTrajectory = false;
}
/// <summary>
/// Detaches this Anchorable object from its anchor. The anchor reference
/// remains unchanged. Call TryAttach() to re-attach to this object's assigned anchor.
/// </summary>
public void Detach() {
isAttached = false;
}
/// <summary>
/// Returns whether the argument anchor is an acceptable anchor for this anchorable
/// object; that is, whether the argument Anchor is within this behaviour's AnchorGroup
/// if it has one, or if this behaviour has no AnchorGroup, returns true.
/// </summary>
public bool IsValidAnchor(Anchor anchor) {
if (this.anchorGroup != null) {
return this.anchorGroup.Contains(anchor);
}
else {
return true;
}
}
/// <summary>
/// Returns whether the specified anchor is within attachment range of this Anchorable object.
/// </summary>
public bool IsWithinRange(Anchor anchor) {
return (this.transform.position - anchor.transform.position).sqrMagnitude < maxAnchorRange * maxAnchorRange;
}
/// <summary>
/// Attempts to find and return the best anchor for this anchorable object to attach to
/// based on its current configuration. If useTrajectory is enabled, the object will
/// consider anchor proximity as well as its own trajectory towards a particular anchor,
/// and may return null if the object is moving away from all of its possible anchors.
/// Otherwise, the object will simply return the nearest valid anchor, or null if there
/// is no valid anchor nearby.
///
/// This method is called every Update() automatically by anchorable objects, and its
/// result is stored in preferredAnchor. Only call this if you need a new calculation.
/// </summary>
public Anchor FindPreferredAnchor() {
if (!useTrajectory) {
// Simply try to attach to the nearest valid anchor.
return GetNearestValidAnchor();
}
else {
// Pick the nearby valid anchor with the highest score, based on proximity and trajectory.
Anchor optimalAnchor = null;
float optimalScore = 0F;
Anchor testAnchor = null;
float testScore = 0F;
foreach (var anchor in GetNearbyValidAnchors()) {
testAnchor = anchor;
testScore = getAnchorScore(anchor);
// Scores of 0 mark ineligible anchors.
if (testScore == 0F) continue;
if (testScore > optimalScore) {
optimalAnchor = testAnchor;
optimalScore = testScore;
}
}
return optimalAnchor;
}
}
private List<Anchor> _nearbyAnchorsBuffer = new List<Anchor>();
/// <summary>
/// Returns all anchors within the max anchor range of this anchorable object. If this
/// anchorable object has its anchorGroup property set, only anchors within that AnchorGroup
/// will be returned. By default, this method will only return anchors that have space for
/// an object to attach to it.
///
/// Warning: This method checks squared-distance for all anchors in teh scene if this
/// AnchorableBehaviour has no AnchorGroup.
/// </summary>
public List<Anchor> GetNearbyValidAnchors(bool requireAnchorHasSpace = true,
bool requireAnchorActiveAndEnabled = true) {
HashSet<Anchor> anchorsToCheck;
if (this.anchorGroup == null) {
anchorsToCheck = Anchor.allAnchors;
}
else {
anchorsToCheck = this.anchorGroup.anchors;
}
_nearbyAnchorsBuffer.Clear();
foreach (var anchor in anchorsToCheck) {
if ((requireAnchorHasSpace && (!anchor.allowMultipleObjects && anchor.anchoredObjects.Count != 0))
|| (requireAnchorActiveAndEnabled && !anchor.isActiveAndEnabled)) continue;
if ((anchor.transform.position - this.transform.position).sqrMagnitude <= maxAnchorRange * maxAnchorRange) {
_nearbyAnchorsBuffer.Add(anchor);
}
}
return _nearbyAnchorsBuffer;
}
/// <summary>
/// Returns the nearest valid anchor to this Anchorable object. If this anchorable object has its
/// anchorGroup property set, all anchors within that AnchorGroup are valid to be this object's
/// anchor. If there is no valid anchor within range, returns null. By default, this method will
/// only return anchors that are within the max anchor range of this object and that have space for
/// an object to attach to it.
///
/// Warning: This method checks squared-distance for all anchors in the scene if this AnchorableBehaviour
/// has no AnchorGroup.
/// </summary>
public Anchor GetNearestValidAnchor(bool requireWithinRange = true,
bool requireAnchorHasSpace = true,
bool requireAnchorActiveAndEnabled = true) {
HashSet<Anchor> anchorsToCheck;
if (this.anchorGroup == null) {
anchorsToCheck = Anchor.allAnchors;
}
else {
anchorsToCheck = this.anchorGroup.anchors;
}
Anchor closestAnchor = null;
float closestDistSqrd = float.PositiveInfinity;
foreach (var testAnchor in anchorsToCheck) {
if ((requireAnchorHasSpace && (!anchor.allowMultipleObjects || anchor.anchoredObjects.Count == 0))
|| (requireAnchorActiveAndEnabled && !anchor.isActiveAndEnabled)) continue;
float testDistanceSqrd = (testAnchor.transform.position - this.transform.position).sqrMagnitude;
if (testDistanceSqrd < closestDistSqrd) {
closestAnchor = testAnchor;
closestDistSqrd = testDistanceSqrd;
}
}
if (!requireWithinRange || closestDistSqrd < maxAnchorRange * maxAnchorRange) {
return closestAnchor;
}
else {
return null;
}
}
/// <summary>
/// Attempts to attach to this Anchorable object's currently specified anchor.
/// The attempt may fail if this anchor is out of range. Optionally, the range
/// requirement can be ignored.
/// </summary>
public bool TryAttach(bool ignoreRange = false) {
if (anchor != null && (ignoreRange || IsWithinRange(anchor))) {
isAttached = true;
return true;
}
else {
return false;
}
}
/// <summary>
/// Attempts to find and attach this anchorable object to the nearest valid anchor, or the
/// most optimal nearby anchor based on proximity and the object's trajectory if useTrajectory
/// is enabled.
/// </summary>
public bool TryAttachToNearestAnchor() {
Anchor preferredAnchor = FindPreferredAnchor();
if (preferredAnchor != null) {
_preferredAnchor = preferredAnchor;
anchor = preferredAnchor;
isAttached = true;
return true;
}
return false;
}
/// <summary> Score an anchor based on its proximity and this object's trajectory relative to it. </summary>
private float getAnchorScore(Anchor anchor) {
return GetAnchorScore(this.interactionBehaviour.rigidbody.position,
this.interactionBehaviour.rigidbody.velocity,
anchor.transform.position,
maxAnchorRange,
_maxMotionlessRange,
_minAttachmentDotProduct);
}
/// <summary>
/// Calculates and returns a score from 0 (non-valid anchor) to 1 (ideal anchor) based on
/// the argument configuration, using an anchorable object's position and velocity, an
/// anchor position, and distance/angle settings. A score of zero indicates an invalid
/// anchor no matter what; a non-zero score indicates a possible anchor, with more optimal
/// anchors receiving a score closer to 1.
/// </summary>
public static float GetAnchorScore(Vector3 anchObjPos, Vector3 anchObjVel, Vector3 anchorPos, float maxDistance, float nonDirectedMaxDistance, float minAngleProduct) {
// Calculated a "directedness" heuristic for determining whether the user is throwing or releasing without directed motion.
float directedness = anchObjVel.magnitude.Map(0.2F, 1F, 0F, 1F);
float distanceSqrd = (anchorPos - anchObjPos).sqrMagnitude;
float effMaxDistance = directedness.Map(0F, 1F, nonDirectedMaxDistance, maxDistance);
float distanceScore;
if (distanceSqrd > effMaxDistance * effMaxDistance) {
distanceScore = 0F;
}
else {
distanceScore = distanceSqrd.Map(0F, effMaxDistance * effMaxDistance, 1F, 0F);
}
float angleScore;
float dotProduct = Vector3.Dot(anchObjVel.normalized, (anchorPos - anchObjPos).normalized);
// Angular score only factors in based on how directed the motion of the object is.
dotProduct = Mathf.Lerp(1F, dotProduct, directedness);
if (dotProduct < minAngleProduct) {
angleScore = 0F;
}
else {
angleScore = dotProduct.Map(minAngleProduct, 1F, 0F, 1F);
angleScore *= angleScore;
}
return distanceScore * angleScore;
}
private void updateAttractionToHand() {
if (interactionBehaviour == null || !isAttractedByHand) {
if (_offsetTowardsHand != Vector3.zero) {
_offsetTowardsHand = Vector3.Lerp(_offsetTowardsHand, Vector3.zero, 5F * Time.deltaTime);
}
return;
}
float reachTargetAmount = 0F;
Vector3 towardsHand = Vector3.zero;
if (interactionBehaviour != null) {
if (isAttractedByHand) {
if (interactionBehaviour.isHovered) {
Hand hoveringHand = interactionBehaviour.closestHoveringHand;
reachTargetAmount = Mathf.Clamp01(attractionReachByDistance.Evaluate(
Vector3.Distance(hoveringHand.PalmPosition.ToVector3(), anchor.transform.position)
));
towardsHand = hoveringHand.PalmPosition.ToVector3() - anchor.transform.position;
}
Vector3 targetOffsetTowardsHand = towardsHand * maxAttractionReach * reachTargetAmount;
_offsetTowardsHand = Vector3.Lerp(_offsetTowardsHand, targetOffsetTowardsHand, 5 * Time.deltaTime);
}
}
}
private void updateAnchorAttachment() {
// Initialize position.
Vector3 finalPosition;
if (interactionBehaviour != null) {
finalPosition = interactionBehaviour.rigidbody.position;
}
else {
finalPosition = this.transform.position;
}
// Update position based on anchor state.
Vector3 targetPosition = anchor.transform.position;
if (lockToAnchor) {
// In this state, we are simply locked directly to the anchor.
finalPosition = targetPosition + _offsetTowardsHand;
// Reset anchor position storage; it can't be updated from this state.
_hasTargetPositionLastUpdate = false;
}
else if (lockWhenAttached) {
if (_isLockedToAnchor) {
// In this state, we are already attached to the anchor.
finalPosition = targetPosition + _offsetTowardsHand;
// Reset anchor position storage; it can't be updated from this state.
_hasTargetPositionLastUpdate = false;
}
else {
// Undo any "reach towards hand" offset.
finalPosition -= _offsetTowardsHand;
// If desired, automatically correct for the anchor itself moving while attempting to return to it.
if (matchAnchorMotionWhileAttaching && this.transform.parent != anchor.transform) {
if (_hasTargetPositionLastUpdate) {
finalPosition += (targetPosition - _targetPositionLastUpdate);
}
_targetPositionLastUpdate = targetPosition;
_hasTargetPositionLastUpdate = true;
}
// Lerp towards the anchor.
finalPosition = Vector3.Lerp(finalPosition, targetPosition, anchorLerpCoeffPerSec * Time.deltaTime);
if (Vector3.Distance(finalPosition, targetPosition) < 0.001F) {
_isLockedToAnchor = true;
}
// Redo any "reach toward hand" offset.
finalPosition += _offsetTowardsHand;
}
}
// Set final position.
if (interactionBehaviour != null) {
interactionBehaviour.rigidbody.position = finalPosition;
this.transform.position = finalPosition;
}
else {
this.transform.position = finalPosition;
}
}
private void updateAnchorAttachmentRotation() {
// Initialize rotation.
Quaternion finalRotation;
if (interactionBehaviour != null) {
finalRotation = interactionBehaviour.rigidbody.rotation;
}
else {
finalRotation = this.transform.rotation;
}
// Update rotation based on anchor state.
Quaternion targetRotation = anchor.transform.rotation;
if (lockToAnchor) {
// In this state, we are simply locked directly to the anchor.
finalRotation = targetRotation;
// Reset anchor rotation storage; it can't be updated from this state.
_hasTargetPositionLastUpdate = false;
}
else if (lockWhenAttached) {
if (_isRotationLockedToAnchor) {
// In this state, we are already attached to the anchor.
finalRotation = targetRotation;
// Reset anchor rotation storage; it can't be updated from this state.
_hasTargetRotationLastUpdate = false;
}
else {
// If desired, automatically correct for the anchor itself moving while attempting to return to it.
if (matchAnchorMotionWhileAttaching && this.transform.parent != anchor.transform) {
if (_hasTargetRotationLastUpdate) {
finalRotation = (Quaternion.Inverse(_targetRotationLastUpdate) * targetRotation) * finalRotation;
}
_targetRotationLastUpdate = targetRotation;
_hasTargetRotationLastUpdate = true;
}
// Slerp towards the anchor rotation.
finalRotation = Quaternion.Slerp(finalRotation, targetRotation, anchorLerpCoeffPerSec * 0.8F * Time.deltaTime);
if (Quaternion.Angle(targetRotation, finalRotation) < 2F) {
_isRotationLockedToAnchor = true;
}
}
}
// Set final rotation.
if (interactionBehaviour != null) {
interactionBehaviour.rigidbody.rotation = finalRotation;
this.transform.rotation = finalRotation;
}
else {
this.transform.rotation = finalRotation;
}
}
private void updateAnchorPreference() {
Anchor newPreferredAnchor;
if (!isAttached) {
newPreferredAnchor = FindPreferredAnchor();
}
else {
newPreferredAnchor = null;
}
if (_preferredAnchor != newPreferredAnchor) {
if (_preferredAnchor != null) {
_preferredAnchor.NotifyEndAnchorPreference(this);
}
_preferredAnchor = newPreferredAnchor;
if (_preferredAnchor != null) {
_preferredAnchor.NotifyAnchorPreference(this);
}
}
}
private void endAnchorPreference() {
if (_preferredAnchor != null) {
_preferredAnchor.NotifyEndAnchorPreference(this);
_preferredAnchor = null;
}
}
private void detachAnchorOnGraspBegin() {
Detach();
}
private void tryToAnchorOnGraspEnd() {
TryAttachToNearestAnchor();
OnPostTryAnchorOnGraspEnd(this);
}
#region Unity Events (Internal)
[SerializeField]
private EnumEventTable _eventTable;
public enum EventType {
OnAttachedToAnchor = 100,
OnLockedToAnchor = 105,
OnDetachedFromAnchor = 110,
WhileAttachedToAnchor = 120,
WhileLockedToAnchor = 125,
OnPostTryAnchorOnGraspEnd = 130
}
private void initUnityEvents() {
setupCallback(ref OnAttachedToAnchor, EventType.OnAttachedToAnchor);
setupCallback(ref OnLockedToAnchor, EventType.OnLockedToAnchor);
setupCallback(ref OnDetachedFromAnchor, EventType.OnDetachedFromAnchor);
setupCallback(ref WhileAttachedToAnchor, EventType.WhileAttachedToAnchor);
setupCallback(ref WhileLockedToAnchor, EventType.WhileLockedToAnchor);
setupCallback(ref OnPostTryAnchorOnGraspEnd, EventType.OnPostTryAnchorOnGraspEnd);
}
private void setupCallback<T1, T2>(ref Action<T1, T2> action, EventType type)
where T1 : AnchorableBehaviour
where T2 : Anchor {
action += (anchObj, anchor) => _eventTable.Invoke((int)type);
}
private void setupCallback<T>(ref Action<T> action, EventType type)
where T : AnchorableBehaviour {
action += (anchObj) => _eventTable.Invoke((int)type);
}
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using System.Xml;
using Ecosim;
using Ecosim.SceneData;
using Ecosim.SceneData.Rules;
using Ecosim.SceneData.VegetationRules;
using UnityEngine;
namespace Ecosim.SceneData.Action
{
public class PurchaseLandAction : BasicAction
{
public const string XML_ELEMENT = "purchaseland";
public EditData.NotifyTileChanged OnTileChanged;
public string areaName;
public int invalidTileIconId;
public int undoTileIconId;
private EditData edit;
private Data selectedArea;
private GridTextureSettings areaGrid = null;
private Texture2D areaTex = null;
private Material areaMat = null;
private Material selectedAreaMat = null;
private MethodInfo canSelectTileMI = null;
public PurchaseLandAction (Scene scene, int id) : base(scene, id)
{
}
public PurchaseLandAction (Scene scene) : base(scene, scene.actions.lastId)
{
UserInteraction ui = new UserInteraction (this);
this.areaName = "area" + this.id.ToString ();
this.uiList.Add (ui);
}
~PurchaseLandAction ()
{
if (this.areaMat != null) {
UnityEngine.Object.Destroy (this.areaMat);
}
if (this.selectedAreaMat != null) {
UnityEngine.Object.Destroy (this.selectedAreaMat);
}
if (this.areaTex != null) {
UnityEngine.Object.Destroy (this.areaTex);
}
}
/**
* Overriden CompileScript to add constants
*/
public override bool CompileScript ()
{
Dictionary <string, string> consts = new Dictionary<string, string> ();
consts.Add ("string AREA", "\"" + areaName + "\"");
return CompileScript (consts);
}
protected override void UnlinkEcoBase ()
{
base.UnlinkEcoBase ();
canSelectTileMI = null;
}
protected override void LinkEcoBase ()
{
base.LinkEcoBase ();
if (ecoBase != null) {
canSelectTileMI = ecoBase.GetType ().GetMethod ("CanSelectTile",
BindingFlags.NonPublic | BindingFlags.Instance, null,
new Type[] { typeof(int), typeof(int), typeof(UserInteraction) }, null);
}
}
public override string GetDescription ()
{
return "Handle Purchase Land";
}
public override int GetMinUICount ()
{
return 1;
}
public override int GetMaxUICount ()
{
return 1;
}
public bool CanSelectTile (int x, int y, UserInteraction ui)
{
if (canSelectTileMI != null) {
return (bool)canSelectTileMI.Invoke (ecoBase, new object[] { x, y, ui });
}
return true;
}
public override void DoSuccession ()
{
base.DoSuccession ();
}
public override void ActionSelected (UserInteraction ui)
{
base.ActionSelected (ui);
new Ecosim.GameCtrl.GameButtons.PurchaseLandActionWindow (ui);
}
public void StartSelecting (UserInteraction ui)
{
// New selected area
if (this.selectedArea == null && this.scene.progression.HasData (this.areaName))
this.selectedArea = this.scene.progression.GetData (this.areaName);
else if (this.selectedArea == null) {
this.selectedArea = new SparseBitMap8 (this.scene);
this.scene.progression.AddData (this.areaName, this.selectedArea);
}
// Get the selectable area
Data selectableArea = new BitMap16 (this.scene);
this.scene.progression.purchasableArea.CopyTo (selectableArea);
// Remove all managed area from the purchaseable area
foreach (ValueCoordinate vc in selectableArea.EnumerateNotZero ()) {
if (this.scene.progression.managedArea.Get (vc) > 0) {
selectableArea.Set (vc, 0);
continue;
}
// Update selectable area
if (this.selectedArea.Get (vc) == 0)
this.selectedArea.Set (vc, vc.v);
}
// Get price classes count for choosing correct icons
int priceClasses = this.scene.progression.priceClasses.Count;
// Create edit data
this.edit = EditData.CreateEditData ("action", this.selectedArea, selectableArea, delegate(int x, int y, int currentVal, float strength, bool shift, bool ctrl)
{
// Show undo icon
if (shift) return 0;
// Show selected icon
return this.CanSelectTile (x,y,ui) ? selectableArea.Get (x,y) + priceClasses : this.invalidTileIconId;
},
this.areaGrid);
// Final brush
this.edit.SetFinalBrushFunction (delegate(int x, int y, int currentVal, float strength, bool shift, bool ctrl)
{
// Show default icon
if (shift) return selectableArea.Get (x,y);
// Show selected icon
return this.CanSelectTile (x,y,ui) ? selectableArea.Get (x,y) + priceClasses : -1;
});
// Set area mode selection
this.edit.SetModeAreaSelect ();
// Set tile changed handler
this.edit.AddTileChangedHandler (delegate(int x, int y, int oldV, int newV)
{
// Update
if (this.OnTileChanged != null) {
this.OnTileChanged (x,y,oldV,newV);
}
});
}
/**
* Called when player finished selecting tile
* method will create EditData instance
* ui is the user button pressed for doing this action
*/
public void FinishSelecting (UserInteraction ui, bool isCanceled)
{
// Check if not cancelled
if (!isCanceled) {
// make selection permanent
this.edit.CopyData (this.selectedArea);
// Remember the last taken measure values
// Convert selected area to managed area
int selectedTilesCount = 0;
foreach (ValueCoordinate vc in this.selectedArea.EnumerateNotZero()) {
selectedTilesCount++;
}
// Save predefined variables
scene.progression.variables [Progression.PredefinedVariables.lastMeasure.ToString()] = this.GetDescription ();
scene.progression.variables [Progression.PredefinedVariables.lastMeasureGroup.ToString()] = "Area";
scene.progression.variables [Progression.PredefinedVariables.lastMeasureCount.ToString()] = selectedTilesCount;
}
// Delete
this.edit.Delete ();
this.edit = null;
// Fire the measure taken methods
if (!isCanceled) {
scene.actions.MeasureTaken ();
}
}
public override void UpdateReferences ()
{
// Destroy references first
if (this.areaMat != null) {
UnityEngine.Object.DestroyImmediate (this.areaMat);
}
if (this.selectedAreaMat != null) {
UnityEngine.Object.DestroyImmediate (this.selectedAreaMat);
}
if (this.areaTex != null) {
UnityEngine.Object.DestroyImmediate (this.areaTex);
}
// Area grid
int gridSize = this.scene.progression.priceClasses.Count + 2;
this.areaTex = new Texture2D (gridSize * 32, gridSize * 32, TextureFormat.RGBA32, false, true);
this.areaTex.filterMode = FilterMode.Point;
this.areaTex.wrapMode = TextureWrapMode.Clamp;
this.areaGrid = new GridTextureSettings (true, 0, gridSize, areaMat, true, selectedAreaMat);
this.areaMat = new Material (EcoTerrainElements.GetMaterial ("MapGrid100"));
this.selectedAreaMat = new Material (EcoTerrainElements.GetMaterial ("ActiveMapGrid100"));
// Icons
List<Texture2D> icons = new List<Texture2D> ();
icons.Add (this.scene.assets.GetIcon (this.undoTileIconId));
foreach (Progression.PriceClass pc in this.scene.progression.priceClasses) {
icons.Add (this.scene.assets.GetIcon (pc.normalIconId));
}
foreach (Progression.PriceClass pc in this.scene.progression.priceClasses) {
icons.Add (this.scene.assets.GetIcon (pc.selectedIconId));
}
icons.Add (this.scene.assets.GetIcon (this.invalidTileIconId));
this.scene.assets.CopyTexures (icons.ToArray (), areaTex, null);
icons.Clear ();
this.areaMat.mainTexture = this.areaTex;
this.selectedAreaMat.mainTexture = this.areaTex;
this.areaGrid = new GridTextureSettings (true, 0, gridSize, this.areaMat, true, this.selectedAreaMat);
}
public static PurchaseLandAction Load (Scene scene, XmlTextReader reader)
{
int id = int.Parse (reader.GetAttribute ("id"));
PurchaseLandAction action = new PurchaseLandAction (scene, id);
action.areaName = reader.GetAttribute ("areaname");
if (string.IsNullOrEmpty (action.areaName))
action.areaName = "action" + id;
action.undoTileIconId = (!string.IsNullOrEmpty (reader.GetAttribute ("undotileid"))) ?
int.Parse (reader.GetAttribute ("undotileid")) : 0;
action.invalidTileIconId = (!string.IsNullOrEmpty (reader.GetAttribute ("invalidtileid"))) ?
int.Parse (reader.GetAttribute ("invalidtileid")) : 0;
if (!reader.IsEmptyElement) {
while (reader.Read()) {
XmlNodeType nType = reader.NodeType;
if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == UserInteraction.XML_ELEMENT)) {
action.uiList.Add (UserInteraction.Load (action, reader));
} else if ((nType == XmlNodeType.EndElement) && (reader.Name.ToLower () == XML_ELEMENT)) {
break;
}
}
}
return action;
}
public override void Save (XmlTextWriter writer)
{
writer.WriteStartElement (XML_ELEMENT);
writer.WriteAttributeString ("id", this.id.ToString ());
writer.WriteAttributeString ("areaname", this.areaName.ToString ());
writer.WriteAttributeString ("undotileid", this.undoTileIconId.ToString ());
writer.WriteAttributeString ("invalidtileid", this.invalidTileIconId.ToString ());
foreach (UserInteraction ui in this.uiList) {
ui.Save (writer);
}
writer.WriteEndElement ();
}
}
}
| |
using UnityEngine;
public class flowcontrol : MonoBehaviour
{
float bpminterval = 0.42f;
float lastTime;
float timePassedSinceIntro;
const float introLength = 2.8502f;
bool isLoopPlaying = false;
float loopTimer;
AudioSource audioLoop;
public Vector4 f0 = new Vector4(243.9028f, 4.383772f, 27.37137f, 300f);
public Vector4 f1 = new Vector4(305.5934f, 30.0f, 2.461121f, 6.0f);
public bool frequencyChange = true;
public bool setupChange = true;
public bool gainChange = true;
public bool stepControlled = true; //else: random controlled
Vector4 innerColorDestination;
Vector4 innerColor;
Vector4 bgColorDestination;
Vector4 bgColor;
Color alphaColor = Color.black;
public bool controlsOthers = false;
void Awake()
{
innerColorDestination = GameObject.Find("inner").renderer.material.GetColor("diffuse_color");
bgColorDestination = GameObject.Find("background").renderer.material.GetColor("diffuse_color");
GameObject.Find("fakealpha").renderer.material.SetColor("_Color", Color.black);
currentMix = this.renderer.material.GetFloat("ns_mix");
currentPhaseMixX = this.renderer.material.GetFloat("shift_x");
currentPhaseMixY = this.renderer.material.GetFloat("shift_y");
blurObject = GameObject.Find("Main Camera").GetComponent<BlurEffect>();
blurState = blurObject.enabled;
}
void Start ()
{
lastTime = Time.time;
GameObject.Find("apintro").audio.Play();
audioLoop = GameObject.Find("ap").audio;
timePassedSinceIntro = Time.time;
}
const float range = 25;
float step = 0.1f;
float stepTimer;
const float stepTimerMax = 10.0f;
public bool isBackgroundSpecialSupreme = false;
float currentMix;
float mixStep = 0.1f;
float currentPhaseMixX;
float currentPhaseMixY;
float phaseMixStepX = 0.1f;
float phaseMixStepY = 0.1f;
int bpmCounter = 0;
int bpmPatternMode = 0;
bool isVortexActivated = false;
float vortexStep = 0.01f;
bool isTwirlActivated = false;
bool doTwirlOneTimer = true;
float twirlStep = 0.01f;
bool isBlurActivated = false;
BlurEffect blurObject;
bool blurState;
void Update ()
{
// uncomment for tinting
//innerColor = Vector4.Lerp(Color.black, innerColorDestination, Time.deltaTime * 0.05f);
//GameObject.Find("inner").renderer.material.SetColor("diffuse_color", innerColor);
//bgColor = Vector4.Lerp(Color.black, bgColorDestination, Time.deltaTime * 0.05f);
//GameObject.Find("background").renderer.material.SetColor("diffuse_color", bgColor);
alphaColor.a -= 0.0015f;
GameObject.Find("fakealpha").renderer.material.SetColor("_Color", alphaColor);
if (Time.time - timePassedSinceIntro > introLength
&& !isLoopPlaying)
{
audioLoop.Play();
isLoopPlaying = true;
loopTimer = Time.time;
}
if(isLoopPlaying)
{
if (controlsOthers)
{
if (bpmCounter > 55)
{
isVortexActivated = true;
}
if (Time.time - loopTimer > 24*2)
{
if (!isTwirlActivated)
{
isBlurActivated = true;
//UGLY:
GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle = Mathf.Lerp(GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle, 40, Time.deltaTime*2);
if (GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle > 30)
{
isTwirlActivated = true;
isBlurActivated = false;
blurState = false;
blurObject.enabled = blurState;
}
}
}
//if (bpmCounter % 49 == 0)
if (Time.time - loopTimer > 24.2 * 3)
{
//print("twirl deactivated");
isTwirlActivated = false;
}
//if (bpmCounter > 55 * 1
// && bpmCounter < 55 * 1 + 10)
if (Time.time - loopTimer > 24)
{
if (!isTwirlActivated)
{
isBlurActivated = true;
GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle = Mathf.Lerp(GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle, 40, Time.deltaTime * 2);
if (GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle > 30)
{
// doTwirlOneTimer = false;
isTwirlActivated = true;
isBlurActivated = false;
blurState = false;
blurObject.enabled = blurState;
}
}
}
if (isTwirlActivated)
{
//UGLY:
GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle += twirlStep;
if (GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle > 30
|| GameObject.Find("Main Camera").GetComponent<TwirlEffect>().angle < -30)
twirlStep *= -1;
}
}
if (Time.time - lastTime > bpminterval)
{
bpmCounter++;
lastTime = Time.time;
if (controlsOthers)
{
if (isBlurActivated)
{
//print("toggle blur");
blurState = !blurState;
blurObject.enabled = blurState;
}
}
if (isBackgroundSpecialSupreme)
{
if (Time.time - loopTimer < 10)
{
if ((Time.time - loopTimer) % 0.3f >= 0 &&
(Time.time - loopTimer) % 0.4f <= 1)
{
//print("bpmCounter % 4 = " + bpmCounter % 4);
if (bpmPatternMode == 0)
bpmPatternMode = 1;
else if (bpmPatternMode == 1)
bpmPatternMode = 0;
else if (bpmPatternMode == 2)
{
bpmPatternMode = 0;
currentMix = 0;
this.renderer.material.SetFloat("ns_mix", currentMix);
}
}
if (bpmCounter % 8 == 0)
{
//print("flash mode");
bpmPatternMode = 2;
}
}
else
{
if (bpmCounter % 4 == 0)
{
//print("bpmCounter % 4 = " + bpmCounter % 4);
if (bpmPatternMode == 0)
bpmPatternMode = 1;
else if (bpmPatternMode == 1)
bpmPatternMode = 0;
else if (bpmPatternMode == 2)
{
bpmPatternMode = 0;
currentMix = 0;
this.renderer.material.SetFloat("ns_mix", currentMix);
}
}
if (bpmCounter % 16 == 0)
{
//print("flash mode");
bpmPatternMode = 2;
}
}
if (bpmCounter % 32 == 0)
{
//print("bpm 32");
phaseMixStepX *= -1.0f;
phaseMixStepY *= -1.0f;
}
if (bpmPatternMode == 0)
{
//print("pattern 0");
currentPhaseMixX += phaseMixStepX;
this.renderer.material.SetFloat("shift_x", currentPhaseMixX);
}
else if (bpmPatternMode == 1)
{
//print("pattern 1");
currentPhaseMixY += phaseMixStepY;
this.renderer.material.SetFloat("shift_y", currentPhaseMixY);
}
else if (bpmPatternMode == 2)
{
if(currentMix == 1)
currentMix = 0;
else if (currentMix == 0)
currentMix = 20;
this.renderer.material.SetFloat("ns_mix", currentMix);
}
}
else
{
this.renderer.material.SetFloat("ns_mix", Random.Range(10, 50));
this.renderer.material.SetFloat("shift_x", Random.Range(10, 50));
this.renderer.material.SetFloat("shift_y", Random.Range(10, 50));
}
if (stepControlled)
{
if (Time.time - stepTimer > stepTimerMax)
{
stepTimer = Time.time;
step *= -1;
}
if (frequencyChange)
{
f0.x += step;
f0.y += step;
//f1.x += Random.Range(range, range);
//f1.y += Random.Range(-range, range);
}
if (setupChange)
{
f0.z += step;
//f1.z += Random.Range(-range, range);
}
if (gainChange)
{
f0.w += step;
//f1.w += Random.Range(-range, range);
}
}
else
{
//random
if (frequencyChange)
{
f0.x += Random.Range(-range, range);
f0.y += Random.Range(-range, range);
//f1.x += Random.Range(range, range);
//f1.y += Random.Range(-range, range);
}
if (setupChange)
{
f0.z += Random.Range(-range, range);
//f1.z += Random.Range(-range, range);
}
if (gainChange)
{
f0.w += Random.Range(-range, range);
//f1.w += Random.Range(-range, range);
}
}
this.renderer.material.SetVector("freq_0", f0);
this.renderer.material.SetVector("freq_1", f1);
}
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Cryptography;
using System.Threading;
using Belikov.GenuineChannels.BufferPooling;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.Security.ZeroProofAuthorization
{
/// <summary>
/// Implements basic functionality for Zero Proof Authorization Security Sessions.
/// </summary>
public abstract class SecuritySession_BaseZpaSession : SecuritySession
{
/// <summary>
/// Constructs an instance of the SecuritySession_BaseZpaSession class.
/// </summary>
/// <param name="name">Name of the SecuritySession being created.</param>
/// <param name="remote">The remote host.</param>
/// <param name="zpaFeatureFlags">The requested features.</param>
public SecuritySession_BaseZpaSession(string name, HostInformation remote, ZpaFeatureFlags zpaFeatureFlags)
: base(name, remote)
{
this.ZpaFeatureFlags = zpaFeatureFlags;
}
/// <summary>
/// The symmetric algorithm being used for encryption.
/// </summary>
public SymmetricAlgorithm SymmetricAlgorithm;
/// <summary>
/// Cryptographic encryptor.
/// </summary>
private ICryptoTransform _encryptor;
/// <summary>
/// Cryptographic decryptor.
/// </summary>
private ICryptoTransform _decryptor;
/// <summary>
/// The hash algorithm.
/// </summary>
public KeyedHashAlgorithm KeyedHashAlgorithm;
/// <summary>
/// The salt.
/// </summary>
public byte[] Salt;
/// <summary>
/// The requested security options.
/// </summary>
public ZpaFeatureFlags ZpaFeatureFlags;
/// <summary>
/// Encrypts the message data and put a result into the specified output stream.
/// </summary>
/// <param name="input">The stream containing the serialized message.</param>
/// <param name="output">The result stream with the data being sent to the remote host.</param>
public override void Encrypt(Stream input, GenuineChunkedStream output)
{
#if DEBUG
input.Position = 0;
#endif
output.WriteByte(1);
lock (this)
{
// write encrypted content
if (this._encryptor != null)
GenuineUtility.CopyStreamToStream(new CryptoStream(new FinishReadingStream(input), this._encryptor, CryptoStreamMode.Read), output);
else
output.WriteStream(input);
if (this.KeyedHashAlgorithm != null)
{
// and write down the calculated message hash
input.Position = 0;
output.WriteBuffer(this.KeyedHashAlgorithm.ComputeHash(input), -1);
// it's in the content, reset its position
if (this._encryptor == null)
input.Position = 0;
}
}
}
/// <summary>
/// Creates and returns a stream containing decrypted data.
/// </summary>
/// <param name="input">A stream containing encrypted data.</param>
/// <returns>A stream with decrypted data.</returns>
public override Stream Decrypt(Stream input)
{
// check on view whether it's session's packet
if (input.ReadByte() == 0)
{
// continue the Security Session establishing
Stream outputStream = this.EstablishSession(input, false);
if (outputStream != null)
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.SendMessage), outputStream, false);
return null;
}
lock (this)
{
GenuineChunkedStream output = new GenuineChunkedStream(false);
byte[] sign = null;
int signSize = 0;
if (this.KeyedHashAlgorithm != null)
signSize = this.KeyedHashAlgorithm.HashSize / 8;
// decrypt the content and fetch the sign
if (this._decryptor != null)
{
CryptoStream cryptoStream = new CryptoStream(new FinishReadingStream(output), this._decryptor, CryptoStreamMode.Write);
sign = GenuineUtility.CopyStreamToStreamExceptSign(input, cryptoStream, signSize);
cryptoStream.FlushFinalBlock();
}
else
sign = GenuineUtility.CopyStreamToStreamExceptSign(input, output, signSize);
// check the sign
if (this.KeyedHashAlgorithm != null)
{
if (!ZeroProofAuthorizationUtility.CompareBuffers(sign, this.KeyedHashAlgorithm.ComputeHash(output), sign.Length))
throw GenuineExceptions.Get_Security_WrongSignature();
output.Position = 0;
}
output.ReleaseOnReadMode = true;
return output;
}
}
/// <summary>
/// Sets up all security stuff for encrypting content and checking integrity.
/// </summary>
/// <param name="password">The password.</param>
protected void SetupSecurityAlgorithms(string password)
{
lock(this)
{
if ((this.ZpaFeatureFlags & ZpaFeatureFlags.ElectronicCodebookEncryption) != 0
|| (this.ZpaFeatureFlags & ZpaFeatureFlags.CipherBlockChainingEncryption) != 0)
{
// encryption
this.SymmetricAlgorithm = Rijndael.Create();
this.SymmetricAlgorithm.Key = ZeroProofAuthorizationUtility.GeneratePasswordBasedSequence("Key" + password, this.Salt, 32);
this.SymmetricAlgorithm.IV = ZeroProofAuthorizationUtility.GeneratePasswordBasedSequence("IV" + password, this.Salt, 16);
this.SymmetricAlgorithm.Mode = (this.ZpaFeatureFlags & ZpaFeatureFlags.ElectronicCodebookEncryption) != 0 ? CipherMode.ECB : CipherMode.CBC;
this._encryptor = this.SymmetricAlgorithm.CreateEncryptor();
this._decryptor = this.SymmetricAlgorithm.CreateDecryptor();
}
// and integrity checking
if ( (this.ZpaFeatureFlags & ZpaFeatureFlags.Mac3DesCbcSigning) != 0)
this.KeyedHashAlgorithm = MACTripleDES.Create();
if ( (this.ZpaFeatureFlags & ZpaFeatureFlags.HmacSha1Signing) != 0 )
this.KeyedHashAlgorithm = HMACSHA1.Create();
if (this.KeyedHashAlgorithm != null)
this.KeyedHashAlgorithm.Key = ZeroProofAuthorizationUtility.GeneratePasswordBasedSequence("M3D" + password, this.Salt, 24);
// LOG:
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
if (binaryLogWriter != null && binaryLogWriter[LogCategory.Security] > 0 )
{
binaryLogWriter.WriteEvent(LogCategory.Security, "SecuritySession_BaseZpaSession.SetupSecurityAlgorithms",
LogMessageType.SecuritySessionKey, null, null, this.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, this,
this.Name, -1,
0, 0, 0, string.Format("Zero Proof Authorization Flags: {0} Encryption: {1} Data Integrity: {2}", Enum.Format(typeof(ZpaFeatureFlags), this.ZpaFeatureFlags, "g"), this.SymmetricAlgorithm == null ? "No" : this.SymmetricAlgorithm.GetType().ToString(), this.KeyedHashAlgorithm == null ? "No" : this.KeyedHashAlgorithm.GetType().ToString()),
null, null, null,
"Security Session security information is initialized.");
}
}
}
}
}
| |
#region BSD License
/*
Copyright (c) 2004 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
[Target("monodev")]
public class MonoDevelopTarget : ITarget
{
#region Fields
private Kernel m_Kernel;
#endregion
#region Private Methods
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
{
tmpPath = Helper.NormalizePath(tmpPath);
}
else
{
tmpPath = Helper.NormalizePath("./" + tmpPath);
}
return tmpPath;
}
private static string BuildReference(SolutionNode solution, ReferenceNode refr)
{
string ret = "<ProjectReference type=\"";
if(solution.ProjectsTable.ContainsKey(refr.Name))
{
ret += "Project\"";
ret += " localcopy=\"" + refr.LocalCopy.ToString() + "\" refto=\"" + refr.Name + "\" />";
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if(refr.Path != null || fileRef != null)
{
ret += "Assembly\" refto=\"";
string finalPath = (refr.Path != null) ? Helper.MakeFilePath(refr.Path, refr.Name, "dll") : fileRef;
ret += finalPath;
ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
return ret;
}
ret += "Gac\"";
ret += " localcopy=\"" + refr.LocalCopy.ToString() + "\"";
ret += " refto=\"";
try
{
/*
Day changed to 28 Mar 2007
...
08:09 < cj> is there anything that replaces Assembly.LoadFromPartialName() ?
08:09 < jonp> no
08:10 < jonp> in their infinite wisdom [sic], microsoft decided that the
ability to load any assembly version by-name was an inherently
bad idea
08:11 < cj> I'm thinking of a bunch of four-letter words right now...
08:11 < cj> security through making it difficult for the developer!!!
08:12 < jonp> just use the Obsolete API
08:12 < jonp> it should still work
08:12 < cj> alrighty.
08:12 < jonp> you just get warnings when using it
*/
Assembly assem = Assembly.LoadWithPartialName(refr.Name);
ret += assem.FullName;
//ret += refr.Name;
}
catch (System.NullReferenceException e)
{
e.ToString();
ret += refr.Name;
}
ret += "\" />";
}
return ret;
}
private static string FindFileReference(string refName, ProjectNode project)
{
foreach(ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if(File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GenerateXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if( conf == null )
{
throw new ArgumentNullException("conf");
}
if( project == null )
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
{
return "False";
}
return "True";
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string csComp = "Mcs";
string netRuntime = "Mono";
if(project.Runtime == ClrRuntime.Microsoft)
{
csComp = "Csc";
netRuntime = "MsNet";
}
string projFile = Helper.MakeFilePath(project.FullPath, project.Name, "mdp");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
using(ss)
{
ss.WriteLine(
"<Project name=\"{0}\" description=\"\" standardNamespace=\"{1}\" newfilesearch=\"None\" enableviewstate=\"True\" fileversion=\"2.0\" language=\"C#\" clr-version=\"Net_2_0\" ctype=\"DotNetProject\">",
project.Name,
project.RootNamespace
);
int count = 0;
ss.WriteLine(" <Configurations active=\"{0}\">", solution.ActiveConfig);
foreach(ConfigurationNode conf in project.Configurations)
{
ss.WriteLine(" <Configuration name=\"{0}\" ctype=\"DotNetProjectConfiguration\">", conf.Name);
ss.Write(" <Output");
ss.Write(" directory=\"{0}\"", Helper.EndPath(Helper.NormalizePath(".\\" + conf.Options["OutputPath"].ToString())));
ss.Write(" assembly=\"{0}\"", project.AssemblyName);
ss.Write(" executeScript=\"{0}\"", conf.Options["RunScript"]);
//ss.Write(" executeBeforeBuild=\"{0}\"", conf.Options["PreBuildEvent"]);
//ss.Write(" executeAfterBuild=\"{0}\"", conf.Options["PostBuildEvent"]);
if (conf.Options["PreBuildEvent"] != null && conf.Options["PreBuildEvent"].ToString().Length != 0)
{
ss.Write(" executeBeforeBuild=\"{0}\"", Helper.NormalizePath(conf.Options["PreBuildEvent"].ToString()));
}
else
{
ss.Write(" executeBeforeBuild=\"{0}\"", conf.Options["PreBuildEvent"]);
}
if (conf.Options["PostBuildEvent"] != null && conf.Options["PostBuildEvent"].ToString().Length != 0)
{
ss.Write(" executeAfterBuild=\"{0}\"", Helper.NormalizePath(conf.Options["PostBuildEvent"].ToString()));
}
else
{
ss.Write(" executeAfterBuild=\"{0}\"", conf.Options["PostBuildEvent"]);
}
ss.Write(" executeBeforeBuildArguments=\"{0}\"", conf.Options["PreBuildEventArgs"]);
ss.Write(" executeAfterBuildArguments=\"{0}\"", conf.Options["PreBuildEventArgs"]);
ss.WriteLine(" />");
ss.Write(" <Build");
ss.Write(" debugmode=\"True\"");
if (project.Type == ProjectType.WinExe)
{
ss.Write(" target=\"{0}\"", ProjectType.Exe.ToString());
}
else
{
ss.Write(" target=\"{0}\"", project.Type);
}
ss.WriteLine(" />");
ss.Write(" <Execution");
ss.Write(" runwithwarnings=\"{0}\"", !conf.Options.WarningsAsErrors);
ss.Write(" consolepause=\"True\"");
ss.Write(" runtime=\"{0}\"", netRuntime);
ss.Write(" clr-version=\"Net_2_0\"");
ss.WriteLine(" />");
ss.Write(" <CodeGeneration");
ss.Write(" compiler=\"{0}\"", csComp);
ss.Write(" warninglevel=\"{0}\"", conf.Options["WarningLevel"]);
ss.Write(" nowarn=\"{0}\"", conf.Options["SuppressWarnings"]);
ss.Write(" includedebuginformation=\"{0}\"", conf.Options["DebugInformation"]);
ss.Write(" optimize=\"{0}\"", conf.Options["OptimizeCode"]);
ss.Write(" unsafecodeallowed=\"{0}\"", conf.Options["AllowUnsafe"]);
ss.Write(" generateoverflowchecks=\"{0}\"", conf.Options["CheckUnderflowOverflow"]);
ss.Write(" mainclass=\"{0}\"", project.StartupObject);
ss.Write(" target=\"{0}\"", project.Type);
ss.Write(" definesymbols=\"{0}\"", conf.Options["CompilerDefines"]);
ss.Write(" generatexmldocumentation=\"{0}\"", GenerateXmlDocFile(project, conf));
ss.Write(" win32Icon=\"{0}\"", project.AppIcon);
ss.Write(" ctype=\"CSharpCompilerParameters\"");
ss.WriteLine(" />");
ss.WriteLine(" </Configuration>");
count++;
}
ss.WriteLine(" </Configurations>");
ss.Write(" <DeploymentInformation");
ss.Write(" target=\"\"");
ss.Write(" script=\"\"");
ss.Write(" strategy=\"File\"");
ss.WriteLine(">");
ss.WriteLine(" <excludeFiles />");
ss.WriteLine(" </DeploymentInformation>");
ss.WriteLine(" <Contents>");
foreach(string file in project.Files)
{
string buildAction = "Compile";
switch(project.Files.GetBuildAction(file))
{
case BuildAction.None:
buildAction = "Nothing";
break;
case BuildAction.Content:
buildAction = "Exclude";
break;
case BuildAction.EmbeddedResource:
buildAction = "EmbedAsResource";
break;
default:
buildAction = "Compile";
break;
}
// Sort of a hack, we try and resolve the path and make it relative, if we can.
string filePath = PrependPath(file);
ss.WriteLine(" <File name=\"{0}\" subtype=\"Code\" buildaction=\"{1}\" dependson=\"\" data=\"\" />", filePath, buildAction);
}
ss.WriteLine(" </Contents>");
ss.WriteLine(" <References>");
foreach(ReferenceNode refr in project.References)
{
ss.WriteLine(" {0}", BuildReference(solution, refr));
}
ss.WriteLine(" </References>");
ss.WriteLine("</Project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating MonoDevelop combine and project files");
foreach(ProjectNode project in solution.Projects)
{
if(m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "mds");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
int count = 0;
using(ss)
{
ss.WriteLine("<Combine name=\"{0}\" fileversion=\"2.0\" description=\"\">", solution.Name);
count = 0;
foreach(ConfigurationNode conf in solution.Configurations)
{
if(count == 0)
{
ss.WriteLine(" <Configurations active=\"{0}\">", conf.Name);
}
ss.WriteLine(" <Configuration name=\"{0}\" ctype=\"CombineConfiguration\">", conf.Name);
foreach(ProjectNode project in solution.Projects)
{
ss.WriteLine(" <Entry configuration=\"{1}\" build=\"True\" name=\"{0}\" />", project.Name, conf.Name);
}
ss.WriteLine(" </Configuration>");
count++;
}
ss.WriteLine(" </Configurations>");
count = 0;
foreach(ProjectNode project in solution.Projects)
{
if(count == 0)
ss.WriteLine(" <StartMode startupentry=\"{0}\" single=\"True\">", project.Name);
ss.WriteLine(" <Execute type=\"None\" entry=\"{0}\" />", project.Name);
count++;
}
ss.WriteLine(" </StartMode>");
ss.WriteLine(" <Entries>");
foreach(ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.WriteLine(" <Entry filename=\"{0}\" />",
Helper.MakeFilePath(path, project.Name, "mdp"));
}
ss.WriteLine(" </Entries>");
ss.WriteLine("</Combine>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, "mdp");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning MonoDevelop combine and project files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "mds");
Helper.DeleteIfExists(slnFile);
foreach(ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if( kern == null )
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach(SolutionNode solution in kern.Solutions)
{
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if( kern == null )
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach(SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "sharpdev";
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using pltkw3msShipping.Areas.HelpPage.ModelDescriptions;
using pltkw3msShipping.Areas.HelpPage.Models;
namespace pltkw3msShipping.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
public List<Tuple<int, double, double, double, byte, byte, byte>> VoxelizeMesh(Mesh M, Color MC, int M_ID, Vector3d Vsize, int CO, ref PointCloud VPC)
{
//{ID,X,Y,Z,R,G,B}
BoundingBox RBBox = M.GetBoundingBox(false);
//bounding box in R3 (real numbers)
BoundingBox ZBBox = RBBox_to_ZBBox(RBBox, Vsize);
//boudning box in Z3 (integer numbers) (note that they are again embedded in R3 for visualization)
List<Point3d> gridpoints = BBoxToVoxels(ZBBox, Vsize);
List<Point3d> Mesh_NearPoints = NearPoints(gridpoints, M, Vsize.Length / 2);
//A = Mesh_NearPoints
List<Tuple<int, double, double, double, byte, byte, byte>> Voxels = new List<Tuple<int, double, double, double, byte, byte, byte>>();
//{ID,X,Y,Z,R,G,B}
Line[] Intarget = null;
//int[] Facets = null;
// for each potential voxel check if it has to be included in the raster
foreach (Point3d gp in Mesh_NearPoints) {
if (CO == 26) {
Intarget = MeshTarget26_Connected(gp, Vsize);
} else if (CO == 6) {
Intarget = MeshTarget06_Connected(gp, Vsize);
} else {
RhinoApp.WriteLine("connectivity target undefined!");
}
//Line[] Intersections = Array.FindAll(Intarget, lambda => MeshLineIntersect(M, lambda));
if (Array.Exists(Intarget, lambda => MeshLineIntersect(M, lambda))) {
Voxels.Add(Tuple.Create(M_ID, gp.X, gp.Y, gp.Z, MC.R, MC.G, MC.B));
VPC.Add(gp, MC);
}
}
return Voxels;
}
public Mesh[] MeshToTriangles(Mesh M) //not necessary perhaps; just in case... a utility function
{
M.Faces.ConvertQuadsToTriangles();
Mesh[] Meshes = null;
M.Unweld(0, false);
Meshes = M.ExplodeAtUnweldedEdges();
return Meshes;
}
public BoundingBox RBBox_to_ZBBox(BoundingBox RBbox, Vector3d VSize) // converts a bounding box given in R3 to a bounding box in Z3 that is bigger than or the same size as the one given in R3
{
Point3d ZMinP = MinBoundRP_to_ZP(RBbox.Min, VSize);
Point3d ZMaxP = MaxBoundRP_to_ZP(RBbox.Max, VSize);
BoundingBox ZBBox = new BoundingBox(ZMinP, ZMaxP);
return ZBBox;
}
public Point3d RPtoZP(Point3d RPoint, Vector3d VSize) // finds the closest Z3 point to an R3 point
{
Point3d ZPOint = new Point3d((Math.Floor(RPoint.X / VSize.X) + 0.5) * VSize.X, (Math.Floor(RPoint.Y / VSize.Y) + 0.5) * VSize.Y, (Math.Floor(RPoint.Z) / VSize.Z + 0.5) * VSize.Z);
return ZPOint;
}
private Point3d MaxBoundRP_to_ZP(Point3d RPoint, Vector3d VSize) //snaps a boundingbox Maximum Corner point embedded in R3 to a point in Z3 ensuring a bounding box in Z3 that is bigger than or the same size as the bounding box in R3
{
double x = 0;double y = 0;double z = 0;
double u = 0;double v = 0;double w = 0;
double ZP_x = 0;
double ZP_y = 0;
double ZP_z = 0;
x = RPoint.X;
y = RPoint.Y;
z = RPoint.Z;
u = VSize.X;
v = VSize.Y;
w = VSize.Z;
ZP_x = Math.Ceiling(x / u) * u;
ZP_y = Math.Ceiling(y / v) * v;
ZP_z = Math.Ceiling(z / w) * w;
Point3d ZPoint = new Point3d(ZP_x, ZP_y, ZP_z);
return ZPoint;
}
private Point3d MinBoundRP_to_ZP(Point3d RPoint, Vector3d VSize) //snaps a boundingbox Minimum Corner point embedded in R3 to a point in Z3 ensuring a bounding box in Z3 that is bigger than or the same size as the bounding box in R3
{
double x = 0;double y = 0;double z = 0;
double u = 0;double v = 0;double w = 0;
double ZP_x = 0;
double ZP_y = 0;
double ZP_z = 0;
x = RPoint.X;
y = RPoint.Y;
z = RPoint.Z;
u = VSize.X;
v = VSize.Y;
w = VSize.Z;
ZP_x = Math.Floor(x / u) * u;
ZP_y = Math.Floor(y / v) * v;
ZP_z = Math.Floor(z / w) * w;
Point3d ZPoint = new Point3d(ZP_x, ZP_y, ZP_z);
return ZPoint;
}
public List<Point3d> BBoxToVoxels(BoundingBox ZBBox, Vector3d Vsize) //Creates a List of voxels that correspond to a boundingbox described in Z3 space
{
int i = 0;
int j = 0;
int k = 0;
int Imax = 0;
int Jmax = 0;
int Kmax = 0;
Imax = Convert.ToInt32(Math.Abs(ZBBox.Diagonal.X / Vsize.X) - 1);
Jmax = Convert.ToInt32(Math.Abs(ZBBox.Diagonal.Y / Vsize.Y) - 1);
Kmax = Convert.ToInt32(Math.Abs(ZBBox.Diagonal.Z / Vsize.Z) - 1);
//Dim VoxelPoints(IMax,JMax,KMax) As Point3d
List<Point3d> VoxelPoints = new List<Point3d>();
for (k = 0; k <= Kmax; k++) {
for (j = 0; j <= Jmax; j++) {
for (i = 0; i <= Imax; i++) {
Point3d RelPoint = new Point3d(i * Vsize.X, j * Vsize.Y, k * Vsize.Z);
//VoxelPoints(i, j, k) = (RelPoint + New Vector3d(ZBbox.Min) + New Vector3d(VSize(0), VSize(1), VSize(2)) * 0.5)
VoxelPoints.Add((RelPoint + new Vector3d(ZBBox.Min) + new Vector3d(Vsize[0], Vsize[1], Vsize[2]) * 0.5));
}
}
}
return VoxelPoints;
}
public Line[] MeshTarget26_Connected(Point3d VoxelPoint, Vector3d Vsize) ////makes a target for intersection with a mesh that ensures 26-connected results as proven by Samuli Laine 2013, NVIDIA Research: this is the set of a cube's diagons
{
//3D crosshair target for 26-connected results
Line[] IntersectionTarget = new Line[3];
Point3d[] Vertices = new Point3d[6];
double u = 0;
double v = 0;
double w = 0;
u = Vsize.X / 2;
v = Vsize.Y / 2;
w = Vsize.Z / 2;
Vertices[0] = VoxelPoint + new Vector3d(+u, 0, 0);
Vertices[1] = VoxelPoint + new Vector3d(0, +v, 0);
Vertices[2] = VoxelPoint + new Vector3d(0, 0, +w);
Vertices[3] = VoxelPoint + new Vector3d(-u, 0, 0);
Vertices[4] = VoxelPoint + new Vector3d(0, -v, 0);
Vertices[5] = VoxelPoint + new Vector3d(0, 0, -w);
for (int i = 0; i <= 2; i++) {
IntersectionTarget[i] = new Line(Vertices[i], Vertices[i + 3]);
}
return IntersectionTarget;
}
public Line[] MeshTarget06_Connected_Diagonal(Point3d VP, Vector3d Vsize) //makes a target for intersection with a mesh that ensures 06-connected results as proven by Samuli Laine 2013, NVIDIA Research: this is the outline wireframe of a cube
{
//cube outline target for 6-connected results
Line[] IT = new Line[12];
Point3d[] VX = new Point3d[8];
double u = 0;
double v = 0;
double w = 0;
u = Vsize.X / 2;
v = Vsize.Y / 2;
w = Vsize.Z / 2;
VX[0] = VP + new Vector3d(+u, +v, +w);VX[4] = VP + new Vector3d(-u, -v, -w);
VX[1] = VP + new Vector3d(-u, +v, +w);VX[5] = VP + new Vector3d(+u, -v, -w);
VX[2] = VP + new Vector3d(-u, -v, +w);VX[6] = VP + new Vector3d(+u, +v, -w);
VX[3] = VP + new Vector3d(+u, -v, +w);VX[7] = VP + new Vector3d(-u, +v, -w);
//diagonals
IT[00] = new Line(VX[0], VX[4]);
IT[01] = new Line(VX[1], VX[5]);
IT[02] = new Line(VX[2], VX[6]);
IT[03] = new Line(VX[3], VX[7]);
return IT;
}
public Line[] MeshTarget06_Connected(Point3d VP, Vector3d Vsize) //makes a target for intersection with a mesh that ensures 06-connected results as proven by Samuli Laine 2013, NVIDIA Research: this is the outline wireframe of a cube
{
//cube outline target for 6-connected results
Line[] IT = new Line[12];
Point3d[] VX = new Point3d[8];
double u = 0;
double v = 0;
double w = 0;
u = Vsize.X / 2;
v = Vsize.Y / 2;
w = Vsize.Z / 2;
VX[0] = VP + new Vector3d(+u, +v, +w);
VX[1] = VP + new Vector3d(-u, +v, +w);
VX[2] = VP + new Vector3d(-u, -v, +w);
VX[3] = VP + new Vector3d(+u, -v, +w);
VX[4] = VP + new Vector3d(-u, -v, -w);
VX[5] = VP + new Vector3d(+u, -v, -w);
VX[6] = VP + new Vector3d(+u, +v, -w);
VX[7] = VP + new Vector3d(-u, +v, -w);
//cube edges
IT[00] = new Line(VX[0], VX[1]);
IT[01] = new Line(VX[1], VX[2]);
IT[02] = new Line(VX[2], VX[3]);
IT[03] = new Line(VX[3], VX[0]);
IT[04] = new Line(VX[0], VX[6]);
IT[05] = new Line(VX[6], VX[5]);
IT[06] = new Line(VX[5], VX[4]);
IT[07] = new Line(VX[4], VX[7]);
IT[08] = new Line(VX[5], VX[3]);
IT[09] = new Line(VX[4], VX[2]);
IT[10] = new Line(VX[1], VX[7]);
IT[11] = new Line(VX[6], VX[7]);
return IT;
}
public List<Point3d> NearPoints(List<Point3d> x, Mesh y, double Distance) //finds the voxel centrepoints that could be relevant as to their distance towards the mesh, which is to be voxelized.
{
List<Point3d> AllPoints = x;
Point3d MP = default(Point3d);
List<Point3d> RelevantPoints = AllPoints.FindAll(lambda => y.ClosestPoint(lambda, out MP, Distance) != -1);
return RelevantPoints;
}
public List<Point3d> NearPoints(List<Point3d> x, Curve y, double Distance) //finds the voxel centrepoints that could be relevant as to their distance towards the curve, which is to be voxelized.
{
List<Point3d> AllPoints = x;
double t = 0;
List<Point3d> RelevantPoints = AllPoints.FindAll(lambda => y.ClosestPoint(lambda, out t, Distance));
return RelevantPoints;
}
public bool MeshLineIntersect(Rhino.Geometry.Mesh x, Rhino.Geometry.Line L) //this is now for reading triangles from Rhino Mesh objects; can be eventually replaced with something, which reads OBJ mesh objects
{
//List<Point3d[]> TVs = new List<Point3d[]>();
//List of Triangle Vertices
Point3d[] TV = new Point3d[3];
//Triangle Vertices
Point3f av = default(Point3f);
Point3f bv = default(Point3f);
Point3f cv = default(Point3f);
Point3f dv = default(Point3f);
//Each face As MeshFace In x.Faces
bool does = false;
for (int k = 0; k <= x.Faces.Count - 1; k++) {
x.Faces.GetFaceVertices(k, out av, out bv, out cv, out dv);
TV = new Point3d[] {new Point3d(av), new Point3d(bv),new Point3d(cv)};
//TVs.Add(TV);
if (TriangleLineIntersect(TV, x.FaceNormals[k], L)){
does = true;
}
}
return does;//TVs.Exists(Lambda => TriangleLineIntersect(Lambda, L));
}
public bool TriangleLineIntersect(Rhino.Geometry.Point3d[] Vx, Rhino.Geometry.Line L)
{
if (Vx.Length != 3) {
throw new Exception("Triangle is not valid!");
}
Point3d O = Vx[0];
Vector3d U = Vx[1] - O;
Vector3d V = Vx[2] - O;
Vector3d N = Vector3d.CrossProduct(U, V);
//plane normal
Point3d PS = L.From;//start point of the line
Point3d PE = L.To; //end point of the line
double Nomin = ((O - PS) * N);
//operator * for dot product
double Denom = N * (PE - PS);
// only if the line is not paralell to the plane containing triangle T
if (Denom != 0) {
double alpha = Nomin / Denom;
// parameter along the line where it intersects the plane in question, only if not paralell to the plane
Point3d P = PS + alpha * (PE - PS);
//L.PointAt(alpha) '
Vector3d W = P - O;
double UU = U * U;
double VV = V * V;
double UV = U * V;
double WU = W * U;
double WV = W * V;
double STDenom = Math.Pow(UV, 2) - UU * VV;
double s = (UV * WV - VV * WU) / STDenom;
double t = (UV * WU - UU * WV) / STDenom;
Point3d Point = O + s * U + t * V;
if (s >= 0 && t >= 0 && s + t <= 1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public bool TriangleLineIntersect(Rhino.Geometry.Point3d[] Vx, Rhino.Geometry.Vector3d Normal, Rhino.Geometry.Line L)
{
if (Vx.Length != 3) {
throw new Exception("Triangle is not valid!");
}
Point3d O = Vx[0];
Vector3d U = Vx[1] - O;
Vector3d V = Vx[2] - O;
Vector3d N = Normal;//Vector3d.CrossProduct(U, V);
//plane normal
Point3d PS = L.From;//start point of the line
Point3d PE = L.To; //end point of the line
double Nomin = ((O - PS) * N);
//operator * for dot product
double Denom = N * (PE - PS);
// only if the line is not paralell to the plane containing triangle T
if (Denom != 0) {
double alpha = Nomin / Denom;
// parameter along the line where it intersects the plane in question, only if not paralell to the plane
Point3d P = PS + alpha * (PE - PS);
//L.PointAt(alpha) '
Vector3d W = P - O;
double UU = U * U;
double VV = V * V;
double UV = U * V;
double WU = W * U;
double WV = W * V;
double STDenom = Math.Pow(UV, 2) - UU * VV;
double s = (UV * WV - VV * WU) / STDenom;
double t = (UV * WU - UU * WV) / STDenom;
Point3d Point = O + s * U + t * V;
if (s >= 0 & t >= 0 & s + t <= 1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Threading.Tasks;
using static Csla.Analyzers.Extensions.IMethodSymbolExtensions;
namespace Csla.Analyzers.Tests.Extensions
{
[TestClass]
public sealed class IMethodSymbolExtensionsTests
{
private const string AMethod = nameof(AMethod);
private const string DP_Create = nameof(DP_Create);
private const string DP_Fetch = nameof(DP_Fetch);
private const string DP_Insert = nameof(DP_Insert);
private const string DP_Update = nameof(DP_Update);
private const string DP_Delete = nameof(DP_Delete);
private const string DP_DeleteSelf = nameof(DP_DeleteSelf);
private const string DP_Execute = nameof(DP_Execute);
private const string C_Create = nameof(C_Create);
private const string C_Fetch = nameof(C_Fetch);
private const string C_Insert = nameof(C_Insert);
private const string C_Update = nameof(C_Update);
private const string C_DeleteSelf = nameof(C_DeleteSelf);
private const string C_Execute = nameof(C_Execute);
private static readonly string DataPortalOperationCode =
$@"using Csla;
namespace Csla.Analyzers.Tests.Targets.IMethodSymbolExtensionsTests
{{
public class DataPortalOperations
{{
public void {AMethod} () {{ }}
public void {CslaMemberConstants.Operations.DataPortalCreate}() {{ }}
public void {CslaMemberConstants.Operations.DataPortalFetch}() {{ }}
public void {CslaMemberConstants.Operations.DataPortalInsert}() {{ }}
public void {CslaMemberConstants.Operations.DataPortalUpdate}() {{ }}
public void {CslaMemberConstants.Operations.DataPortalDelete}() {{ }}
public void {CslaMemberConstants.Operations.DataPortalDeleteSelf}() {{ }}
public void {CslaMemberConstants.Operations.DataPortalExecute}() {{ }}
public void {CslaMemberConstants.Operations.ChildCreate}() {{ }}
public void {CslaMemberConstants.Operations.ChildFetch}() {{ }}
public void {CslaMemberConstants.Operations.ChildInsert}() {{ }}
public void {CslaMemberConstants.Operations.ChildUpdate}() {{ }}
public void {CslaMemberConstants.Operations.ChildDeleteSelf}() {{ }}
public void {CslaMemberConstants.Operations.ChildExecute}() {{ }}
[Create] public void {DP_Create}() {{ }}
[Fetch] public void {DP_Fetch}() {{ }}
[Insert] public void {DP_Insert}() {{ }}
[Update] public void {DP_Update}() {{ }}
[Delete] public void {DP_Delete}() {{ }}
[DeleteSelf] public void {DP_DeleteSelf}() {{ }}
[Execute] public void {DP_Execute}() {{ }}
[CreateChild] public void {C_Create}() {{ }}
[FetchChild] public void {C_Fetch}() {{ }}
[InsertChild] public void {C_Insert}() {{ }}
[UpdateChild] public void {C_Update}() {{ }}
[DeleteSelfChild] public void {C_DeleteSelf}() {{ }}
[ExecuteChild] public void {C_Execute}() {{ }}
}}
}}";
private const string PropertyInfoManagementCode =
@"namespace Csla.Analyzers.Tests.Targets.IMethodSymbolExtensionsTests
{
public class PropertyInfoManagementMethods
: BusinessBase<PropertyInfoManagementMethods>
{
public void AMethod()
{
this.GetProperty(null);
this.GetPropertyConvert<string, string>(null, null);
this.SetProperty(null, null);
this.SetPropertyConvert<string, string>(null, null);
this.LoadProperty(null, null);
this.LoadPropertyAsync<string>(null, null);
this.LoadPropertyConvert<string, string>(null, null);
this.LoadPropertyMarkDirty(null, null);
this.ReadProperty(null);
this.ReadPropertyConvert<string, string>(null);
this.LazyGetProperty<string>(null, null);
this.LazyGetPropertyAsync<string>(null, null);
this.LazyReadProperty<string>(null, null);
this.LazyReadPropertyAsync<string>(null, null);
this.Something();
}
private void Something() { }
}
}";
[TestMethod]
public void IsPropertyInfoManagementMethodWhenSymbolIsNull()
{
Assert.IsFalse((null as IMethodSymbol).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForMethodThatIsNotAPropertyInfoManagementMethod()
{
Assert.IsFalse((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, "Something")).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForSetProperty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.SetProperty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForSetPropertyConvert()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.SetPropertyConvert)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForGetProperty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.GetProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.GetProperty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForGetPropertyConvert()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.GetPropertyConvert)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.GetPropertyConvert)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLazyGetProperty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetProperty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLazyGetPropertyAsync()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetPropertyAsync)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyGetPropertyAsync)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLazyReadProperty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadProperty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLazyReadPropertyAsync()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadPropertyAsync)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LazyReadPropertyAsync)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLoadPropertyAsync()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyAsync)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyAsync)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLoadPropertyMarkDirty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyMarkDirty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyMarkDirty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForReadProperty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadProperty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForReadPropertyConvert()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadPropertyConvert)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadPropertyConvert)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.ReadPropertyConvert)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLoadProperty()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadProperty)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadProperty)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public async Task IsPropertyInfoManagementMethodForLoadPropertyConvert()
{
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyConvert)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyConvert)).IsPropertyInfoManagementMethod());
Assert.IsTrue((await GetMethodReferenceSymbolAsync(
PropertyInfoManagementCode, CslaMemberConstants.Properties.LoadPropertyConvert)).IsPropertyInfoManagementMethod());
}
[TestMethod]
public void IsDataPortalOperationWhenSymbolIsNull() =>
Assert.IsFalse((null as IMethodSymbol).IsDataPortalOperation());
[TestMethod]
public void IsRootDataPortalOperationWhenSymbolIsNull() =>
Assert.IsFalse((null as IMethodSymbol).IsRootDataPortalOperation());
[TestMethod]
public void IsChildDataPortalOperationWhenSymbolIsNull() =>
Assert.IsFalse((null as IMethodSymbol).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForMethodThatIsNotADataPortalOperation() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, AMethod)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForMethodThatIsNotADataPortalOperation() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, AMethod)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForMethodThatIsNotADataPortalOperation() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, AMethod)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalCreate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalCreate)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalCreate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalCreate)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalCreate() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalCreate)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalCreateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Create)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalCreateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Create)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalCreateWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Create)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalFetch() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalFetch)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalFetch() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalFetch)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalFetch() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalFetch)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalFetchWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Fetch)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalFetchWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Fetch)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalFetchWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Fetch)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalInsert() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalInsert)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalInsert() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalInsert)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalInsert() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalInsert)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalInsertWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Insert)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalInsertWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Insert)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalInsertWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Insert)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalUpdate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalUpdate)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalUpdate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalUpdate)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalUpdate() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalUpdate)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalUpdateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Update)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalUpdateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Update)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalUpdateWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Update)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalDelete() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDelete)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalDelete() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDelete)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalDelete() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDelete)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalDeleteWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Delete)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalDeleteWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Delete)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalDeleteWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Delete)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalDeleteSelf() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDeleteSelf)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalDeleteSelf() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDeleteSelf)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalDeleteSelf() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalDeleteSelf)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalDeleteSelfWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_DeleteSelf)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalDeleteSelfWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_DeleteSelf)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalDeleteSelfWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_DeleteSelf)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalExecute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalExecute)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalExecute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalExecute)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalExecute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.DataPortalExecute)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForDataPortalExecuteWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Execute)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForDataPortalExecuteWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Execute)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForDataPortalExecuteWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, DP_Execute)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildCreate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildCreate)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildCreate() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildCreate)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildCreate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildCreate)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildCreateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Create)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildCreateWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Create)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildCreateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Create)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildFetch() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildFetch)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildFetch() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildFetch)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildFetch() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildFetch)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildFetchWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Fetch)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildFetchWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Fetch)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildFetchWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Fetch)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildInsert() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildInsert)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildInsert() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildInsert)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildInsert() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildInsert)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildInsertWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Insert)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildInsertWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Insert)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildInsertWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Insert)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildUpdate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildUpdate)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildUpdate() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildUpdate)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildUpdate() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildUpdate)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildUpdateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Update)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildUpdateWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Update)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildUpdateWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Update)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildDeleteSelf() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildDeleteSelf)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildDeleteSelf() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildDeleteSelf)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildDeleteSelf() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildDeleteSelf)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildExecute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildExecute)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildExecute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildExecute)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildExecute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, CslaMemberConstants.Operations.ChildExecute)).IsChildDataPortalOperation());
[TestMethod]
public async Task IsDataPortalOperationForChildExecuteWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Execute)).IsDataPortalOperation());
[TestMethod]
public async Task IsRootDataPortalOperationForChildExecuteWithAttribute() =>
Assert.IsFalse((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Execute)).IsRootDataPortalOperation());
[TestMethod]
public async Task IsChildDataPortalOperationForChildExecuteWithAttribute() =>
Assert.IsTrue((await GetMethodSymbolAsync(
DataPortalOperationCode, C_Execute)).IsChildDataPortalOperation());
private static async Task<(SemanticModel, SyntaxNode)> ParseFileAsync(string code)
{
var tree = CSharpSyntaxTree.ParseText(code);
var compilation = CSharpCompilation.Create(
Guid.NewGuid().ToString("N"),
syntaxTrees: new[] { tree },
references: AssemblyReferences.GetMetadataReferences(new[]
{
typeof(object).Assembly,
typeof(BusinessBase<>).Assembly,
typeof(Attribute).Assembly
}));
return (compilation.GetSemanticModel(tree), await tree.GetRootAsync().ConfigureAwait(false));
}
private async Task<IMethodSymbol> GetMethodSymbolAsync(string code, string name)
{
var (model, root) = await ParseFileAsync(code);
foreach (var method in root.DescendantNodes().OfType<MethodDeclarationSyntax>())
{
if (model.GetDeclaredSymbol(method) is IMethodSymbol methodNode && methodNode.Name == name)
{
return methodNode;
}
}
return null;
}
private async Task<IMethodSymbol> GetMethodReferenceSymbolAsync(string code, string name)
{
var (model, root) = await ParseFileAsync(code);
foreach (var invocation in root.DescendantNodes().OfType<InvocationExpressionSyntax>())
{
var symbol = model.GetSymbolInfo(invocation);
var methodSymbol = symbol.Symbol as IMethodSymbol;
if (methodSymbol?.Name == name)
{
return methodSymbol;
}
}
return null;
}
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Supported display operations for Stage.
/// </summary>
public enum StageDisplayType
{
/// <summary> No operation </summary>
None,
/// <summary> Show the stage and all portraits. </summary>
Show,
/// <summary> Hide the stage and all portraits. </summary>
Hide,
/// <summary> Swap the stage and all portraits with another stage. </summary>
Swap,
/// <summary> Move stage to the front. </summary>
MoveToFront,
/// <summary> Undim all portraits on the stage. </summary>
UndimAllPortraits,
/// <summary> Dim all non-speaking portraits on the stage. </summary>
DimNonSpeakingPortraits
}
/// <summary>
/// Controls the stage on which character portraits are displayed.
/// </summary>
[CommandInfo("Narrative",
"Control Stage",
"Controls the stage on which character portraits are displayed.")]
public class ControlStage : ControlWithDisplay<StageDisplayType>
{
[Tooltip("Stage to display characters on")]
[SerializeField] protected Stage stage;
public virtual Stage _Stage { get { return stage; } }
[Tooltip("Stage to swap with")]
[SerializeField] protected Stage replacedStage;
[Tooltip("Use Default Settings")]
[SerializeField] protected bool useDefaultSettings = true;
public virtual bool UseDefaultSettings { get { return useDefaultSettings; } }
[Tooltip("Fade Duration")]
[SerializeField] protected float fadeDuration;
[Tooltip("Wait until the tween has finished before executing the next command")]
[SerializeField] protected bool waitUntilFinished = false;
protected virtual void Show(Stage stage, bool visible)
{
float duration = (fadeDuration == 0) ? float.Epsilon : fadeDuration;
float targetAlpha = visible ? 1f : 0f;
CanvasGroup canvasGroup = stage.GetComponentInChildren<CanvasGroup>();
if (canvasGroup == null)
{
Continue();
return;
}
LeanTween.value(canvasGroup.gameObject, canvasGroup.alpha, targetAlpha, duration).setOnUpdate( (float alpha) => {
canvasGroup.alpha = alpha;
}).setOnComplete( () => {
OnComplete();
});
}
protected virtual void MoveToFront(Stage stage)
{
var activeStages = Stage.ActiveStages;
for (int i = 0; i < activeStages.Count; i++)
{
var s = activeStages[i];
if (s == stage)
{
s.PortraitCanvas.sortingOrder = 1;
}
else
{
s.PortraitCanvas.sortingOrder = 0;
}
}
}
protected virtual void UndimAllPortraits(Stage stage)
{
stage.DimPortraits = false;
var charactersOnStage = stage.CharactersOnStage;
for (int i = 0; i < charactersOnStage.Count; i++)
{
var character = charactersOnStage[i];
stage.SetDimmed(character, false);
}
}
protected virtual void DimNonSpeakingPortraits(Stage stage)
{
stage.DimPortraits = true;
}
protected virtual void OnComplete()
{
if (waitUntilFinished)
{
Continue();
}
}
#region Public members
public override void OnEnter()
{
// If no display specified, do nothing
if (IsDisplayNone(display))
{
Continue();
return;
}
// Selected "use default Portrait Stage"
if (stage == null)
{
// If no default specified, try to get any portrait stage in the scene
stage = FindObjectOfType<Stage>();
// If portrait stage does not exist, do nothing
if (stage == null)
{
Continue();
return;
}
}
// Selected "use default Portrait Stage"
if (display == StageDisplayType.Swap) // Default portrait stage selected
{
if (replacedStage == null) // If no default specified, try to get any portrait stage in the scene
{
replacedStage = GameObject.FindObjectOfType<Stage>();
}
// If portrait stage does not exist, do nothing
if (replacedStage == null)
{
Continue();
return;
}
}
// Use default settings
if (useDefaultSettings)
{
fadeDuration = stage.FadeDuration;
}
switch(display)
{
case (StageDisplayType.Show):
Show(stage, true);
break;
case (StageDisplayType.Hide):
Show(stage, false);
break;
case (StageDisplayType.Swap):
Show(stage, true);
Show(replacedStage, false);
break;
case (StageDisplayType.MoveToFront):
MoveToFront(stage);
break;
case (StageDisplayType.UndimAllPortraits):
UndimAllPortraits(stage);
break;
case (StageDisplayType.DimNonSpeakingPortraits):
DimNonSpeakingPortraits(stage);
break;
}
if (!waitUntilFinished)
{
Continue();
}
}
public override string GetSummary()
{
string displaySummary = "";
if (display != StageDisplayType.None)
{
displaySummary = StringFormatter.SplitCamelCase(display.ToString());
}
else
{
return "Error: No display selected";
}
string stageSummary = "";
if (stage != null)
{
stageSummary = " \"" + stage.name + "\"";
}
return displaySummary + stageSummary;
}
public override Color GetButtonColor()
{
return new Color32(230, 200, 250, 255);
}
public override void OnCommandAdded(Block parentBlock)
{
//Default to display type: show
display = StageDisplayType.Show;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models.Identity;
namespace Umbraco.Core.Security
{
//TODO: In v8 we need to change this to use an int? nullable TKey instead, see notes against overridden TwoFactorSignInAsync
public class BackOfficeSignInManager : SignInManager<BackOfficeIdentityUser, int>
{
private readonly ILogger _logger;
private readonly IOwinRequest _request;
public BackOfficeSignInManager(UserManager<BackOfficeIdentityUser, int> userManager, IAuthenticationManager authenticationManager, ILogger logger, IOwinRequest request)
: base(userManager, authenticationManager)
{
if (logger == null) throw new ArgumentNullException("logger");
if (request == null) throw new ArgumentNullException("request");
_logger = logger;
_request = request;
AuthenticationType = Constants.Security.BackOfficeAuthenticationType;
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(BackOfficeIdentityUser user)
{
return user.GenerateUserIdentityAsync((BackOfficeUserManager<BackOfficeIdentityUser>)UserManager);
}
public static BackOfficeSignInManager Create(IdentityFactoryOptions<BackOfficeSignInManager> options, IOwinContext context, ILogger logger)
{
return new BackOfficeSignInManager(
context.GetBackOfficeUserManager(),
context.Authentication,
logger,
context.Request);
}
/// <summary>
/// Sign in the user in using the user name and password
/// </summary>
/// <param name="userName"/><param name="password"/><param name="isPersistent"/><param name="shouldLockout"/>
/// <returns/>
public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
var result = await PasswordSignInAsyncImpl(userName, password, isPersistent, shouldLockout);
switch (result)
{
case SignInStatus.Success:
_logger.WriteCore(TraceEventType.Information, 0,
string.Format(
"User: {0} logged in from IP address {1}",
userName,
_request.RemoteIpAddress), null, null);
break;
case SignInStatus.LockedOut:
_logger.WriteCore(TraceEventType.Information, 0,
string.Format(
"Login attempt failed for username {0} from IP address {1}, the user is locked",
userName,
_request.RemoteIpAddress), null, null);
break;
case SignInStatus.RequiresVerification:
_logger.WriteCore(TraceEventType.Information, 0,
string.Format(
"Login attempt requires verification for username {0} from IP address {1}",
userName,
_request.RemoteIpAddress), null, null);
break;
case SignInStatus.Failure:
_logger.WriteCore(TraceEventType.Information, 0,
string.Format(
"Login attempt failed for username {0} from IP address {1}",
userName,
_request.RemoteIpAddress), null, null);
break;
default:
throw new ArgumentOutOfRangeException();
}
return result;
}
/// <summary>
/// Borrowed from Micorosoft's underlying sign in manager which is not flexible enough to tell it to use a different cookie type
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="isPersistent"></param>
/// <param name="shouldLockout"></param>
/// <returns></returns>
private async Task<SignInStatus> PasswordSignInAsyncImpl(string userName, string password, bool isPersistent, bool shouldLockout)
{
if (UserManager == null)
{
return SignInStatus.Failure;
}
var user = await UserManager.FindByNameAsync(userName);
//if the user is null, create an empty one which can be used for auto-linking
if (user == null)
user = BackOfficeIdentityUser.CreateNew(userName, null, GlobalSettings.DefaultUILanguage);
//check the password for the user, this will allow a developer to auto-link
//an account if they have specified an IBackOfficeUserPasswordChecker
if (await UserManager.CheckPasswordAsync(user, password))
{
//the underlying call to this will query the user by Id which IS cached!
if (await UserManager.IsLockedOutAsync(user.Id))
{
return SignInStatus.LockedOut;
}
await UserManager.ResetAccessFailedCountAsync(user.Id);
return await SignInOrTwoFactor(user, isPersistent);
}
var requestContext = _request.Context;
if (user.HasIdentity && shouldLockout)
{
// If lockout is requested, increment access failed count which might lock out the user
await UserManager.AccessFailedAsync(user.Id);
if (await UserManager.IsLockedOutAsync(user.Id))
{
//at this point we've just locked the user out after too many failed login attempts
if (requestContext != null)
{
var backofficeUserManager = requestContext.GetBackOfficeUserManager();
if (backofficeUserManager != null)
backofficeUserManager.RaiseAccountLockedEvent(user.Id);
}
return SignInStatus.LockedOut;
}
}
if (requestContext != null)
{
var backofficeUserManager = requestContext.GetBackOfficeUserManager();
if (backofficeUserManager != null)
backofficeUserManager.RaiseInvalidLoginAttemptEvent(userName);
}
return SignInStatus.Failure;
}
/// <summary>
/// Borrowed from Micorosoft's underlying sign in manager which is not flexible enough to tell it to use a different cookie type
/// </summary>
/// <param name="user"></param>
/// <param name="isPersistent"></param>
/// <returns></returns>
private async Task<SignInStatus> SignInOrTwoFactor(BackOfficeIdentityUser user, bool isPersistent)
{
var id = Convert.ToString(user.Id);
if (await UserManager.GetTwoFactorEnabledAsync(user.Id)
&& (await UserManager.GetValidTwoFactorProvidersAsync(user.Id)).Count > 0)
{
var identity = new ClaimsIdentity(Constants.Security.BackOfficeTwoFactorAuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id));
identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName));
AuthenticationManager.SignIn(identity);
return SignInStatus.RequiresVerification;
}
await SignInAsync(user, isPersistent, false);
return SignInStatus.Success;
}
/// <summary>
/// Creates a user identity and then signs the identity using the AuthenticationManager
/// </summary>
/// <param name="user"></param>
/// <param name="isPersistent"></param>
/// <param name="rememberBrowser"></param>
/// <returns></returns>
public override async Task SignInAsync(BackOfficeIdentityUser user, bool isPersistent, bool rememberBrowser)
{
var userIdentity = await CreateUserIdentityAsync(user);
// Clear any partial cookies from external or two factor partial sign ins
AuthenticationManager.SignOut(
Constants.Security.BackOfficeExternalAuthenticationType,
Constants.Security.BackOfficeTwoFactorAuthenticationType);
var nowUtc = DateTime.Now.ToUniversalTime();
if (rememberBrowser)
{
var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
AuthenticationManager.SignIn(new AuthenticationProperties()
{
IsPersistent = isPersistent,
AllowRefresh = true,
IssuedUtc = nowUtc,
ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes)
}, userIdentity, rememberBrowserIdentity);
}
else
{
AuthenticationManager.SignIn(new AuthenticationProperties()
{
IsPersistent = isPersistent,
AllowRefresh = true,
IssuedUtc = nowUtc,
ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes)
}, userIdentity);
}
//track the last login date
user.LastLoginDateUtc = DateTime.UtcNow;
if (user.AccessFailedCount > 0)
//we have successfully logged in, reset the AccessFailedCount
user.AccessFailedCount = 0;
await UserManager.UpdateAsync(user);
_logger.WriteCore(TraceEventType.Information, 0,
string.Format(
"Login attempt succeeded for username {0} from IP address {1}",
user.UserName,
_request.RemoteIpAddress), null, null);
}
/// <summary>
/// Get the user id that has been verified already or -1.
/// </summary>
/// <returns></returns>
/// <remarks>
/// Replaces the underlying call which is not flexible and doesn't support a custom cookie
/// </remarks>
public new async Task<int> GetVerifiedUserIdAsync()
{
var result = await AuthenticationManager.AuthenticateAsync(Constants.Security.BackOfficeTwoFactorAuthenticationType);
if (result != null && result.Identity != null && string.IsNullOrEmpty(result.Identity.GetUserId()) == false)
{
return ConvertIdFromString(result.Identity.GetUserId());
}
return -1;
}
/// <summary>
/// Get the username that has been verified already or null.
/// </summary>
/// <returns></returns>
public async Task<string> GetVerifiedUserNameAsync()
{
var result = await AuthenticationManager.AuthenticateAsync(Constants.Security.BackOfficeTwoFactorAuthenticationType);
if (result != null && result.Identity != null && string.IsNullOrEmpty(result.Identity.GetUserName()) == false)
{
return result.Identity.GetUserName();
}
return null;
}
/// <summary>
/// Two factor verification step
/// </summary>
/// <param name="provider"></param>
/// <param name="code"></param>
/// <param name="isPersistent"></param>
/// <param name="rememberBrowser"></param>
/// <returns></returns>
/// <remarks>
/// This is implemented because we cannot override GetVerifiedUserIdAsync and instead we have to shadow it
/// so due to this and because we are using an INT as the TKey and not an object, it can never be null. Adding to that
/// the default(int) value returned by the base class is always a valid user (i.e. the admin) so we just have to duplicate
/// all of this code to check for -1 instead.
/// </remarks>
public override async Task<SignInStatus> TwoFactorSignInAsync(string provider, string code, bool isPersistent, bool rememberBrowser)
{
var userId = await GetVerifiedUserIdAsync();
if (userId == -1)
{
return SignInStatus.Failure;
}
var user = await UserManager.FindByIdAsync(userId);
if (user == null)
{
return SignInStatus.Failure;
}
if (await UserManager.IsLockedOutAsync(user.Id))
{
return SignInStatus.LockedOut;
}
if (await UserManager.VerifyTwoFactorTokenAsync(user.Id, provider, code))
{
// When token is verified correctly, clear the access failed count used for lockout
await UserManager.ResetAccessFailedCountAsync(user.Id);
await SignInAsync(user, isPersistent, rememberBrowser);
return SignInStatus.Success;
}
// If the token is incorrect, record the failure which also may cause the user to be locked out
await UserManager.AccessFailedAsync(user.Id);
return SignInStatus.Failure;
}
/// <summary>Send a two factor code to a user</summary>
/// <param name="provider"></param>
/// <returns></returns>
/// <remarks>
/// This is implemented because we cannot override GetVerifiedUserIdAsync and instead we have to shadow it
/// so due to this and because we are using an INT as the TKey and not an object, it can never be null. Adding to that
/// the default(int) value returned by the base class is always a valid user (i.e. the admin) so we just have to duplicate
/// all of this code to check for -1 instead.
/// </remarks>
public override async Task<bool> SendTwoFactorCodeAsync(string provider)
{
var userId = await GetVerifiedUserIdAsync();
if (userId == -1)
return false;
var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider);
var identityResult = await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token);
return identityResult.Succeeded;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) Punit Todi
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Xunit;
namespace System.Data.Tests
{
public class DataTableCollectionTest : IDisposable
{
// common variables here
private DataSet[] _dataset;
private DataTable[] _tables;
public DataTableCollectionTest()
{
// setting up dataset && tables
_dataset = new DataSet[2];
_tables = new DataTable[2];
_dataset[0] = new DataSet();
_dataset[1] = new DataSet();
_tables[0] = new DataTable("Books");
_tables[0].Columns.Add("id", typeof(int));
_tables[0].Columns.Add("name", typeof(string));
_tables[0].Columns.Add("author", typeof(string));
_tables[1] = new DataTable("Category");
_tables[1].Columns.Add("id", typeof(int));
_tables[1].Columns.Add("desc", typeof(string));
}
// clean up code here
public void Dispose()
{
_dataset[0].Tables.Clear();
_dataset[1].Tables.Clear();
}
[Fact]
public void Add()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(_tables[0]);
int i, j;
i = 0;
foreach (DataTable table in tbcol)
{
Assert.Equal(_tables[i].TableName, table.TableName);
j = 0;
foreach (DataColumn column in table.Columns)
{
Assert.Equal(_tables[i].Columns[j].ColumnName, column.ColumnName);
j++;
}
i++;
}
tbcol.Add(_tables[1]);
i = 0;
foreach (DataTable table in tbcol)
{
Assert.Equal(_tables[i].TableName, table.TableName);
j = 0;
foreach (DataColumn column in table.Columns)
{
Assert.Equal(_tables[i].Columns[j].ColumnName, column.ColumnName);
j++;
}
i++;
}
}
[Fact]
public void AddException1()
{
Assert.Throws<ArgumentNullException>(() =>
{
DataTableCollection tbcol = _dataset[0].Tables;
DataTable tb = null;
tbcol.Add(tb);
});
}
[Fact]
public void AddException2()
{
AssertExtensions.Throws<ArgumentException>(null, () =>
{
/* table already exist in the collection */
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(_tables[0]);
tbcol.Add(_tables[0]);
});
}
[Fact]
public void AddException3()
{
Assert.Throws<DuplicateNameException>(() =>
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(new DataTable("SameTableName"));
tbcol.Add(new DataTable("SameTableName"));
});
}
[Fact]
public void AddException4()
{
Assert.Throws<DuplicateNameException>(() =>
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add("SameTableName");
tbcol.Add("SameTableName");
});
}
[Fact]
public void Count()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(_tables[0]);
Assert.Equal(1, tbcol.Count);
tbcol.Add(_tables[1]);
Assert.Equal(2, tbcol.Count);
}
[Fact]
public void AddRange()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Clear();
/* _tables is array of type DataTable defined in Setup */
tbcol.AddRange(_tables);
int i, j;
i = 0;
foreach (DataTable table in tbcol)
{
Assert.Equal(_tables[i].TableName, table.TableName);
j = 0;
foreach (DataColumn column in table.Columns)
{
Assert.Equal(_tables[i].Columns[j].ColumnName, column.ColumnName);
j++;
}
i++;
}
}
[Fact]
public void CanRemove()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Clear();
/* _tables is array of DataTables defined in Setup */
tbcol.AddRange(_tables);
DataTable tbl = null;
/* checking for a recently input table, expecting true */
Assert.Equal(true, tbcol.CanRemove(_tables[0]));
/* trying to check with a null reference, expecting false */
Assert.Equal(false, tbcol.CanRemove(tbl));
/* trying to check with a table that does not exist in collection, expecting false */
Assert.Equal(false, tbcol.CanRemove(new DataTable("newTable")));
}
[Fact]
public void Remove()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Clear();
/* _tables is array of DataTables defined in Setup */
tbcol.AddRange(_tables);
/* removing a recently added table */
int count = tbcol.Count;
tbcol.Remove(_tables[0]);
Assert.Equal(count - 1, tbcol.Count);
DataTable tbl = null;
/* removing a null reference. must generate an Exception */
try
{
tbcol.Remove(tbl);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentNullException), e.GetType());
}
/* removing a table that is not there in collection */
try
{
tbcol.Remove(new DataTable("newTable"));
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void Clear()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(_tables[0]);
tbcol.Clear();
Assert.Equal(0, tbcol.Count);
tbcol.AddRange(new DataTable[] { _tables[0], _tables[1] });
tbcol.Clear();
Assert.Equal(0, tbcol.Count);
}
[Fact]
public void Contains()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Clear();
/* _tables is array of DataTables defined in Setup */
tbcol.AddRange(_tables);
string tblname = "";
/* checking for a recently input table, expecting true */
Assert.Equal(true, tbcol.Contains(_tables[0].TableName));
/* trying to check with an empty string, expecting false */
Assert.Equal(false, tbcol.Contains(tblname));
/* trying to check for a table that donot exist, expecting false */
Assert.Equal(false, tbcol.Contains("InvalidTableName"));
}
[Fact]
public void CopyTo()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add("Table1");
tbcol.Add("Table2");
tbcol.Add("Table3");
tbcol.Add("Table4");
DataTable[] array = new DataTable[4];
/* copying to the beginning of the array */
tbcol.CopyTo(array, 0);
Assert.Equal(4, array.Length);
Assert.Equal("Table1", array[0].TableName);
Assert.Equal("Table2", array[1].TableName);
Assert.Equal("Table3", array[2].TableName);
Assert.Equal("Table4", array[3].TableName);
/* copying with in an array */
DataTable[] array1 = new DataTable[6];
tbcol.CopyTo(array1, 2);
Assert.Equal(null, array1[0]);
Assert.Equal(null, array1[1]);
Assert.Equal("Table1", array1[2].TableName);
Assert.Equal("Table2", array1[3].TableName);
Assert.Equal("Table3", array1[4].TableName);
Assert.Equal("Table4", array1[5].TableName);
}
[Fact]
public void Equals()
{
DataTableCollection tbcol1 = _dataset[0].Tables;
DataTableCollection tbcol2 = _dataset[1].Tables;
DataTableCollection tbcol3;
tbcol1.Add(_tables[0]);
tbcol2.Add(_tables[1]);
tbcol3 = tbcol1;
Assert.Equal(true, tbcol1.Equals(tbcol1));
Assert.Equal(true, tbcol1.Equals(tbcol3));
Assert.Equal(true, tbcol3.Equals(tbcol1));
Assert.Equal(false, tbcol1.Equals(tbcol2));
Assert.Equal(false, tbcol2.Equals(tbcol1));
Assert.Equal(true, object.Equals(tbcol1, tbcol3));
Assert.Equal(true, object.Equals(tbcol1, tbcol1));
Assert.Equal(false, object.Equals(tbcol1, tbcol2));
}
[Fact]
public void IndexOf()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(_tables[0]);
tbcol.Add("table1");
tbcol.Add("table2");
Assert.Equal(0, tbcol.IndexOf(_tables[0]));
Assert.Equal(-1, tbcol.IndexOf(_tables[1]));
Assert.Equal(1, tbcol.IndexOf("table1"));
Assert.Equal(2, tbcol.IndexOf("table2"));
Assert.Equal(0, tbcol.IndexOf(tbcol[0]));
Assert.Equal(1, tbcol.IndexOf(tbcol[1]));
Assert.Equal(-1, tbcol.IndexOf("_noTable_"));
DataTable tb = new DataTable("new_table");
Assert.Equal(-1, tbcol.IndexOf(tb));
}
[Fact]
public void RemoveAt()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add(_tables[0]);
tbcol.Add("table1");
try
{
tbcol.RemoveAt(-1);
Assert.False(true);
}
catch (IndexOutOfRangeException e)
{
}
try
{
tbcol.RemoveAt(101);
Assert.False(true);
}
catch (IndexOutOfRangeException e)
{
}
tbcol.RemoveAt(1);
Assert.Equal(1, tbcol.Count);
tbcol.RemoveAt(0);
Assert.Equal(0, tbcol.Count);
}
[Fact]
public void ToStringTest()
{
DataTableCollection tbcol = _dataset[0].Tables;
tbcol.Add("Table1");
tbcol.Add("Table2");
tbcol.Add("Table3");
Assert.Equal("System.Data.DataTableCollection", tbcol.ToString());
}
[Fact]
public void TableDataSetNamespaces()
{
DataTable dt = new DataTable("dt1");
Assert.Equal(string.Empty, dt.Namespace);
Assert.Null(dt.DataSet);
DataSet ds1 = new DataSet("ds1");
ds1.Tables.Add(dt);
Assert.Equal(string.Empty, dt.Namespace);
Assert.Equal(ds1, dt.DataSet);
ds1.Namespace = "ns1";
Assert.Equal("ns1", dt.Namespace);
// back to null again
ds1.Tables.Remove(dt);
Assert.Equal(string.Empty, dt.Namespace);
Assert.Null(dt.DataSet);
// This table is being added to _already namespaced_
// dataset.
dt = new DataTable("dt2");
ds1.Tables.Add(dt);
Assert.Equal("ns1", dt.Namespace);
Assert.Equal(ds1, dt.DataSet);
ds1.Tables.Remove(dt);
Assert.Equal(string.Empty, dt.Namespace);
Assert.Null(dt.DataSet);
DataSet ds2 = new DataSet("ds2");
ds2.Namespace = "ns2";
ds2.Tables.Add(dt);
Assert.Equal("ns2", dt.Namespace);
Assert.Equal(ds2, dt.DataSet);
}
}
}
| |
// 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.
////////////////////////////////////////////////////////////////////////////
//
//
//
// Purpose: This class implements a set of methods for comparing
// strings.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Flags]
[Serializable]
public enum CompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreSymbols = 0x00000004,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
StringSort = 0x20000000, // use string sort method
Ordinal = 0x40000000, // This flag can not be used with other flags.
}
[Serializable]
public partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Mask used to check if GetHashCodeOfString() has the right flags.
private const CompareOptions ValidHashCodeOfStringMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if we have the right flags.
private const CompareOptions ValidSortkeyCtorMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private String _name; // The name used to construct this CompareInfo
[NonSerialized]
private String _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion _sortVersion;
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
// Parameter checking.
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
Contract.EndContractBlock();
return GetCompareInfo(culture);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
public static CompareInfo GetCompareInfo(String name, Assembly assembly)
{
if (name == null || assembly == null)
{
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
Contract.EndContractBlock();
if (assembly != typeof(Object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
** This method is provided for ease of integration with NLS-based software.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** culture the ID of the culture.
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
**Returns: The CompareInfo for the specified culture.
**Arguments:
** name the name of the culture.
**Exceptions:
** ArgumentException if name is invalid.
============================================================================*/
public static CompareInfo GetCompareInfo(String name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
char *pChar = &ch;
return IsSortable(pChar, 1);
}
public static unsafe bool IsSortable(string text)
{
if (text == null)
{
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
if (0 == text.Length)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
fixed (char *pChar = text)
{
return IsSortable(pChar, text.Length);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
_name = null;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
if (_name != null)
{
InitSort(CultureInfo.GetCultureInfo(_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx) { }
///////////////////////////----- Name -----/////////////////////////////////
//
// Returns the name of the culture (well actually, of the sort).
// Very important for providing a non-LCID way of identifying
// what the sort is.
//
// Note that this name isn't dereferenced in case the CompareInfo is a different locale
// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
// and the locale's changed behavior, then you'll get changed behavior, which is like
// what happens for a version update)
//
////////////////////////////////////////////////////////////////////////
public virtual String Name
{
get
{
Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
if (_name == "zh-CHT" || _name == "zh-CHS")
{
return _name;
}
return _sortName;
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two strings with the given options. Returns 0 if the
// two strings are equal, a number less than 0 if string1 is less
// than string2, and a number greater than 0 if string1 is greater
// than string2.
//
////////////////////////////////////////////////////////////////////////
public virtual int Compare(String string1, String string2)
{
return (Compare(string1, string2, CompareOptions.None));
}
public unsafe virtual int Compare(String string1, String string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
}
// Verify the options before we do any real comparison.
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
}
return String.CompareOrdinal(string1, string2);
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
if (string1 == null)
{
if (string2 == null)
{
return (0); // Equal
}
return (-1); // null < non-null
}
if (string2 == null)
{
return (1); // non-null > null
}
return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options);
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the specified regions of the two strings with the given
// options.
// Returns 0 if the two strings are equal, a number less than 0 if
// string1 is less than string2, and a number greater than 0 if
// string1 is greater than string2.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
// Check for the null case.
//
if (string1 == null)
{
if (string2 == null)
{
return (0);
}
return (-1);
}
if (string2 == null)
{
return (1);
}
if (options == CompareOptions.Ordinal)
{
return CompareOrdinal(string1, offset1, length1,
string2, offset2, length2);
}
return CompareString(string1, offset1, length1,
string2, offset2, length2,
options);
}
private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
int result = String.CompareOrdinal(string1, offset1, string2, offset2,
(length1 < length2 ? length1 : length2));
if ((length1 != length2) && result == 0)
{
return (length1 > length2 ? 1 : -1);
}
return (result);
}
//
// CompareOrdinalIgnoreCase compare two string oridnally with ignoring the case.
// it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
// calling the OS.
//
internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
Debug.Assert(indexA + lengthA <= strA.Length);
Debug.Assert(indexB + lengthB <= strB.Length);
int length = Math.Min(lengthA, lengthB);
int range = length;
fixed (char* ap = strA) fixed (char* bp = strB)
{
char* a = ap + indexA;
char* b = bp + indexB;
while (length != 0 && (*a <= 0x80) && (*b <= 0x80))
{
int charA = *a;
int charB = *b;
if (charA == charB)
{
a++; b++;
length--;
continue;
}
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
//Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
if (length == 0)
return lengthA - lengthB;
range -= length;
return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
{
if (source == null || prefix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
if (prefix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
return StartsWith(source, prefix, options);
}
public virtual bool IsPrefix(String source, String prefix)
{
return (IsPrefix(source, prefix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
//
// Determines whether suffix is a suffix of string. If suffix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options)
{
if (source == null || suffix == null)
{
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
if (suffix.Length == 0)
{
return (true);
}
if (source.Length == 0)
{
return false;
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix, StringComparison.Ordinal);
}
if ((options & ValidIndexMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
return EndsWith(source, suffix, options);
}
public virtual bool IsSuffix(String source, String suffix)
{
return (IsSuffix(source, suffix, 0));
}
////////////////////////////////////////////////////////////////////////
//
// IndexOf
//
// Returns the first index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// startIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int IndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, String value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
public unsafe virtual int IndexOf(String source, String value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
Contract.EndContractBlock();
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex > source.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
// In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here.
// We return 0 if both source and value are empty strings for Everett compatibility too.
if (source.Length == 0)
{
if (value.Length == 0)
{
return 0;
}
return -1;
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
return IndexOfCore(source, value, startIndex, count, options, null);
}
////////////////////////////////////////////////////////////////////////
//
// LastIndexOf
//
// Returns the last index where value is found in string. The
// search starts from startIndex and ends at endIndex. Returns -1 if
// the specified value is not found. If value equals String.Empty,
// endIndex is returned. Throws IndexOutOfRange if startIndex or
// endIndex is less than zero or greater than the length of string.
// Throws ArgumentException if value is null.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual int LastIndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(String source, String value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, CompareOptions.None);
}
public virtual int LastIndexOf(String source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
return LastIndexOf(source, value, source.Length - 1,
source.Length, options);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
return LastIndexOfCore(source, value, startIndex, count, options);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual SortKey GetSortKey(String source, CompareOptions options)
{
return CreateSortKey(source, options);
}
public unsafe virtual SortKey GetSortKey(String source)
{
return CreateSortKey(source, CompareOptions.None);
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CompareInfo as the current
// instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
CompareInfo that = value as CompareInfo;
if (that != null)
{
return this.Name == that.Name;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CompareInfo. The hash code is guaranteed to be the same for
// CompareInfo A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.Name.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCodeOfString
//
// This internal method allows a method that allows the equivalent of creating a Sortkey for a
// string from CompareInfo, and generate a hashcode value from it. It is not very convenient
// to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed.
//
// The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both
// the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects
// treat the string the same way, this implementation will treat them differently (the same way that
// Sortkey does at the moment).
//
// This method will never be made public itself, but public consumers of it could be created, e.g.:
//
// string.GetHashCode(CultureInfo)
// string.GetHashCode(CompareInfo)
// string.GetHashCode(CultureInfo, CompareOptions)
// string.GetHashCode(CompareInfo, CompareOptions)
// etc.
//
// (the methods above that take a CultureInfo would use CultureInfo.CompareInfo)
//
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
//
// Parameter validation
//
if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
Contract.EndContractBlock();
return GetHashCodeOfStringCore(source, options);
}
public virtual int GetHashCode(string source, CompareOptions options)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (options == CompareOptions.Ordinal)
{
return source.GetHashCode();
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
}
//
// GetHashCodeOfString does more parameters validation. basically will throw when
// having Ordinal, OrdinalIgnoreCase and StringSort
//
return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("CompareInfo - " + this.Name);
}
public SortVersion Version
{
get
{
if (_sortVersion == null)
{
_sortVersion = GetSortVersion();
}
return _sortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
#if !ZEN_NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ModestTree.Util;
using UnityEditor;
using UnityEngine;
using ModestTree;
#if UNITY_5_3
using UnityEditor.SceneManagement;
#endif
namespace Zenject
{
public static class ZenEditorUtil
{
public static IEnumerable<ZenjectResolveException> ValidateInstallers(SceneCompositionRoot compRoot)
{
return ValidateInstallers(compRoot, null);
}
public static IEnumerable<ZenjectResolveException> ValidateInstallers(SceneCompositionRoot compRoot, GameObject rootGameObject)
{
var globalContainer = GlobalCompositionRoot.CreateContainer(true, null);
var container = compRoot.CreateContainer(true, globalContainer, new List<IInstaller>());
foreach (var error in container.ValidateResolve(
new InjectContext(container, typeof(IFacade), null)))
{
yield return error;
}
var injectedGameObjects = rootGameObject != null ? rootGameObject.GetComponentsInChildren<Transform>() : GameObject.FindObjectsOfType<Transform>();
// Also make sure we can fill in all the dependencies in the built-in scene
foreach (var curTransform in injectedGameObjects)
{
foreach (var monoBehaviour in curTransform.GetComponents<MonoBehaviour>())
{
if (monoBehaviour == null)
{
// fiBackupSceneStorage shows up sometimes for reasons I don't understand
// but it's normal so ignore
if (curTransform.name != "fiBackupSceneStorage")
{
Log.Warn("Found null MonoBehaviour on " + curTransform.name);
}
continue;
}
foreach (var error in container.ValidateObjectGraph(monoBehaviour.GetType()))
{
yield return error;
}
}
}
foreach (var installer in globalContainer.InstalledInstallers.Concat(container.InstalledInstallers).OfType<IValidatable>())
{
foreach (var error in installer.Validate())
{
yield return error;
}
}
foreach (var error in container.ValidateValidatables())
{
yield return error;
}
}
public static void ValidateCurrentSceneThenPlay()
{
if (ValidateCurrentScene())
{
EditorApplication.isPlaying = true;
}
}
public static SceneDecoratorCompositionRoot TryGetSceneDecoratorCompositionRoot()
{
return GameObject.FindObjectsOfType<SceneDecoratorCompositionRoot>().OnlyOrDefault();
}
public static SceneCompositionRoot TryGetSceneCompositionRoot()
{
return GameObject.FindObjectsOfType<SceneCompositionRoot>().OnlyOrDefault();
}
// Returns true if we should continue
static bool CheckForExistingCompositionRoot()
{
if (TryGetSceneCompositionRoot() != null)
{
var shouldContinue = EditorUtility.DisplayDialog("Error", "There already exists a SceneCompositionRoot in the scene. Are you sure you want to add another?", "Yes", "Cancel");
return shouldContinue;
}
return true;
}
[MenuItem("GameObject/Zenject/Scene Composition Root", false, 9)]
public static void CreateSceneCompositionRoot(MenuCommand menuCommand)
{
if (CheckForExistingCompositionRoot())
{
var root = new GameObject("CompositionRoot").AddComponent<SceneCompositionRoot>();
Selection.activeGameObject = root.gameObject;
}
}
[MenuItem("GameObject/Zenject/Decorator Composition Root", false, 9)]
public static void CreateDecoratorCompositionRoot(MenuCommand menuCommand)
{
if (CheckForExistingCompositionRoot())
{
var root = new GameObject("DecoratorCompositionRoot").AddComponent<SceneDecoratorCompositionRoot>();
Selection.activeGameObject = root.gameObject;
}
}
[MenuItem("Assets/Create/Zenject/Global Installers Asset")]
public static void AddGlobalInstallers()
{
var dir = UnityEditorUtil.TryGetCurrentDirectoryInProjectsTab();
var assetName = GlobalCompositionRoot.GlobalInstallersResourceName + ".asset";
if (dir == null)
{
EditorUtility.DisplayDialog("Error",
"Could not find directory to place the {0} asset. Please try again by right clicking in the desired folder within the projects pane.".Fmt(assetName), "Ok");
return;
}
var parentFolderName = Path.GetFileName(dir);
if (parentFolderName != "Resources")
{
EditorUtility.DisplayDialog("Error", "{0} must be placed inside a directory named 'Resources'. Please try again by right clicking within the Project pane in a valid Resources folder.".Fmt(assetName), "Ok");
return;
}
var asset = ScriptableObject.CreateInstance<GlobalInstallerConfig>();
string assetPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(dir, assetName));
AssetDatabase.CreateAsset(asset, assetPath);
AssetDatabase.Refresh();
Debug.Log("Created new asset at '{0}'".Fmt(assetPath));
}
// This can be called by build scripts using batch mode unity for continuous integration testing
// This will exit with an error code for whether validation passed or not
public static void ValidateAllScenesFromScript()
{
ValidateAllActiveScenes(true);
}
[MenuItem("Edit/Zenject/Validate All Active Scenes")]
public static bool ValidateAllActiveScenes()
{
return ValidateAllActiveScenes(false);
}
public static bool ValidateAllActiveScenes(bool exitAfter)
{
return ValidateScenes(UnityEditorUtil.GetAllActiveScenePaths(), exitAfter);
}
static string GetActiveScene()
{
#if UNITY_5_3
return EditorSceneManager.GetActiveScene().path;
#else
return EditorApplication.currentScene;
#endif
}
public static void OpenScene(string scenePath)
{
#if UNITY_5_3
EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
#else
EditorApplication.OpenScene(scenePath);
#endif
}
public static void OpenSceneAdditive(string scenePath)
{
#if UNITY_5_3
EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
#else
EditorApplication.OpenSceneAdditive(scenePath);
#endif
}
public static bool ValidateScenes(List<string> scenePaths, bool exitAfter)
{
var startScene = GetActiveScene();
var failedScenes = new List<string>();
foreach (var scenePath in scenePaths)
{
var sceneName = Path.GetFileNameWithoutExtension(scenePath);
Log.Trace("Validating scene '{0}'...", sceneName);
OpenScene(scenePath);
if (!ValidateCurrentScene())
{
Log.Error("Failed to validate scene '{0}'", sceneName);
failedScenes.Add(sceneName);
}
}
OpenScene(startScene);
if (failedScenes.IsEmpty())
{
Log.Trace("Successfully validated all {0} scenes", scenePaths.Count);
if (exitAfter)
{
EditorApplication.Exit(0);
}
return true;
}
else
{
Log.Error("Validated {0}/{1} scenes. Failed to validate the following: {2}",
scenePaths.Count - failedScenes.Count, scenePaths.Count, failedScenes.Join(", "));
if (exitAfter)
{
EditorApplication.Exit(1);
}
return false;
}
}
[MenuItem("Edit/Zenject/Validate Current Scene #%v")]
public static bool ValidateCurrentScene()
{
var startTime = DateTime.Now;
// Only show a few to avoid spamming the log too much
var resolveErrors = GetCurrentSceneValidationErrors(10).ToList();
foreach (var error in resolveErrors)
{
Log.ErrorException(error);
}
var secondsElapsed = (DateTime.Now - startTime).Milliseconds / 1000.0f;
if (resolveErrors.Any())
{
Log.Error("Validation Completed With Errors, Took {0:0.00} Seconds.", secondsElapsed);
return false;
}
Log.Info("Validation Completed Successfully, Took {0:0.00} Seconds.", secondsElapsed);
return true;
}
static List<ZenjectResolveException> GetCurrentSceneValidationErrors(int maxErrors)
{
var compRoot = GameObject.FindObjectsOfType<SceneCompositionRoot>().OnlyOrDefault();
if (compRoot != null)
{
return ValidateCompRoot(compRoot, maxErrors);
}
var decoratorCompRoot = GameObject.FindObjectsOfType<SceneDecoratorCompositionRoot>().OnlyOrDefault();
if (decoratorCompRoot != null)
{
return ValidateDecoratorCompRoot(decoratorCompRoot, maxErrors);
}
return new List<ZenjectResolveException>()
{
new ZenjectResolveException("Unable to find unique composition root in current scene"),
};
}
static List<ZenjectResolveException> ValidateDecoratorCompRoot(SceneDecoratorCompositionRoot decoratorCompRoot, int maxErrors)
{
var sceneName = decoratorCompRoot.SceneName;
var scenePath = UnityEditorUtil.GetScenePath(sceneName);
if (scenePath == null)
{
return new List<ZenjectResolveException>()
{
new ZenjectResolveException(
"Could not find scene path for decorated scene '{0}'".Fmt(sceneName)),
};
}
var rootObjectsBefore = UnityUtil.GetRootGameObjects();
OpenSceneAdditive(scenePath);
var newRootObjects = UnityUtil.GetRootGameObjects().Except(rootObjectsBefore);
// Use finally to ensure we clean up the data added from OpenSceneAdditive
try
{
var previousBeforeInstallHook = SceneCompositionRoot.BeforeInstallHooks;
SceneCompositionRoot.BeforeInstallHooks = (container) =>
{
if (previousBeforeInstallHook != null)
{
previousBeforeInstallHook(container);
}
decoratorCompRoot.AddPreBindings(container);
};
var previousAfterInstallHook = SceneCompositionRoot.AfterInstallHooks;
SceneCompositionRoot.AfterInstallHooks = (container) =>
{
decoratorCompRoot.AddPostBindings(container);
if (previousAfterInstallHook != null)
{
previousAfterInstallHook(container);
}
};
var compRoot = newRootObjects.SelectMany(x => x.GetComponentsInChildren<SceneCompositionRoot>()).OnlyOrDefault();
if (compRoot != null)
{
return ValidateCompRoot(compRoot, maxErrors);
}
var newDecoratorCompRoot = newRootObjects.SelectMany(x => x.GetComponentsInChildren<SceneDecoratorCompositionRoot>()).OnlyOrDefault();
if (newDecoratorCompRoot != null)
{
return ValidateDecoratorCompRoot(newDecoratorCompRoot, maxErrors);
}
return new List<ZenjectResolveException>()
{
new ZenjectResolveException(
"Could not find composition root for decorated scene '{0}'".Fmt(sceneName)),
};
}
finally
{
#if UNITY_5_3
EditorSceneManager.CloseScene(EditorSceneManager.GetSceneByPath(scenePath), true);
#else
foreach (var newObject in newRootObjects)
{
GameObject.DestroyImmediate(newObject);
}
#endif
}
}
static List<ZenjectResolveException> ValidateCompRoot(SceneCompositionRoot compRoot, int maxErrors)
{
if (compRoot.Installers.IsEmpty())
{
return new List<ZenjectResolveException>()
{
new ZenjectResolveException("Could not find installers while validating current scene"),
};
}
return ValidateInstallers(compRoot).Take(maxErrors).ToList();
}
}
}
#endif
| |
// 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.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Its.Log.Instrumentation;
using Microsoft.Its.Domain;
using Its.Validation;
using Sample.Domain.Ordering.Commands;
namespace Sample.Domain.Ordering
{
public partial class Order
{
public void EnactCommand(CreateOrder create)
{
RecordEvent(new Created
{
CustomerName = create.CustomerName,
CustomerId = create.CustomerId
});
RecordEvent(new CustomerInfoChanged
{
CustomerName = create.CustomerName
});
}
public void EnactCommand(AddItem addItem)
{
RecordEvent(new ItemAdded
{
Price = addItem.Price,
ProductName = addItem.ProductName,
Quantity = addItem.Quantity
});
}
public void EnactCommand(ChangeCustomerInfo command)
{
RecordEvent(new CustomerInfoChanged
{
CustomerName = command.CustomerName,
Address = command.Address,
PhoneNumber = command.PhoneNumber,
PostalCode = command.PostalCode,
RegionOrCountry = command.RegionOrCountry
});
}
public void EnactCommand(ChangeFufillmentMethod change)
{
RecordEvent(new FulfillmentMethodSelected
{
FulfillmentMethod = change.FulfillmentMethod
});
}
public class OrderCancelCommandHandler : ICommandHandler<Order, Cancel>
{
private readonly ICommandScheduler<CustomerAccount> scheduler;
public OrderCancelCommandHandler(
ICommandScheduler<CustomerAccount> scheduler)
{
if (scheduler == null)
{
throw new ArgumentNullException("scheduler");
}
this.scheduler = scheduler;
}
public async Task EnactCommand(Order order, Cancel cancel)
{
var cancelled = new Cancelled();
order.RecordEvent(cancelled);
var command = new NotifyOrderCanceled
{
OrderNumber = order.OrderNumber
};
await scheduler.Schedule(
order.CustomerId,
command,
deliveryDependsOn: cancelled);
}
public async Task HandleScheduledCommandException(Order order, CommandFailed<Cancel> command)
{
// Tests depend on this being an empty handler - don't modify.
Debug.WriteLine("[HandleScheduledCommandException] " + command.ToLogString());
}
}
public void EnactCommand(Deliver cancel)
{
RecordEvent(new Delivered());
RecordEvent(new Fulfilled());
}
public void EnactCommand(ProvideCreditCardInfo command)
{
RecordEvent(new CreditCardInfoProvided
{
CreditCardCvv2 = command.CreditCardCvv2,
CreditCardExpirationMonth = command.CreditCardExpirationMonth,
CreditCardExpirationYear = command.CreditCardExpirationYear,
CreditCardName = command.CreditCardName,
CreditCardNumber = command.CreditCardNumber
});
}
public void HandleCommandValidationFailure(ChargeCreditCard command, ValidationReport validationReport)
{
if (validationReport.Failures.All(failure => failure.IsRetryable()))
{
// this will terminate further attempts
RecordEvent(new CreditCardChargeRejected());
}
else
{
ThrowCommandValidationException(command, validationReport);
}
}
public class OrderChargeCreditCardHandler : ICommandHandler<Order, ChargeCreditCard>
{
public async Task EnactCommand(Order order, ChargeCreditCard command)
{
order.RecordEvent(new CreditCardCharged
{
Amount = command.Amount
});
}
public async Task HandleScheduledCommandException(Order order, CommandFailed<ChargeCreditCard> command)
{
if (command.NumberOfPreviousAttempts < 3)
{
command.Retry(after: command.Command.ChargeRetryPeriod);
}
else
{
order.RecordEvent(new Cancelled
{
Reason = "Final credit card charge attempt failed."
});
}
}
}
public void EnactCommand(ChargeCreditCardOn command)
{
ScheduleCommand(new ChargeCreditCard
{
Amount = command.Amount,
PaymentId = command.PaymentId,
ChargeRetryPeriod = command.ChargeRetryPeriod
}, command.ChargeDate);
}
public void EnactCommand(SpecifyShippingInfo command)
{
RecordEvent(new ShippingMethodSelected
{
Address = command.Address,
City = command.City,
StateOrProvince = command.StateOrProvince,
Country = command.Country,
DeliverBy = command.DeliverBy,
RecipientName = command.RecipientName,
});
}
public void EnactCommand(Place command)
{
RecordEvent(new Placed(orderNumber: Guid.NewGuid().ToString().Substring(0, 8)));
}
public void EnactCommand(ShipOn command)
{
ScheduleCommand(new Ship
{
ShipmentId = command.ShipmentId
}, command.ShipDate);
}
public void EnactCommand(RenameEvent command)
{
pendingRenames.Add(new EventMigrations.Rename(command.sequenceNumber, command.newName));
}
public class OrderShipCommandHandler : ICommandHandler<Order, Ship>
{
public async Task HandleScheduledCommandException(Order order, CommandFailed<Ship> command)
{
Debug.WriteLine("OrderShipCommandHandler.HandleScheduledCommandException");
if (command.Exception is CommandValidationException)
{
if (order.IsCancelled)
{
order.RecordEvent(new ShipmentCancelled());
}
if (order.IsShipped)
{
command.Cancel();
}
}
}
public async Task EnactCommand(Order order, Ship command)
{
Debug.WriteLine("OrderShipCommandHandler.EnactCommand");
order.RecordEvent(new Shipped
{
ShipmentId = command.ShipmentId
});
}
}
public void EnactCommand(ConfirmPayment command)
{
RecordEvent(new PaymentConfirmed
{
PaymentId = command.PaymentId
});
}
public class ChargeAccountHandler : ICommandHandler<Order, ChargeAccount>
{
private readonly IPaymentService paymentService;
public ChargeAccountHandler(IPaymentService paymentService)
{
if (paymentService == null)
{
throw new ArgumentNullException("paymentService");
}
this.paymentService = paymentService;
}
public async Task EnactCommand(Order aggregate, ChargeAccount command)
{
try
{
var paymentId = await paymentService.Charge(aggregate.Balance);
aggregate.RecordEvent(new PaymentConfirmed
{
PaymentId = paymentId
});
}
catch (InvalidOperationException)
{
aggregate.RecordEvent(new ChargeAccountChargeRejected());
}
}
public async Task HandleScheduledCommandException(Order order, CommandFailed<ChargeAccount> command)
{
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Threading;
using System.Reflection;
using NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class Engine_Tests
{
[Test]
public void TestMSBuildForwardPropertiesFromChild()
{
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", null);
Engine childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
string[] propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsNull(propertiesToSerialize, "Expected propertiesToSerialize to be null");
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", string.Empty);
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsNull(propertiesToSerialize, "Expected propertiesToSerialize to be null");
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform;Configuration");
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
Assert.IsTrue(string.Compare(propertiesToSerialize[1], "Configuration") == 0);
Assert.IsTrue(propertiesToSerialize.Length == 2);
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform;;;;;;;;;;Configuration");
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
Assert.IsTrue(string.Compare(propertiesToSerialize[1], "Configuration") == 0);
Assert.IsTrue(propertiesToSerialize.Length == 2);
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform;");
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
Assert.IsTrue(propertiesToSerialize.Length == 1);
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", "Platform");
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
Assert.IsTrue(propertiesToSerialize.Length == 1);
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", ";Platform");
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
Assert.IsTrue(propertiesToSerialize.Length == 1);
childEngine.Shutdown();
Environment.SetEnvironmentVariable("MSBuildForwardPropertiesFromChild", ";Platform;");
childEngine = new Engine(new BuildPropertyGroup(), new ToolsetDefinitionLocations(), 3, true, 3, string.Empty, string.Empty);
propertiesToSerialize = childEngine.PropertyListToSerialize;
Assert.IsTrue(string.Compare(propertiesToSerialize[0], "Platform") == 0);
Assert.IsTrue(propertiesToSerialize.Length == 1);
childEngine.Shutdown();
}
[Test]
public void DefaultToolsVersionInitializedWithBinPath()
{
Engine e = new Engine(@"C:\binpath");
Assertion.AssertEquals(Constants.defaultToolsVersion, e.DefaultToolsVersion);
Assertion.AssertEquals(@"C:\binpath", e.Toolsets[Constants.defaultToolsVersion].ToolsPath);
}
[Test]
public void TestTEMBatchSizeSettings()
{
Engine e = new Engine(@"C:\binpath");
EngineLoggingServicesHelper loggingServicesHelper = new EngineLoggingServicesHelper();
e.LoggingServices = loggingServicesHelper;
EngineCallback engineCallback = new EngineCallback(e);
Environment.SetEnvironmentVariable("MSBUILDREQUESTBATCHSIZE", "-4");
TaskExecutionModule TEM = new TaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, false);
DualQueue<BuildEventArgs> currentQueue = loggingServicesHelper.GetCurrentQueueBuildEvents();
BuildEventArgs currentEvent = currentQueue.Dequeue();
Assertion.Assert("Expected event to be a warning event", currentEvent is BuildWarningEventArgs);
Assertion.Assert(String.Compare(ResourceUtilities.FormatResourceString("BatchRequestSizeOutOfRange", "-4"), ((BuildWarningEventArgs)currentEvent).Message, StringComparison.OrdinalIgnoreCase) == 0);
e = new Engine(@"C:\binpath");
loggingServicesHelper = new EngineLoggingServicesHelper();
e.LoggingServices = loggingServicesHelper;
engineCallback = new EngineCallback(e);
Environment.SetEnvironmentVariable("MSBUILDREQUESTBATCHSIZE", "0");
TEM = new TaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, false);
currentQueue = loggingServicesHelper.GetCurrentQueueBuildEvents();
currentEvent = currentQueue.Dequeue();
Assertion.Assert("Expected event to be a warning event", currentEvent is BuildWarningEventArgs);
Assertion.Assert(String.Compare(ResourceUtilities.FormatResourceString("BatchRequestSizeOutOfRange", "0"), ((BuildWarningEventArgs)currentEvent).Message, StringComparison.OrdinalIgnoreCase) == 0);
e = new Engine(@"C:\binpath");
loggingServicesHelper = new EngineLoggingServicesHelper();
e.LoggingServices = loggingServicesHelper;
engineCallback = new EngineCallback(e);
Environment.SetEnvironmentVariable("MSBUILDREQUESTBATCHSIZE", int.MaxValue.ToString());
TEM = new TaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, false);
currentQueue = loggingServicesHelper.GetCurrentQueueBuildEvents();
Assertion.Assert(currentQueue.Count == 0);
e = new Engine(@"C:\binpath");
loggingServicesHelper = new EngineLoggingServicesHelper();
e.LoggingServices = loggingServicesHelper;
engineCallback = new EngineCallback(e);
Environment.SetEnvironmentVariable("MSBUILDREQUESTBATCHSIZE", "4");
TEM = new TaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, false);
currentQueue = loggingServicesHelper.GetCurrentQueueBuildEvents();
Assertion.Assert(currentQueue.Count == 0);
e = new Engine(@"C:\binpath");
loggingServicesHelper = new EngineLoggingServicesHelper();
e.LoggingServices = loggingServicesHelper;
engineCallback = new EngineCallback(e);
Environment.SetEnvironmentVariable("MSBUILDREQUESTBATCHSIZE", "Giberish");
TEM = new TaskExecutionModule(engineCallback, TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, false);
currentQueue = loggingServicesHelper.GetCurrentQueueBuildEvents();
currentEvent = currentQueue.Dequeue();
Assertion.Assert("Expected event to be a warning event", currentEvent is BuildWarningEventArgs);
Assertion.Assert(String.Compare(ResourceUtilities.FormatResourceString("BatchRequestSizeOutOfRange", "Giberish"), ((BuildWarningEventArgs)currentEvent).Message, StringComparison.OrdinalIgnoreCase) == 0);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SettingDefaultToolsVersionThrowsIfProjectsAlreadyLoaded()
{
Engine e = new Engine(ToolsetDefinitionLocations.None);
try
{
e.AddToolset(new Toolset("1.0", "someToolsPath"));
e.AddToolset(new Toolset("2.0", "someToolsPath"));
e.DefaultToolsVersion = "1.0"; // OK
}
catch(InvalidOperationException)
{
// Make sure the first one doesn't throw
Assertion.Assert(false);
}
try
{
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.csproj", @"<Project DefaultTargets=`Build` xmlns=`msbuildnamespace`/>");
Project p1 = new Project(e);
p1.Load(p1Path);
e.DefaultToolsVersion = "2.0"; // Throws
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
[Test]
public void AddingAnExistingToolsVersionDirtiesLoadedProjects()
{
try
{
Engine e = new Engine(ToolsetDefinitionLocations.None);
e.AddToolset(new Toolset("2.0", "someToolsPath"));
e.AddToolset(new Toolset("3.0", "anotherToolsPath"));
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.csproj", @"<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`/>");
string p2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p2.csproj", @"<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`/>");
Project p1 = new Project(e, "2.0");
p1.Load(p1Path);
Project p2 = new Project(e, "3.0");
p2.Load(p2Path);
Assertion.Assert("Expected p1.IsDirty to be false", !p1.IsDirty);
Assertion.Assert("Expected p2.IsDirty to be false", !p2.IsDirty);
e.AddToolset(new Toolset("2.0", "someTotallyDifferentToolsPath"));
Assertion.Assert("Expected p1.IsDirty to be true", p1.IsDirty);
Assertion.Assert("Expected p2.IsDirty to be false", !p2.IsDirty);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
[Test]
public void BinPathAfterDefaultToolsVersionChange()
{
Engine e = new Engine(ToolsetDefinitionLocations.None);
e.AddToolset(new Toolset("orcas", @"C:\OrcasBinPath"));
e.DefaultToolsVersion = "Orcas";
Assertion.AssertEquals(@"C:\OrcasBinPath", e.BinPath);
Assertion.AssertEquals("Orcas", e.DefaultToolsVersion);
}
[Test]
public void GetToolsVersionNames()
{
// Check the contents of GetToolsVersions on engine creation
Engine e = new Engine(ToolsetDefinitionLocations.None);
List<string> toolsVersions = new List<string>(e.Toolsets.ToolsVersions);
Assertion.AssertEquals(1, toolsVersions.Count);
Assertion.AssertEquals(Constants.defaultToolsVersion, toolsVersions[0]);
// Check the contents after adding two more tools versions
e.Toolsets.Add(new Toolset("Whidbey", @"C:\WhidbeyPath"));
e.Toolsets.Add(new Toolset("orcas", @"C:\OrcasBinPath"));
Dictionary<string, object> toolsVersionNamesDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (string name in e.Toolsets.ToolsVersions)
{
toolsVersionNamesDictionary[name] = null;
}
Assertion.AssertEquals(3, toolsVersionNamesDictionary.Count);
Assertion.AssertEquals(true, toolsVersionNamesDictionary.ContainsKey(Constants.defaultToolsVersion));
Assertion.AssertEquals(true, toolsVersionNamesDictionary.ContainsKey("Whidbey"));
Assertion.AssertEquals(true, toolsVersionNamesDictionary.ContainsKey("Orcas"));
}
[Test]
public void GetToolsetSettings()
{
Engine e = new Engine(@"C:\binpath");
e.Toolsets.Add(new Toolset("Whidbey", @"C:\WhidbeyPath"));
BuildPropertyGroup properties = new BuildPropertyGroup();
properties.SetProperty("foo", "bar");
e.Toolsets.Add(new Toolset("orcas", @"C:\OrcasBinPath", properties));
Toolset ts1 = e.Toolsets["Whidbey"];
Toolset ts2 = e.Toolsets["Orcas"];
Assertion.AssertEquals(@"C:\WhidbeyPath", ts1.ToolsPath);
Assertion.AssertEquals(@"C:\OrcasBinPath", ts2.ToolsPath);
Assertion.AssertEquals(0, ts1.BuildProperties.Count);
Assertion.AssertEquals(1, ts2.BuildProperties.Count);
Assertion.AssertEquals("bar", ts2.BuildProperties["foo"].Value);
}
[Test]
public void GetToolsetProxiesToolset()
{
Engine e = new Engine(@"C:\binpath");
e.Toolsets.Add(new Toolset("Whidbey", @"C:\WhidbeyPath"));
BuildPropertyGroup properties = new BuildPropertyGroup();
properties.SetProperty("foo", "bar");
e.Toolsets.Add(new Toolset("orcas", @"C:\OrcasBinPath", properties));
Toolset ts1 = e.Toolsets["orcas"];
ts1.BuildProperties["foo"].Value = "bar2";
ts1.BuildProperties.SetProperty("foo2", "bar3");
Assertion.AssertEquals("bar2", ts1.BuildProperties["foo"].Value);
Assertion.AssertEquals("bar3", ts1.BuildProperties["foo2"].Value);
// Get it again, should be unchanged
Toolset ts1b = e.Toolsets["orcas"];
Assertion.AssertEquals("bar", ts1b.BuildProperties["foo"].Value);
Assertion.AssertNull(ts1b.BuildProperties["foo2"]);
}
/// <summary>
/// Check the code that assigns values to MSBuildBinPath
/// </summary>
[Test]
public void MSBuildBinPath()
{
Engine engine = new Engine();
engine.BinPath = @"C:";
Assertion.AssertEquals(@"C:", engine.BinPath); // the user should be able to pass in a raw drive letter
engine.BinPath = @"C:\";
Assertion.AssertEquals(@"C:\", engine.BinPath);
engine.BinPath = @"C:\\";
Assertion.AssertEquals(@"C:\", engine.BinPath);
engine.BinPath = @"C:\foo";
Assertion.AssertEquals(@"C:\foo", engine.BinPath);
engine.BinPath = @"C:\foo\";
Assertion.AssertEquals(@"C:\foo", engine.BinPath);
engine.BinPath = @"C:\foo\\";
Assertion.AssertEquals(@"C:\foo\", engine.BinPath); // trim at most one slash
engine.BinPath = @"\\foo\share";
Assertion.AssertEquals(@"\\foo\share", engine.BinPath);
engine.BinPath = @"\\foo\share\";
Assertion.AssertEquals(@"\\foo\share", engine.BinPath);
engine.BinPath = @"\\foo\share\\";
Assertion.AssertEquals(@"\\foo\share\", engine.BinPath); // trim at most one slash
}
/// <summary>
/// When a project fails to load successfully, the engine should not be tracking it.
/// Bug VSWhidbey 415236.
/// </summary>
[Test]
public void MalformedProjectDoesNotGetAddedToEngine
(
)
{
Engine myEngine = new Engine(@"c:\");
Project myProject = myEngine.CreateNewProject();
// Create a temp file to be used as our project file.
string projectFile = Path.GetTempFileName();
try
{
// Write some garbage into a project file.
File.WriteAllText(projectFile, "blah");
Assertion.AssertNull("Engine should not know about project before project has been loaded",
myEngine.GetLoadedProject(projectFile));
int exceptionCount = 0;
// Load the garbage project file. We should get an exception.
try
{
myProject.Load(projectFile);
}
catch (InvalidProjectFileException)
{
exceptionCount++;
}
Assertion.AssertEquals("Should have received invalid project file exception.", 1, exceptionCount);
Assertion.AssertNull("Engine should not know about project if project load failed.",
myEngine.GetLoadedProject(projectFile));
}
finally
{
// Get a little extra code coverage
myEngine.UnregisterAllLoggers();
myEngine.UnloadAllProjects();
File.Delete(projectFile);
}
}
/// <summary>
/// Engine.BuildProjectFile method with project file specified does not honor global properties set in the engine object
/// Bug VSWhidbey 570988.
/// </summary>
[Test]
public void BuildProjectFileWithGlobalPropertiesSetInEngineObjectWithProjectFileSpecified
(
)
{
MockEngine myEngine = new MockEngine();
string projectFile = CreateGlobalPropertyProjectFile();
try
{
myEngine.GlobalProperties.SetProperty("MyGlobalProp", "SomePropertyText");
myEngine.BuildProjectFile(projectFile);
myEngine.AssertLogContains("SomePropertyText");
}
finally
{
myEngine.UnregisterAllLoggers();
myEngine.UnloadAllProjects();
File.Delete(projectFile);
}
}
/// <summary>
/// Engine.BuildProjectFile method with project file and target specified does not honor global properties set in the engine object
/// Bug VSWhidbey 570988.
/// </summary>
[Test]
public void BuildProjectFileWithGlobalPropertiesSetInEngineObjectWithProjectFileAndTargetSpecified
(
)
{
MockEngine myEngine = new MockEngine();
string projectFile = CreateGlobalPropertyProjectFile();
try
{
myEngine.GlobalProperties.SetProperty("MyGlobalProp", "SomePropertyText");
myEngine.BuildProjectFile(projectFile, "Build");
myEngine.AssertLogContains("SomePropertyText");
}
finally
{
myEngine.UnregisterAllLoggers();
myEngine.UnloadAllProjects();
File.Delete(projectFile);
}
}
/// <summary>
/// Engine.BuildProjectFile method with project file and target list specified does not honor global properties set in the engine object
/// Bug VSWhidbey 570988.
/// </summary>
[Test]
public void BuildProjectFileWithGlobalPropertiesSetInEngineObjectWithProjectFileAndTargetListSpecified
(
)
{
string[] targets;
MockEngine myEngine = new MockEngine();
string projectFile = CreateGlobalPropertyProjectFile();
try
{
targets = new string[1];
targets[0] = "Build";
myEngine.GlobalProperties.SetProperty("MyGlobalProp", "SomePropertyText");
myEngine.BuildProjectFile(projectFile, targets);
myEngine.AssertLogContains("SomePropertyText");
}
finally
{
myEngine.UnregisterAllLoggers();
myEngine.UnloadAllProjects();
File.Delete(projectFile);
}
}
/// <summary>
/// Try building a project where the global properties passed in are null. The project should build and not crash
/// </summary>
[Test]
public void BuildProjectFileWithNullGlobalProperties
(
)
{
string[] targets;
MockEngine myEngine = new MockEngine();
string projectFile = CreateGlobalPropertyProjectFile();
try
{
targets = new string[1];
targets[0] = "Build";
bool result = myEngine.BuildProjectFile(projectFile, targets, null);
myEngine.AssertLogDoesntContain("SomePropertyText");
Assert.IsTrue(result);
}
finally
{
myEngine.UnregisterAllLoggers();
myEngine.UnloadAllProjects();
File.Delete(projectFile);
}
}
/// <summary>
/// Test building multiple projects in paralle using the object model, both individual projects and traversal projects
/// </summary>
[Test]
[Ignore("Commenting this out as it sporadically fails. It is not clear what scenarios we will support for the reshipped MSBuild engine and we will decide in beta 2.")]
public void BuildProjectFilesInParallel()
{
//Gets the currently loaded assembly in which the specified class is defined
Assembly engineAssembly = Assembly.GetAssembly(typeof(Engine));
string loggerClassName = "Microsoft.Build.BuildEngine.ConfigurableForwardingLogger";
string loggerAssemblyName = engineAssembly.GetName().FullName;
LoggerDescription forwardingLoggerDescription = new LoggerDescription(loggerClassName, loggerAssemblyName, null, null, LoggerVerbosity.Normal);
string[] fileNames = new string[10];
string traversalProject = TraversalProjectFile("ABC");
string[][] targetNamesPerProject = new string[fileNames.Length][];
IDictionary[] targetOutPutsPerProject = new IDictionary[fileNames.Length];
BuildPropertyGroup[] globalPropertiesPerProject = new BuildPropertyGroup[fileNames.Length];
string[] tempfilesToDelete = new string[fileNames.Length];
Engine engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
try
{
for (int i = 0; i < fileNames.Length; i++)
{
string[] ProjectFiles1 = CreateGlobalPropertyProjectFileWithExtension("ABC");
fileNames[i] = ProjectFiles1[0];
tempfilesToDelete[i] = ProjectFiles1[1];
targetNamesPerProject[i] = new string[] { "Build" };
}
// Test building a traversal
engine.BuildProjectFile(traversalProject);
engine.Shutdown();
// Test building the same set of files in parallel
Console.Out.WriteLine("1:"+Process.GetCurrentProcess().MainModule.FileName);
Console.Out.WriteLine("2:" + AppDomain.CurrentDomain.BaseDirectory);
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterDistributedLogger(new ConsoleLogger(LoggerVerbosity.Normal), forwardingLoggerDescription);
engine.BuildProjectFiles(fileNames, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.Shutdown();
// Do the same using singleproc
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFile(traversalProject);
engine.Shutdown();
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 1, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFiles(fileNames, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
}
finally
{
engine.Shutdown();
for (int i = 0; i < fileNames.Length; i++)
{
File.Delete(fileNames[i]);
File.Delete(tempfilesToDelete[i]);
}
File.Delete(traversalProject);
}
}
/// <summary>
/// Test building multiple projects in parallel using the OM. Try building multiple project builds on the same engine.
/// </summary>
[Test]
[Ignore("Commenting this out as it sporadically fails. It is not clear what scenarios we will support for the reshipped MSBuild engine and we will decide in beta 2.")]
public void BuildProjectFilesInParallel2()
{
string[] fileNames = new string[10];
string[] fileNames2 = new string[10];
string[] fileNamesLeafs = new string[10];
string[] childTraversals = new string[10];
string parentTraversal = TraversalProjectFile("CTrav");
string traversalProject = TraversalProjectFile("ABC");
string[][] targetNamesPerProject = new string[fileNames.Length][];
IDictionary[] targetOutPutsPerProject = new IDictionary[fileNames.Length];
BuildPropertyGroup[] globalPropertiesPerProject = new BuildPropertyGroup[fileNames.Length];
string[] tempfilesToDelete = new string[fileNames.Length];
string[] tempfilesToDelete2 = new string[fileNames.Length];
string[] tempfilesToDelete3 = new string[fileNames.Length];
string[] tempfilesToDelete4 = new string[fileNames.Length];
Engine engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
try
{
for (int i = 0; i < fileNames.Length; i++)
{
string[] ProjectFiles1 = CreateGlobalPropertyProjectFileWithExtension("ABC");
string[] ProjectFiles2 = CreateGlobalPropertyProjectFileWithExtension("DEF");
string[] FileNamesLeafs = CreateGlobalPropertyProjectFileWithExtension("LEAF");
string[] ChildTraversals = CreateSingleProjectTraversalFileWithExtension(FileNamesLeafs[0],"CTrav");
fileNames[i] = ProjectFiles1[0];
fileNames2[i] = ProjectFiles2[0];
fileNamesLeafs[i] = FileNamesLeafs[0];
childTraversals[i] = ChildTraversals[0];
tempfilesToDelete[i] = ProjectFiles1[1];
tempfilesToDelete2[i] = ProjectFiles2[1];
tempfilesToDelete3[i] = FileNamesLeafs[1];
tempfilesToDelete4[i] = ChildTraversals[1];
targetNamesPerProject[i] = new string[] { "Build" };
}
// Try building a traversal project that had other traversals
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFile(parentTraversal, new string[] { "Build" }, new BuildPropertyGroup(), null, BuildSettings.None, "3.5");
engine.Shutdown();
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
// Try building the same traversal project on the same engine one after another
engine.BuildProjectFile(traversalProject);
engine.BuildProjectFile(traversalProject);
engine.Shutdown();
// Try building the same set of project files on the same engine one after another
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFiles(fileNames, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.BuildProjectFiles(fileNames, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.Shutdown();
// Try building a set of project files, then the same set as a traversal on the same engine
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFiles(fileNames2, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.BuildProjectFile(traversalProject);
engine.Shutdown();
// Try building a traversal, then the same files which are in the traversal in parallel on the same engine
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFile(traversalProject);
engine.BuildProjectFiles(fileNames2, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.Shutdown();
/* Do the same as above using single proc */
// Try building the same traversal project on the same engine one after another
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 1, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFile(traversalProject);
engine.BuildProjectFile(traversalProject);
engine.Shutdown();
// Try building the same set of project files on the same engine one after another
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 1, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFiles(fileNames, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.BuildProjectFiles(fileNames, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.Shutdown();
// Try building a set of project files, then the same set as a traversal on the same engine
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 1, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFiles(fileNames2, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
engine.BuildProjectFile(traversalProject);
engine.Shutdown();
// Try building a traversal, then the same files which are in the traversal in parallel on the same engine
engine = new Engine(null, ToolsetDefinitionLocations.ConfigurationFile | ToolsetDefinitionLocations.Registry, 4, "msbuildlocation="+ AppDomain.CurrentDomain.BaseDirectory);
engine.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
engine.BuildProjectFile(traversalProject);
engine.BuildProjectFiles(fileNames2, targetNamesPerProject, globalPropertiesPerProject, targetOutPutsPerProject, BuildSettings.None, new string[fileNames.Length]);
}
finally
{
engine.Shutdown();
for (int i = 0; i < fileNames.Length; i++)
{
File.Delete(fileNames[i]);
File.Delete(fileNames2[i]);
File.Delete(fileNamesLeafs[i]);
File.Delete(childTraversals[i]);
File.Delete(tempfilesToDelete[i]);
File.Delete(tempfilesToDelete2[i]);
File.Delete(tempfilesToDelete3[i]);
File.Delete(tempfilesToDelete4[i]);
}
File.Delete(traversalProject);
}
}
private string CreateGlobalPropertyProjectFile()
{
string projectFileContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<Target Name=""Build"">
<Message Text=""MyGlobalProp = $(MyGlobalProp)"" />
</Target>
</Project>
");
string projectFile = Path.GetTempFileName();
using (StreamWriter fileStream =
new StreamWriter(projectFile))
{
fileStream.Write(projectFileContents);
}
return projectFile;
}
/// <summary>
/// Create a new project file that outputs a property
/// </summary>
/// <returns></returns>
private string[] CreateGlobalPropertyProjectFileWithExtension(string extension)
{
string projectFileContents = @"
<Project ToolsVersion=""3.5"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Target Name=""Build"">
<Message Text=""MyGlobalProp = $(MyGlobalProp)"" />
</Target>
</Project>
";
string tempFile = Path.GetTempFileName();
string projectFile = tempFile + extension;
using (StreamWriter fileStream =
new StreamWriter(projectFile))
{
fileStream.Write(projectFileContents);
}
return new string[] { projectFile, tempFile };
}
private string[] CreateSingleProjectTraversalFileWithExtension(string projectName, string extension)
{
string projectFileContents = @"
<Project ToolsVersion=""3.5"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<ItemGroup>";
projectFileContents = projectFileContents + @"<ProjectReferences Include=""";
projectFileContents = projectFileContents + projectName;
projectFileContents = projectFileContents + @"""/>
</ItemGroup>
<Target Name=""Build"">
<MSBuild
BuildInParallel=""true""
Projects=""@(ProjectReferences)""
Targets=""Build"">
</MSBuild>
</Target>
</Project>
";
string tempFile = Path.GetTempFileName();
string projectFile = tempFile + extension;
using (StreamWriter fileStream =
new StreamWriter(projectFile))
{
fileStream.Write(projectFileContents);
}
return new string[] { projectFile, tempFile };
}
private string TraversalProjectFile(string extensionForChildProjects)
{
string projectFileContents = @"
<Project ToolsVersion=""3.5"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<ItemGroup>";
projectFileContents = projectFileContents + @"<ProjectReferences Include=""*.*";
projectFileContents = projectFileContents + extensionForChildProjects;
projectFileContents = projectFileContents + @"""/>
</ItemGroup>
<Target Name=""Build"">
<MSBuild
BuildInParallel=""true""
Projects=""@(ProjectReferences)""
Targets=""Build"">
</MSBuild>
</Target>
</Project>
";
string projectFile = Path.GetTempFileName();
using (StreamWriter fileStream =
new StreamWriter(projectFile))
{
fileStream.Write(projectFileContents);
}
return projectFile;
}
[Test]
public void RestoringProjectIdFromCache()
{
string childProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`Build`>
<Message Text=`Hi`/>
</Target>
</Project>
");
string mainProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`Build`>
<MSBuild Projects=`{0}` UnloadProjectsOnCompletion=`true` UseResultsCache=`true`/>
<MSBuild Projects=`{0}` UnloadProjectsOnCompletion=`true` UseResultsCache=`true`/>
</Target>
</Project>
", childProject);
ProjectIdLogger logger = new ProjectIdLogger();
Engine engine = new Engine();
engine.RegisterLogger(logger);
Project project = new Project(engine, "4.0");
project.Load(mainProject);
bool success = project.Build(null, null);
Assertion.Assert("Build failed. See Standard Out tab for details", success);
Assert.AreEqual(3, logger.ProjectStartedEvents.Count);
// Project ID should be preserved between runs
Assert.AreEqual(logger.ProjectStartedEvents[1].ProjectId, logger.ProjectStartedEvents[2].ProjectId);
// Project context ID should be different for every entry into the project.
Assert.AreNotEqual(logger.ProjectStartedEvents[1].BuildEventContext.ProjectContextId, logger.ProjectStartedEvents[2].BuildEventContext.ProjectContextId);
}
/// <summary>
/// Build a project where the global properties of the child project is poorly formatted.
/// </summary>
[Test]
public void BuildProjectWithPoorlyFormattedGlobalProperty()
{
string childProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`Build` Outputs=`$(a)$(b)`>
<Message Text=`[b]`/>
</Target>
</Project>
");
string mainProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<ItemGroup>
<Prj Include=`{0}`>
<Properties>``=1</Properties>
</Prj>
</ItemGroup>
<Target Name=`1`>
<MSBuild Projects=`@(Prj)` />
</Target>
</Project>
", childProject);
ProjectIdLogger logger = new ProjectIdLogger();
Engine engine = new Engine();
engine.RegisterLogger(logger);
Project project = new Project(engine, "4.0");
project.Load(mainProject);
bool success = project.Build(null, null);
Assertion.Assert("Build succeeded and should have failed. See Standard Out tab for details", !success);
}
/// <summary>
/// Build a project where the global properties of the child project is a reserved property.
/// </summary>
[Test]
public void BuildProjectWithReservedGlobalProperty()
{
string childProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`1`></Target>
</Project>
");
string mainProject = ObjectModelHelpers.CreateTempFileOnDisk(@"
<Project xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`>
<Target Name=`1`>
<MSBuild Projects=`@(ProjectReference)`/>
</Target>
<ItemGroup>
<ProjectReference Include=`{0}`><Properties>Target=1</Properties></ProjectReference>
</ItemGroup>
</Project>
", childProject);
ProjectIdLogger logger = new ProjectIdLogger();
Engine engine = new Engine();
engine.RegisterLogger(logger);
Project project = new Project(engine, "4.0");
project.Load(mainProject);
bool success = project.Build(null, null);
Assertion.Assert("Build succeded and should have failed. See Standard Out tab for details", !success);
}
/// <summary>
/// We should use the Prjects tools version if a particular tools version is not specified.
/// </summary>
[Test]
public void ProjectShouldBuildUsingProjectToolsVersion()
{
try
{
string projectContent =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
Project p1 = new Project(e);
p1.Load(p1Path);
p1.Build();
logger.AssertLogContains("[a=" + ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// We should use the default tools version if a particular tools version is not specified.
/// </summary>
[Test]
public void ProjectShouldUseDefaultToolsVersionIfOneIsNotSpecified()
{
try
{
string projectContent =
@"
<Project xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
Project p1 = new Project(e);
p1.Load(p1Path);
p1.Build();
Assertion.Assert("Cachescope should have an entry with default tools version", e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), e.DefaultToolsVersion, CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// Project built using MSBuild task should use the default tools version if one is not specified.
/// </summary>
[Test]
public void ProjectBuiltUsingMSBuildTaskShouldBuildUsingDefaultToolsVersionIfOneIsNotSpecified()
{
try
{
string projectContent =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
<MSBuild Projects=`p2.proj`/>
</Target>
</Project>
";
string projectContent2 =
@"
<Project xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[b=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
string p2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p2.proj", projectContent2);
Project p1 = new Project(e);
p1.Load(p1Path);
p1.Build();
logger.AssertLogContains("[a="+ ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
Assertion.Assert("Cachescope should have an entry with 4.0", e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
Assertion.Assert("Cachescope should have an entry with default tools version", e.CacheManager.GetCacheScope(p2Path, new BuildPropertyGroup(), e.DefaultToolsVersion, CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// Project built using MSBuild task should use the default tools version if one is not specified.
/// </summary>
[Test]
public void ProjectBuiltUsingMSBuildTaskShouldUseProjectToolsVersionIfOneIsSpecified()
{
try
{
string projectContent =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
<MSBuild Projects=`p2.proj`/>
</Target>
</Project>
";
string projectContent2 =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[b=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
string p2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p2.proj", projectContent2);
Project p1 = new Project(e);
p1.Load(p1Path);
p1.Build();
logger.AssertLogContains("[a="+ ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
logger.AssertLogContains("[b="+ ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p2Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// Project built using MSBuild task should use the tools version scecified in the task.
/// </summary>
[Test]
public void ProjectBuiltUsingMSBuildTaskAndToolsVersionShouldUseTheOneSpecifiedInMSBuildTask()
{
try
{
string projectContent =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
<MSBuild Projects=`p2.proj`/>
<MSBuild Projects=`p2.proj` ToolsVersion='msbuilddefaulttoolsversion'/>
<MSBuild Projects=`p2.proj` ToolsVersion='2.0'/>
</Target>
</Project>
";
string projectContent2 =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[b=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
string p2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p2.proj", projectContent2);
Project p1 = new Project(e);
p1.Load(p1Path);
p1.Build();
logger.AssertLogContains("[a=" + ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
logger.AssertLogContains("[b=2.0]");
logger.AssertLogContains("[b=" + ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
Assertion.Assert("Cachescope should have an entry with 2.0", e.CacheManager.GetCacheScope(p2Path, new BuildPropertyGroup(), "2.0", CacheContentType.BuildResults) != null);
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p2Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// OverridingToolsVersion in Project should be false if the build request tools version and the project's tools version are the same
/// </summary>
[Test]
public void ProjectToolsVersionOverwriteIsFalse()
{
try
{
string projectContent =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
<MSBuild Projects=`p2.proj`/>
<MSBuild Projects=`p2.proj` ToolsVersion='3.5'/>
<MSBuild Projects=`p2.proj` ToolsVersion='2.0'/>
</Target>
</Project>
";
string projectContent2 =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[b=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
string p2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p2.proj", projectContent2);
Project p1 = new Project(e);
p1.Load(p1Path);
p1.Build();
logger.AssertLogContains("[a="+ ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
logger.AssertLogContains("[b=" + ObjectModelHelpers.MSBuildDefaultToolsVersion + "]");
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
Assertion.Assert("Cachescope should have an entry with " + ObjectModelHelpers.MSBuildDefaultToolsVersion, e.CacheManager.GetCacheScope(p2Path, new BuildPropertyGroup(), ObjectModelHelpers.MSBuildDefaultToolsVersion, CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
/// <summary>
/// OverridingToolsVersion in Project should be true if the build request tools version and the project's tools version are not the same
/// </summary>
[Test]
public void ProjectToolsVersionOverwriteIsTrue()
{
try
{
string projectContent =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[a=$(MSBuildToolsVersion)]`/>
<MSBuild Projects=`p2.proj`/>
<MSBuild Projects=`p2.proj` ToolsVersion='3.5'/>
<MSBuild Projects=`p2.proj` ToolsVersion='2.0'/>
</Target>
</Project>
";
string projectContent2 =
@"
<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name=`a`>
<Message Text=`[b=$(MSBuildToolsVersion)]`/>
</Target>
</Project>
";
MockLogger logger = new MockLogger();
Engine e = new Engine();
e.RegisterLogger(logger);
string p1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p1.proj", projectContent);
string p2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("p2.proj", projectContent2);
Project p1 = new Project(e, "2.0");
p1.Load(p1Path);
p1.Build();
logger.AssertLogContains("[a=2.0]");
logger.AssertLogContains("[b=2.0]");
Assertion.Assert("Cachescope should have an entry with 2.0", e.CacheManager.GetCacheScope(p1Path, new BuildPropertyGroup(), "2.0", CacheContentType.BuildResults) != null);
Assertion.Assert("Cachescope should have an entry with 2.0", e.CacheManager.GetCacheScope(p2Path, new BuildPropertyGroup(), "2.0", CacheContentType.BuildResults) != null);
}
finally
{
ObjectModelHelpers.DeleteTempProjectDirectory();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using Baseline;
using Marten.Storage;
using Marten.Util;
namespace Marten.Schema
{
public class DbObjects : IDbObjects
{
private readonly ITenant _tenant;
private readonly StorageFeatures _features;
public DbObjects(ITenant tenant, StorageFeatures features)
{
_tenant = tenant;
_features = features;
}
public DbObjectName[] DocumentTables()
{
return SchemaTables().Where(x => x.Name.StartsWith(DocumentMapping.TablePrefix)).ToArray();
}
public DbObjectName[] Functions()
{
Func<DbDataReader, DbObjectName> transform = r => new DbObjectName(r.GetString(0), r.GetString(1));
var sql =
"SELECT specific_schema, routine_name FROM information_schema.routines WHERE type_udt_name != 'trigger' and routine_name like ? and specific_schema = ANY(?);";
return
_tenant.Fetch(sql, transform, DocumentMapping.MartenPrefix + "%", _features.AllSchemaNames()).ToArray();
}
public DbObjectName[] SchemaTables()
{
Func<DbDataReader, DbObjectName> transform = r => new DbObjectName(r.GetString(0), r.GetString(1));
var sql =
"SELECT schemaname, relname FROM pg_stat_user_tables WHERE relname LIKE ? AND schemaname = ANY(?);";
var schemaNames = _features.AllSchemaNames();
var tablePattern = DocumentMapping.MartenPrefix + "%";
var tables = _tenant.Fetch(sql, transform, tablePattern, schemaNames).ToArray();
return tables;
}
public bool TableExists(DbObjectName table)
{
var schemaTables = SchemaTables();
return schemaTables.Contains(table);
}
public IEnumerable<ActualIndex> AllIndexes()
{
var sql = @"
SELECT
U.usename AS user_name,
ns.nspname AS schema_name,
pg_catalog.textin(pg_catalog.regclassout(idx.indrelid :: REGCLASS)) AS table_name,
i.relname AS index_name,
pg_get_indexdef(i.oid) as ddl,
idx.indisunique AS is_unique,
idx.indisprimary AS is_primary,
am.amname AS index_type,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, TRUE)
FROM
generate_subscripts(idx.indkey, 1) AS k
ORDER BY k
) AS index_keys,
(idx.indexprs IS NOT NULL) OR (idx.indkey::int[] @> array[0]) AS is_functional,
idx.indpred IS NOT NULL AS is_partial
FROM pg_index AS idx
JOIN pg_class AS i
ON i.oid = idx.indexrelid
JOIN pg_am AS am
ON i.relam = am.oid
JOIN pg_namespace AS NS ON i.relnamespace = NS.OID
JOIN pg_user AS U ON i.relowner = U.usesysid
WHERE NOT nspname LIKE 'pg%' AND i.relname like 'mt_%'; -- Excluding system table
";
Func<DbDataReader, ActualIndex> transform =
r => new ActualIndex(DbObjectName.Parse(r.GetString(2)), r.GetString(3), r.GetString(4));
return _tenant.Fetch(sql, transform);
}
public IEnumerable<ActualIndex> IndexesFor(DbObjectName table)
{
return AllIndexes().Where(x => x.Table.Equals(table)).ToArray();
}
public FunctionBody DefinitionForFunction(DbObjectName function)
{
var sql = @"
SELECT pg_get_functiondef(pg_proc.oid)
FROM pg_proc JOIN pg_namespace as ns ON pg_proc.pronamespace = ns.oid WHERE ns.nspname = :schema and proname = :function;
SELECT format('DROP FUNCTION %s.%s(%s);'
,n.nspname
,p.proname
,pg_get_function_identity_arguments(p.oid))
FROM pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE p.proname = :function
AND n.nspname = :schema;
";
using (var conn = _tenant.CreateConnection())
{
conn.Open();
try
{
var cmd = conn.CreateCommand().Sql(sql)
.With("schema", function.Schema)
.With("function", function.Name);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read()) return null;
var definition = reader.GetString(0);
reader.NextResult();
var drops = new List<string>();
while (reader.Read())
{
drops.Add(reader.GetString(0));
}
return new FunctionBody(function, drops.ToArray(), definition);
}
}
finally
{
conn.Close();
}
}
}
public ForeignKeyConstraint[] AllForeignKeys()
{
Func<DbDataReader, ForeignKeyConstraint> reader = r => new ForeignKeyConstraint(r.GetString(0), r.GetString(1), r.GetString(2));
var sql =
"select constraint_name, constraint_schema, table_name from information_schema.table_constraints where constraint_name LIKE 'mt_%' and constraint_type = 'FOREIGN KEY'";
return _tenant.Fetch(sql, reader).ToArray();
}
public Table ExistingTableFor(Type type)
{
var mapping = _features.MappingFor(type).As<DocumentMapping>();
var expected = new DocumentTable(mapping);
using (var conn = _tenant.CreateConnection())
{
conn.Open();
return expected.FetchExisting(conn);
}
}
private IEnumerable<TableColumn> findTableColumns(IDocumentMapping documentMapping)
{
Func<DbDataReader, TableColumn> transform = r => new TableColumn(r.GetString(0), r.GetString(1));
var sql =
"select column_name, data_type from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position";
return _tenant.Fetch(sql, transform, documentMapping.Table.Schema, documentMapping.Table.Name);
}
private string[] primaryKeysFor(IDocumentMapping documentMapping)
{
var sql = @"
select a.attname, format_type(a.atttypid, a.atttypmod) as data_type
from pg_index i
join pg_attribute a on a.attrelid = i.indrelid and a.attnum = ANY(i.indkey)
where attrelid = (select pg_class.oid
from pg_class
join pg_catalog.pg_namespace n ON n.oid = pg_class.relnamespace
where n.nspname = ? and relname = ?)
and i.indisprimary;
";
return _tenant.GetStringList(sql, documentMapping.Table.Schema, documentMapping.Table.Name).ToArray();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
{
private enum Operation
{
Add,
Set,
Remove,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedDictionary<int, bool>();
var actual = ImmutableSortedDictionary<int, bool>.Empty;
int seed = (int)DateTime.Now.Ticks;
Console.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int key;
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
bool value = random.Next() % 2 == 0;
Console.WriteLine("Adding \"{0}\"={1} to the set.", key, value);
expected.Add(key, value);
actual = actual.Add(key, value);
break;
case Operation.Set:
bool overwrite = expected.Count > 0 && random.Next() % 2 == 0;
if (overwrite)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
}
else
{
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
}
value = random.Next() % 2 == 0;
Console.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite);
expected[key] = value;
actual = actual.SetItem(key, value);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
Console.WriteLine("Removing element \"{0}\" from the set.", key);
Assert.True(expected.Remove(key));
actual = actual.Remove(key);
}
break;
}
Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void ToUnorderedTest()
{
var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n))));
var unsortedMap = sortedMap.ToImmutableDictionary();
Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap);
Assert.Equal(sortedMap.Count, unsortedMap.Count);
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList());
}
[Fact]
public void SortChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void InitialBulkAddUniqueTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("c", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(2, actual.Count);
}
[Fact]
public void InitialBulkAddWithExactDuplicatesTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "b"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(1, actual.Count);
}
[Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void InitialBulkAddWithKeyCollisionTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
Assert.Throws<ArgumentException>(() => map.AddRange(uniqueEntries));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
var dictionary = ImmutableSortedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void ToImmutableSortedDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void WithComparers()
{
var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(Comparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
var cultureComparer = StringComparer.CurrentCulture;
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(cultureComparer, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(() => map.WithComparers(StringComparer.OrdinalIgnoreCase));
// Force all values to be considered equal.
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(EverythingEqual<string>.Default, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersEmptyCollection()
{
var map = ImmutableSortedDictionary.Create<string, string>();
Assert.Same(Comparer<string>.Default, map.KeyComparer);
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance()
{
var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k);
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
File.AppendAllText(Environment.ExpandEnvironmentVariables(@"%TEMP%\timing.txt"), string.Join(Environment.NewLine, timing));
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance_Empty()
{
var dictionary = ImmutableSortedDictionary<int, int>.Empty;
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
File.AppendAllText(Environment.ExpandEnvironmentVariables(@"%TEMP%\timing_empty.txt"), string.Join(Environment.NewLine, timing));
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSortedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer;
}
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using OpenHome.Net.Core;
using OpenHome.Net.ControlPoint;
namespace OpenHome.Net.ControlPoint.Proxies
{
public interface ICpProxyLinnCoUkFlash1 : ICpProxy, IDisposable
{
void SyncRead(uint aId, uint aAddress, uint aLength, out byte[] aBuffer);
void BeginRead(uint aId, uint aAddress, uint aLength, CpProxy.CallbackAsyncComplete aCallback);
void EndRead(IntPtr aAsyncHandle, out byte[] aBuffer);
void SyncWrite(uint aId, uint aAddress, byte[] aSource);
void BeginWrite(uint aId, uint aAddress, byte[] aSource, CpProxy.CallbackAsyncComplete aCallback);
void EndWrite(IntPtr aAsyncHandle);
void SyncErase(uint aId, uint aAddress);
void BeginErase(uint aId, uint aAddress, CpProxy.CallbackAsyncComplete aCallback);
void EndErase(IntPtr aAsyncHandle);
void SyncEraseSector(uint aId, uint aSector);
void BeginEraseSector(uint aId, uint aSector, CpProxy.CallbackAsyncComplete aCallback);
void EndEraseSector(IntPtr aAsyncHandle);
void SyncEraseSectors(uint aId, uint aFirstSector, uint aLastSector);
void BeginEraseSectors(uint aId, uint aFirstSector, uint aLastSector, CpProxy.CallbackAsyncComplete aCallback);
void EndEraseSectors(IntPtr aAsyncHandle);
void SyncEraseChip(uint aId);
void BeginEraseChip(uint aId, CpProxy.CallbackAsyncComplete aCallback);
void EndEraseChip(IntPtr aAsyncHandle);
void SyncSectors(uint aId, out uint aSectors);
void BeginSectors(uint aId, CpProxy.CallbackAsyncComplete aCallback);
void EndSectors(IntPtr aAsyncHandle, out uint aSectors);
void SyncSectorBytes(uint aId, out uint aBytes);
void BeginSectorBytes(uint aId, CpProxy.CallbackAsyncComplete aCallback);
void EndSectorBytes(IntPtr aAsyncHandle, out uint aBytes);
void SyncRomDirInfo(out uint aFlashIdMain, out uint aOffsetMain, out uint aBytesMain, out uint aFlashIdFallback, out uint aOffsetFallback, out uint aBytesFallback);
void BeginRomDirInfo(CpProxy.CallbackAsyncComplete aCallback);
void EndRomDirInfo(IntPtr aAsyncHandle, out uint aFlashIdMain, out uint aOffsetMain, out uint aBytesMain, out uint aFlashIdFallback, out uint aOffsetFallback, out uint aBytesFallback);
}
internal class SyncReadLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
private byte[] iBuffer;
public SyncReadLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
public byte[] Buffer()
{
return iBuffer;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndRead(aAsyncHandle, out iBuffer);
}
};
internal class SyncWriteLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
public SyncWriteLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndWrite(aAsyncHandle);
}
};
internal class SyncEraseLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
public SyncEraseLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndErase(aAsyncHandle);
}
};
internal class SyncEraseSectorLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
public SyncEraseSectorLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndEraseSector(aAsyncHandle);
}
};
internal class SyncEraseSectorsLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
public SyncEraseSectorsLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndEraseSectors(aAsyncHandle);
}
};
internal class SyncEraseChipLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
public SyncEraseChipLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndEraseChip(aAsyncHandle);
}
};
internal class SyncSectorsLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
private uint iSectors;
public SyncSectorsLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
public uint Sectors()
{
return iSectors;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndSectors(aAsyncHandle, out iSectors);
}
};
internal class SyncSectorBytesLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
private uint iBytes;
public SyncSectorBytesLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
public uint Bytes()
{
return iBytes;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndSectorBytes(aAsyncHandle, out iBytes);
}
};
internal class SyncRomDirInfoLinnCoUkFlash1 : SyncProxyAction
{
private CpProxyLinnCoUkFlash1 iService;
private uint iFlashIdMain;
private uint iOffsetMain;
private uint iBytesMain;
private uint iFlashIdFallback;
private uint iOffsetFallback;
private uint iBytesFallback;
public SyncRomDirInfoLinnCoUkFlash1(CpProxyLinnCoUkFlash1 aProxy)
{
iService = aProxy;
}
public uint FlashIdMain()
{
return iFlashIdMain;
}
public uint OffsetMain()
{
return iOffsetMain;
}
public uint BytesMain()
{
return iBytesMain;
}
public uint FlashIdFallback()
{
return iFlashIdFallback;
}
public uint OffsetFallback()
{
return iOffsetFallback;
}
public uint BytesFallback()
{
return iBytesFallback;
}
protected override void CompleteRequest(IntPtr aAsyncHandle)
{
iService.EndRomDirInfo(aAsyncHandle, out iFlashIdMain, out iOffsetMain, out iBytesMain, out iFlashIdFallback, out iOffsetFallback, out iBytesFallback);
}
};
/// <summary>
/// Proxy for the linn.co.uk:Flash:1 UPnP service
/// </summary>
public class CpProxyLinnCoUkFlash1 : CpProxy, IDisposable, ICpProxyLinnCoUkFlash1
{
private OpenHome.Net.Core.Action iActionRead;
private OpenHome.Net.Core.Action iActionWrite;
private OpenHome.Net.Core.Action iActionErase;
private OpenHome.Net.Core.Action iActionEraseSector;
private OpenHome.Net.Core.Action iActionEraseSectors;
private OpenHome.Net.Core.Action iActionEraseChip;
private OpenHome.Net.Core.Action iActionSectors;
private OpenHome.Net.Core.Action iActionSectorBytes;
private OpenHome.Net.Core.Action iActionRomDirInfo;
/// <summary>
/// Constructor
/// </summary>
/// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks>
/// <param name="aDevice">The device to use</param>
public CpProxyLinnCoUkFlash1(ICpDevice aDevice)
: base("linn-co-uk", "Flash", 1, aDevice)
{
OpenHome.Net.Core.Parameter param;
iActionRead = new OpenHome.Net.Core.Action("Read");
param = new ParameterUint("aId");
iActionRead.AddInputParameter(param);
param = new ParameterUint("aAddress");
iActionRead.AddInputParameter(param);
param = new ParameterUint("aLength");
iActionRead.AddInputParameter(param);
param = new ParameterBinary("aBuffer");
iActionRead.AddOutputParameter(param);
iActionWrite = new OpenHome.Net.Core.Action("Write");
param = new ParameterUint("aId");
iActionWrite.AddInputParameter(param);
param = new ParameterUint("aAddress");
iActionWrite.AddInputParameter(param);
param = new ParameterBinary("aSource");
iActionWrite.AddInputParameter(param);
iActionErase = new OpenHome.Net.Core.Action("Erase");
param = new ParameterUint("aId");
iActionErase.AddInputParameter(param);
param = new ParameterUint("aAddress");
iActionErase.AddInputParameter(param);
iActionEraseSector = new OpenHome.Net.Core.Action("EraseSector");
param = new ParameterUint("aId");
iActionEraseSector.AddInputParameter(param);
param = new ParameterUint("aSector");
iActionEraseSector.AddInputParameter(param);
iActionEraseSectors = new OpenHome.Net.Core.Action("EraseSectors");
param = new ParameterUint("aId");
iActionEraseSectors.AddInputParameter(param);
param = new ParameterUint("aFirstSector");
iActionEraseSectors.AddInputParameter(param);
param = new ParameterUint("aLastSector");
iActionEraseSectors.AddInputParameter(param);
iActionEraseChip = new OpenHome.Net.Core.Action("EraseChip");
param = new ParameterUint("aId");
iActionEraseChip.AddInputParameter(param);
iActionSectors = new OpenHome.Net.Core.Action("Sectors");
param = new ParameterUint("aId");
iActionSectors.AddInputParameter(param);
param = new ParameterUint("aSectors");
iActionSectors.AddOutputParameter(param);
iActionSectorBytes = new OpenHome.Net.Core.Action("SectorBytes");
param = new ParameterUint("aId");
iActionSectorBytes.AddInputParameter(param);
param = new ParameterUint("aBytes");
iActionSectorBytes.AddOutputParameter(param);
iActionRomDirInfo = new OpenHome.Net.Core.Action("RomDirInfo");
param = new ParameterUint("aFlashIdMain");
iActionRomDirInfo.AddOutputParameter(param);
param = new ParameterUint("aOffsetMain");
iActionRomDirInfo.AddOutputParameter(param);
param = new ParameterUint("aBytesMain");
iActionRomDirInfo.AddOutputParameter(param);
param = new ParameterUint("aFlashIdFallback");
iActionRomDirInfo.AddOutputParameter(param);
param = new ParameterUint("aOffsetFallback");
iActionRomDirInfo.AddOutputParameter(param);
param = new ParameterUint("aBytesFallback");
iActionRomDirInfo.AddOutputParameter(param);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aAddress"></param>
/// <param name="aLength"></param>
/// <param name="aBuffer"></param>
public void SyncRead(uint aId, uint aAddress, uint aLength, out byte[] aBuffer)
{
SyncReadLinnCoUkFlash1 sync = new SyncReadLinnCoUkFlash1(this);
BeginRead(aId, aAddress, aLength, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aBuffer = sync.Buffer();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndRead().</remarks>
/// <param name="aId"></param>
/// <param name="aAddress"></param>
/// <param name="aLength"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginRead(uint aId, uint aAddress, uint aLength, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionRead, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionRead.InputParameter(inIndex++), aId));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionRead.InputParameter(inIndex++), aAddress));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionRead.InputParameter(inIndex++), aLength));
int outIndex = 0;
invocation.AddOutput(new ArgumentBinary((ParameterBinary)iActionRead.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aBuffer"></param>
public void EndRead(IntPtr aAsyncHandle, out byte[] aBuffer)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aBuffer = Invocation.OutputBinary(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aAddress"></param>
/// <param name="aSource"></param>
public void SyncWrite(uint aId, uint aAddress, byte[] aSource)
{
SyncWriteLinnCoUkFlash1 sync = new SyncWriteLinnCoUkFlash1(this);
BeginWrite(aId, aAddress, aSource, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndWrite().</remarks>
/// <param name="aId"></param>
/// <param name="aAddress"></param>
/// <param name="aSource"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginWrite(uint aId, uint aAddress, byte[] aSource, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionWrite, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionWrite.InputParameter(inIndex++), aId));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionWrite.InputParameter(inIndex++), aAddress));
invocation.AddInput(new ArgumentBinary((ParameterBinary)iActionWrite.InputParameter(inIndex++), aSource));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
public void EndWrite(IntPtr aAsyncHandle)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aAddress"></param>
public void SyncErase(uint aId, uint aAddress)
{
SyncEraseLinnCoUkFlash1 sync = new SyncEraseLinnCoUkFlash1(this);
BeginErase(aId, aAddress, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndErase().</remarks>
/// <param name="aId"></param>
/// <param name="aAddress"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginErase(uint aId, uint aAddress, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionErase, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionErase.InputParameter(inIndex++), aId));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionErase.InputParameter(inIndex++), aAddress));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
public void EndErase(IntPtr aAsyncHandle)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aSector"></param>
public void SyncEraseSector(uint aId, uint aSector)
{
SyncEraseSectorLinnCoUkFlash1 sync = new SyncEraseSectorLinnCoUkFlash1(this);
BeginEraseSector(aId, aSector, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndEraseSector().</remarks>
/// <param name="aId"></param>
/// <param name="aSector"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginEraseSector(uint aId, uint aSector, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionEraseSector, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionEraseSector.InputParameter(inIndex++), aId));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionEraseSector.InputParameter(inIndex++), aSector));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
public void EndEraseSector(IntPtr aAsyncHandle)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aFirstSector"></param>
/// <param name="aLastSector"></param>
public void SyncEraseSectors(uint aId, uint aFirstSector, uint aLastSector)
{
SyncEraseSectorsLinnCoUkFlash1 sync = new SyncEraseSectorsLinnCoUkFlash1(this);
BeginEraseSectors(aId, aFirstSector, aLastSector, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndEraseSectors().</remarks>
/// <param name="aId"></param>
/// <param name="aFirstSector"></param>
/// <param name="aLastSector"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginEraseSectors(uint aId, uint aFirstSector, uint aLastSector, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionEraseSectors, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionEraseSectors.InputParameter(inIndex++), aId));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionEraseSectors.InputParameter(inIndex++), aFirstSector));
invocation.AddInput(new ArgumentUint((ParameterUint)iActionEraseSectors.InputParameter(inIndex++), aLastSector));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
public void EndEraseSectors(IntPtr aAsyncHandle)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
public void SyncEraseChip(uint aId)
{
SyncEraseChipLinnCoUkFlash1 sync = new SyncEraseChipLinnCoUkFlash1(this);
BeginEraseChip(aId, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndEraseChip().</remarks>
/// <param name="aId"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginEraseChip(uint aId, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionEraseChip, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionEraseChip.InputParameter(inIndex++), aId));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
public void EndEraseChip(IntPtr aAsyncHandle)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aSectors"></param>
public void SyncSectors(uint aId, out uint aSectors)
{
SyncSectorsLinnCoUkFlash1 sync = new SyncSectorsLinnCoUkFlash1(this);
BeginSectors(aId, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aSectors = sync.Sectors();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndSectors().</remarks>
/// <param name="aId"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginSectors(uint aId, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionSectors, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionSectors.InputParameter(inIndex++), aId));
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionSectors.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aSectors"></param>
public void EndSectors(IntPtr aAsyncHandle, out uint aSectors)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aSectors = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aId"></param>
/// <param name="aBytes"></param>
public void SyncSectorBytes(uint aId, out uint aBytes)
{
SyncSectorBytesLinnCoUkFlash1 sync = new SyncSectorBytesLinnCoUkFlash1(this);
BeginSectorBytes(aId, sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aBytes = sync.Bytes();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndSectorBytes().</remarks>
/// <param name="aId"></param>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginSectorBytes(uint aId, CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionSectorBytes, aCallback);
int inIndex = 0;
invocation.AddInput(new ArgumentUint((ParameterUint)iActionSectorBytes.InputParameter(inIndex++), aId));
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionSectorBytes.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aBytes"></param>
public void EndSectorBytes(IntPtr aAsyncHandle, out uint aBytes)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aBytes = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Invoke the action synchronously
/// </summary>
/// <remarks>Blocks until the action has been processed
/// on the device and sets any output arguments</remarks>
/// <param name="aFlashIdMain"></param>
/// <param name="aOffsetMain"></param>
/// <param name="aBytesMain"></param>
/// <param name="aFlashIdFallback"></param>
/// <param name="aOffsetFallback"></param>
/// <param name="aBytesFallback"></param>
public void SyncRomDirInfo(out uint aFlashIdMain, out uint aOffsetMain, out uint aBytesMain, out uint aFlashIdFallback, out uint aOffsetFallback, out uint aBytesFallback)
{
SyncRomDirInfoLinnCoUkFlash1 sync = new SyncRomDirInfoLinnCoUkFlash1(this);
BeginRomDirInfo(sync.AsyncComplete());
sync.Wait();
sync.ReportError();
aFlashIdMain = sync.FlashIdMain();
aOffsetMain = sync.OffsetMain();
aBytesMain = sync.BytesMain();
aFlashIdFallback = sync.FlashIdFallback();
aOffsetFallback = sync.OffsetFallback();
aBytesFallback = sync.BytesFallback();
}
/// <summary>
/// Invoke the action asynchronously
/// </summary>
/// <remarks>Returns immediately and will run the client-specified callback when the action
/// later completes. Any output arguments can then be retrieved by calling
/// EndRomDirInfo().</remarks>
/// <param name="aCallback">Delegate to run when the action completes.
/// This is guaranteed to be run but may indicate an error</param>
public void BeginRomDirInfo(CallbackAsyncComplete aCallback)
{
Invocation invocation = iService.Invocation(iActionRomDirInfo, aCallback);
int outIndex = 0;
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRomDirInfo.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRomDirInfo.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRomDirInfo.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRomDirInfo.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRomDirInfo.OutputParameter(outIndex++)));
invocation.AddOutput(new ArgumentUint((ParameterUint)iActionRomDirInfo.OutputParameter(outIndex++)));
iService.InvokeAction(invocation);
}
/// <summary>
/// Retrieve the output arguments from an asynchronously invoked action.
/// </summary>
/// <remarks>This may only be called from the callback set in the above Begin function.</remarks>
/// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param>
/// <param name="aFlashIdMain"></param>
/// <param name="aOffsetMain"></param>
/// <param name="aBytesMain"></param>
/// <param name="aFlashIdFallback"></param>
/// <param name="aOffsetFallback"></param>
/// <param name="aBytesFallback"></param>
public void EndRomDirInfo(IntPtr aAsyncHandle, out uint aFlashIdMain, out uint aOffsetMain, out uint aBytesMain, out uint aFlashIdFallback, out uint aOffsetFallback, out uint aBytesFallback)
{
uint code;
string desc;
if (Invocation.Error(aAsyncHandle, out code, out desc))
{
throw new ProxyError(code, desc);
}
uint index = 0;
aFlashIdMain = Invocation.OutputUint(aAsyncHandle, index++);
aOffsetMain = Invocation.OutputUint(aAsyncHandle, index++);
aBytesMain = Invocation.OutputUint(aAsyncHandle, index++);
aFlashIdFallback = Invocation.OutputUint(aAsyncHandle, index++);
aOffsetFallback = Invocation.OutputUint(aAsyncHandle, index++);
aBytesFallback = Invocation.OutputUint(aAsyncHandle, index++);
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public void Dispose()
{
lock (this)
{
if (iHandle == IntPtr.Zero)
return;
DisposeProxy();
iHandle = IntPtr.Zero;
}
iActionRead.Dispose();
iActionWrite.Dispose();
iActionErase.Dispose();
iActionEraseSector.Dispose();
iActionEraseSectors.Dispose();
iActionEraseChip.Dispose();
iActionSectors.Dispose();
iActionSectorBytes.Dispose();
iActionRomDirInfo.Dispose();
}
}
}
| |
using Fan.Blog.Enums;
using Fan.Blog.Helpers;
using Fan.Blog.Models;
using Fan.Blog.Models.Input;
using Fan.Blog.Models.View;
using Fan.Blog.Services;
using Fan.Blog.Services.Interfaces;
using Fan.Exceptions;
using Fan.Membership;
using Fan.Settings;
using Fan.Themes;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Fan.WebApp.Manage.Admin.Compose
{
/// <summary>
/// Page composer.
/// </summary>
public class PageModel : Microsoft.AspNetCore.Mvc.RazorPages.PageModel
{
private const string DATE_FORMAT = "yyyy-MM-dd";
private readonly UserManager<User> userManager;
private readonly IPageService pageService;
private readonly IThemeService themeService;
private readonly ISettingService settingService;
public const int AUTOSAVE_INTERVAL = 10;
public string PageJson { get; set; }
public string LayoutsJson { get; set; }
public string Theme { get; set; }
public PageModel(UserManager<User> userManager,
IPageService pageService,
IThemeService themeService,
ISettingService settingService)
{
this.userManager = userManager;
this.pageService = pageService;
this.themeService = themeService;
this.settingService = settingService;
}
/// <summary>
/// Prepares a <see cref="PageIM"/> for composer to work with.
/// </summary>
/// <param name="pageId"></param>
/// <param name="parentId"></param>
/// <returns></returns>
/// <remarks>
/// When <paramref name="pageId"/> is present (greater than 0), the user is updating an exisiting page,
/// in this situation the <paramref name="parentId"/> is ignored as it is not part of the update.
/// </remarks>
public async Task<IActionResult> OnGetAsync(int pageId, int? parentId)
{
var coreSettings = await settingService.GetSettingsAsync<CoreSettings>();
Theme = coreSettings.Theme;
Blog.Models.Page parent = null;
PageIM pageIM;
if (pageId > 0) // edit a page, ignore parentId
{
var page = await pageService.GetAsync(pageId);
if (page.ParentId.HasValue && page.ParentId > 0)
{
parent = await pageService.GetAsync(page.ParentId.Value);
}
// convert utc to user local time
var postDate = page.CreatedOn.ToLocalTime(coreSettings.TimeZoneId).ToString(DATE_FORMAT);
pageIM = new PageIM
{
Id = page.Id,
BodyMark = page.BodyMark,
DraftDate = page.UpdatedOn.HasValue ? page.UpdatedOn.Value.ToString(DATE_FORMAT) : "",
Excerpt = page.Excerpt,
IsDraft = page.Status == EPostStatus.Draft,
IsParentDraft = parent != null ? parent.Status == EPostStatus.Draft : false,
ParentId = page.ParentId,
PostDate = postDate,
Published = page.Status == EPostStatus.Published,
Title = page.Title,
PageLayout = (EPageLayout) page.PageLayout,
};
}
else // new post
{
if (parentId.HasValue && parentId > 0)
{
parent = await pageService.GetAsync(parentId.Value);
if (!parent.IsParent) return Redirect("/admin/pages"); // make sure parent is really parent
}
// convert utc to user local time
var date = DateTimeOffset.UtcNow.ToLocalTime(coreSettings.TimeZoneId).ToString(DATE_FORMAT);
pageIM = new PageIM
{
Title = "",
BodyMark = "",
PostDate = date,
ParentId = parentId,
Published = false,
IsDraft = false,
IsParentDraft = parent != null ? parent.Status == EPostStatus.Draft : false,
PageLayout = parent != null ? (EPageLayout) parent.PageLayout : EPageLayout.Layout1,
};
}
PageJson = JsonConvert.SerializeObject(pageIM);
// layouts
var currentTheme = (await themeService.GetManifestsAsync())
.Single(t => t.Name.Equals(coreSettings.Theme, StringComparison.OrdinalIgnoreCase));
LayoutsJson = JsonConvert.SerializeObject(currentTheme.PageLayouts);
return Page();
}
/// <summary>
/// Publishes a post.
/// </summary>
/// <returns>
/// Absolute URL to the post.
/// </returns>
/// <remarks>
/// The post could be new or previously published.
/// </remarks>
public async Task<IActionResult> OnPostPublishAsync([FromBody]PageIM pageIM)
{
try
{
var page = new Blog.Models.Page
{
UserId = Convert.ToInt32(userManager.GetUserId(HttpContext.User)),
ParentId = pageIM.ParentId,
CreatedOn = BlogUtil.GetCreatedOn(pageIM.PostDate),
Title = pageIM.Title,
Body = pageIM.Body,
BodyMark = pageIM.BodyMark,
Excerpt = pageIM.Excerpt,
Status = EPostStatus.Published,
PageLayout = (byte) pageIM.PageLayout,
};
if (pageIM.Id <= 0)
{
page = await pageService.CreateAsync(page);
}
else
{
page.Id = pageIM.Id;
page = await pageService.UpdateAsync(page);
}
return new JsonResult(GetPostAbsoluteUrl(page));
}
catch (FanException ex)
{
return BadRequest(ex.Message);
}
}
/// <summary>
/// Updates an existing published post.
/// </summary>
/// <returns>
/// Absolute URL to the post.
/// </returns>
public async Task<IActionResult> OnPostUpdateAsync([FromBody]PageIM pageIM)
{
try
{
var page = new Blog.Models.Page
{
Id = pageIM.Id,
UserId = Convert.ToInt32(userManager.GetUserId(HttpContext.User)),
ParentId = pageIM.ParentId,
CreatedOn = BlogUtil.GetCreatedOn(pageIM.PostDate),
Title = pageIM.Title,
Body = pageIM.Body,
BodyMark = pageIM.BodyMark,
Excerpt = pageIM.Excerpt,
Status = EPostStatus.Published,
PageLayout = (byte) pageIM.PageLayout,
};
page = await pageService.UpdateAsync(page);
return new JsonResult(GetPostAbsoluteUrl(page));
}
catch (FanException ex)
{
return BadRequest(ex.Message);
}
}
/// <summary>
/// Saves a page as draft.
/// </summary>
/// <returns>
/// The updated <see cref="BlogPost"/>.
/// </returns>
/// <remarks>
/// This is called by either Auto Save or user clicking on Save.
/// </remarks>
public async Task<IActionResult> OnPostSaveAsync([FromBody]PageIM pageIM)
{
try
{
// get page
var page = new Blog.Models.Page
{
UserId = Convert.ToInt32(userManager.GetUserId(HttpContext.User)),
ParentId = pageIM.ParentId,
CreatedOn = BlogUtil.GetCreatedOn(pageIM.PostDate),
Title = pageIM.Title,
Body = pageIM.Body,
BodyMark = pageIM.BodyMark,
Excerpt = pageIM.Excerpt,
Status = EPostStatus.Draft,
PageLayout = (byte) pageIM.PageLayout,
};
// create or update page
if (pageIM.Id <= 0)
{
page = await pageService.CreateAsync(page);
}
else
{
page.Id = pageIM.Id;
page = await pageService.UpdateAsync(page);
}
// return page
var coreSettings = await settingService.GetSettingsAsync<CoreSettings>();
pageIM = new PageIM
{
Id = page.Id,
Title = page.Title,
BodyMark = page.BodyMark,
Excerpt = page.Excerpt,
PostDate = page.CreatedOn.ToString(DATE_FORMAT),
ParentId = page.ParentId,
Published = page.Status == EPostStatus.Published,
IsDraft = page.Status == EPostStatus.Draft,
DraftDate = page.UpdatedOn.HasValue ? page.UpdatedOn.Value.ToDisplayString(coreSettings.TimeZoneId) : "",
PageLayout = (EPageLayout) page.PageLayout,
};
return new JsonResult(pageIM);
}
catch (FanException ex)
{
return BadRequest(ex.Message);
}
}
/// <summary>
/// Returns preview url.
/// </summary>
/// <param name="pageIM"></param>
/// <returns></returns>
public async Task<JsonResult> OnPostPreviewAsync([FromBody]PageIM pageIM)
{
// title
var title = pageIM.Title.IsNullOrEmpty() ? "Untitled" : pageIM.Title;
// slug
var slug = PageService.SlugifyPageTitle(title);
// parent slug
var parentSlug = "";
if (pageIM.ParentId.HasValue && pageIM.ParentId > 0)
{
var parent = await pageService.GetAsync(pageIM.ParentId.Value);
parentSlug = parent.Slug;
}
// body
var body = PageService.ParseNavLinks(pageIM.Body,
parentSlug.IsNullOrEmpty() ? slug : parentSlug);
// author
var user = await userManager.GetUserAsync(HttpContext.User);
var author = user.DisplayName;
// date
var coreSettings = await settingService.GetSettingsAsync<CoreSettings>();
var date = DateTimeOffset.Parse(pageIM.PostDate).ToDisplayString(coreSettings.TimeZoneId);
// layout
var pageLayout = pageIM.PageLayout;
// preview relative link (the slugs are url encoded)
var prevRelLink = parentSlug.IsNullOrEmpty() ?
BlogRoutes.GetPagePreviewRelativeLink(slug) :
BlogRoutes.GetPagePreviewRelativeLink(parentSlug, slug);
// put vm in tempdata with preview link as key
var pageVM = new PageVM
{
Author = author,
Body = body,
CreatedOnDisplay = date,
Title = title,
PageLayout = pageLayout,
};
TempData.Put(prevRelLink, pageVM);
// return preview url
return new JsonResult($"{Request.Scheme}://{Request.Host}{prevRelLink}");
}
private string GetPostAbsoluteUrl(Blog.Models.Page page)
{
var relativeUrl = page.IsParent ?
BlogRoutes.GetPageRelativeLink(page.Slug) :
BlogRoutes.GetPageRelativeLink(page.Parent.Slug, page.Slug);
return $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}{relativeUrl}";
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Roslyn.Utilities;
using ShellInterop = Microsoft.VisualStudio.Shell.Interop;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
using VsThreading = Microsoft.VisualStudio.Threading;
using Document = Microsoft.CodeAnalysis.Document;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue
{
internal sealed class VsENCRebuildableProjectImpl
{
private readonly AbstractProject _vsProject;
// number of projects that are in the debug state:
private static int s_debugStateProjectCount;
// number of projects that are in the break state:
private static int s_breakStateProjectCount;
// projects that entered the break state:
private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>();
// active statements of projects that entered the break state:
private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>();
private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker;
internal static readonly TraceLog log = new TraceLog(2048, "EnC");
private static Solution s_breakStateEntrySolution;
private static EncDebuggingSessionInfo s_encDebuggingSessionInfo;
private readonly IEditAndContinueWorkspaceService _encService;
private readonly IActiveStatementTrackingService _trackingService;
private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider;
private readonly IDebugEncNotify _debugEncNotify;
private readonly INotificationService _notifications;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
#region Per Project State
private bool _changesApplied;
// maps VS Active Statement Id, which is unique within this project, to our id
private Dictionary<uint, ActiveStatementId> _activeStatementIds;
private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
private HashSet<uint> _activeMethods;
private List<VsExceptionRegion> _exceptionRegions;
private EmitBaseline _committedBaseline;
private EmitBaseline _pendingBaseline;
private Project _projectBeingEmitted;
private ImmutableArray<DocumentId> _documentsWithEmitError = ImmutableArray<DocumentId>.Empty;
/// <summary>
/// Initialized when the project switches to debug state.
/// Null if the project has no output file or we can't read the MVID.
/// </summary>
private ModuleMetadata _metadata;
private Lazy<ISymUnmanagedReader3> _pdbReader;
#endregion
private bool IsDebuggable
{
get { return _metadata != null; }
}
internal VsENCRebuildableProjectImpl(AbstractProject project)
{
_vsProject = project;
_encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>();
_trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>();
_notifications = _vsProject.Workspace.Services.GetService<INotificationService>();
_debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel));
_diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>();
_editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
Debug.Assert(_encService != null);
Debug.Assert(_trackingService != null);
Debug.Assert(_diagnosticProvider != null);
Debug.Assert(_editorAdaptersFactoryService != null);
}
// called from an edit filter if an edit of a read-only buffer is attempted:
internal bool OnEdit(DocumentId documentId)
{
if (_encService.IsProjectReadOnly(documentId.ProjectId, out var sessionReason, out var projectReason))
{
OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason);
return true;
}
return false;
}
private void OnReadOnlyDocumentEditAttempt(
DocumentId documentId,
SessionReadOnlyReason sessionReason,
ProjectReadOnlyReason projectReason)
{
if (sessionReason == SessionReadOnlyReason.StoppedAtException)
{
_debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState();
return;
}
var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl;
var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractProject;
if (hostProject?.EditAndContinueImplOpt?._metadata != null)
{
_debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy);
return;
}
// NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586).
// TODO: localize messages https://github.com/dotnet/roslyn/issues/16656
string message;
if (sessionReason == SessionReadOnlyReason.Running)
{
message = "Changes are not allowed while code is running.";
}
else
{
Debug.Assert(sessionReason == SessionReadOnlyReason.None);
switch (projectReason)
{
case ProjectReadOnlyReason.MetadataNotAvailable:
// TODO: Remove once https://github.com/dotnet/roslyn/issues/16657 is addressed
bool deferredLoad = (_vsProject.ServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution7)?.IsSolutionLoadDeferred() == true;
if (deferredLoad)
{
message = "Changes are not allowed if the project wasn't loaded and built when debugging started." + Environment.NewLine +
Environment.NewLine +
"'Lightweight solution load' is enabled for the current solution. " +
"Disable it to ensure that all projects are loaded when debugging starts.";
s_encDebuggingSessionInfo?.LogReadOnlyEditAttemptedProjectNotBuiltOrLoaded();
}
else
{
message = "Changes are not allowed if the project wasn't built when debugging started.";
}
break;
case ProjectReadOnlyReason.NotLoaded:
message = "Changes are not allowed if the assembly has not been loaded.";
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectReason);
}
}
_notifications.SendNotification(message, title: FeaturesResources.Edit_and_Continue1, severity: NotificationSeverity.Error);
}
/// <summary>
/// Since we can't await asynchronous operations we need to wait for them to complete.
/// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to
/// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext
/// that doesn't pump messages. We need to make sure though that the async methods we wait for
/// don't dispatch to foreground thread, otherwise we would end up in a deadlock.
/// </summary>
private static VsThreading.SpecializedSyncContext NonReentrantContext
{
get
{
return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default);
}
}
public bool HasCustomMetadataEmitter()
{
return true;
}
/// <summary>
/// Invoked when the debugger transitions from Design mode to Run mode or Break mode.
/// </summary>
public int StartDebuggingPE()
{
try
{
log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid starting the debug session if it has already been started.
if (_encService.DebuggingSession == null)
{
Debug.Assert(s_debugStateProjectCount == 0);
Debug.Assert(s_breakStateProjectCount == 0);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run);
_encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution);
s_encDebuggingSessionInfo = new EncDebuggingSessionInfo();
s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject);
}
string outputPath = _vsProject.ObjOutputPath;
// The project doesn't produce a debuggable binary or we can't read it.
// Continue on since the debugger ignores HResults and we need to handle subsequent calls.
if (outputPath != null)
{
try
{
InjectFault_MvidRead();
_metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete));
_metadata.GetModuleVersionId();
}
catch (FileNotFoundException)
{
// If the project isn't referenced by the project being debugged it might not be built.
// In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state.
log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath);
_metadata = null;
}
catch (Exception e)
{
log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message);
_metadata = null;
var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.Error_while_reading_0_colon_1, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue);
_diagnosticProvider.ReportDiagnostics(
new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId),
_encService.DebuggingSession.InitialSolution,
_vsProject.Id,
new[] { Diagnostic.Create(descriptor, Location.None, outputPath, e.Message) });
}
}
else
{
log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName);
_metadata = null;
}
if (_metadata != null)
{
// The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID.
// However a project that's initially not loaded (but it might be in future) enters
// both the debug and break states.
s_debugStateProjectCount++;
}
_activeMethods = new HashSet<uint>();
_exceptionRegions = new List<VsExceptionRegion>();
_activeStatementIds = new Dictionary<uint, ActiveStatementId>();
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public int StopDebuggingPE()
{
try
{
log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName);
Debug.Assert(s_breakStateEnteredProjects.Count == 0);
// Clear the solution stored while projects were entering break mode.
// It should be cleared as soon as all tracked projects enter the break mode
// but if the entering break mode fails for some projects we should avoid leaking the solution.
Debug.Assert(s_breakStateEntrySolution == null);
s_breakStateEntrySolution = null;
// EnC service is global (per solution), but the debugger calls this for each project.
// Avoid ending the debug session if it has already been ended.
if (_encService.DebuggingSession != null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design);
_encService.EndDebuggingSession();
LogEncSession();
s_encDebuggingSessionInfo = null;
s_readOnlyDocumentTracker.Dispose();
s_readOnlyDocumentTracker = null;
}
if (_metadata != null)
{
_metadata.Dispose();
_metadata = null;
s_debugStateProjectCount--;
}
else
{
// an error might have been reported:
var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId);
_diagnosticProvider.ClearDiagnostics(errorId, _vsProject.Workspace.CurrentSolution, _vsProject.Id, documentIdOpt: null);
}
_activeMethods = null;
_exceptionRegions = null;
_committedBaseline = null;
_activeStatementIds = null;
_projectBeingEmitted = null;
var pdbReader = Interlocked.Exchange(ref _pdbReader, null);
if (pdbReader?.IsValueCreated == true)
{
var symReader = pdbReader.Value;
if (Marshal.IsComObject(symReader))
{
Marshal.ReleaseComObject(symReader);
}
}
// The HResult is ignored by the debugger.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static void LogEncSession()
{
var sessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo));
foreach (var editSession in s_encDebuggingSessionInfo.EditSessions)
{
var editSessionId = DebugLogMessage.GetNextId();
Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession));
if (editSession.EmitDeltaErrorIds != null)
{
foreach (var error in editSession.EmitDeltaErrorIds)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error));
}
}
foreach (var rudeEdit in editSession.RudeEdits)
{
Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits));
}
}
}
/// <summary>
/// Get MVID and file name of the project's output file.
/// </summary>
/// <remarks>
/// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project.
/// The path seems to be unused.
///
/// The output file path might be different from the path of the module loaded into the process.
/// For example, the binary produced by the C# compiler is stores in obj directory,
/// and then copied to bin directory from which it is loaded to the debuggee.
///
/// The binary produced by the compiler can also be rewritten by post-processing tools.
/// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session
/// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though.
/// </remarks>
public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName)
{
Debug.Assert(_encService.DebuggingSession != null);
if (_metadata == null)
{
return VSConstants.E_FAIL;
}
if (pMVID != null && pMVID.Length != 0)
{
pMVID[0] = _metadata.GetModuleVersionId();
}
if (pbstrPEName != null && pbstrPEName.Length != 0)
{
var outputPath = _vsProject.ObjOutputPath;
Debug.Assert(outputPath != null);
pbstrPEName[0] = Path.GetFileName(outputPath);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger when entering a Break state.
/// </summary>
/// <param name="encBreakReason">Reason for transition to Break state.</param>
/// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param>
/// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param>
public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements)
{
try
{
using (NonReentrantContext)
{
log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : "");
Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0));
Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount);
Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0);
Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count);
Debug.Assert(IsDebuggable);
if (s_breakStateEntrySolution == null)
{
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break);
s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution;
// TODO: This is a workaround for a debugger bug in which not all projects exit the break state.
// Reset the project count.
s_breakStateProjectCount = 0;
}
ProjectReadOnlyReason state;
if (pActiveStatements != null)
{
AddActiveStatements(s_breakStateEntrySolution, pActiveStatements);
state = ProjectReadOnlyReason.None;
}
else
{
// unfortunately the debugger doesn't provide details:
state = ProjectReadOnlyReason.NotLoaded;
}
// If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding
// to the project in the debuggee. We won't include such projects in the edit session.
s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state));
s_breakStateProjectCount++;
// EnC service is global, but the debugger calls this for each project.
// Avoid starting the edit session until all projects enter break state.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
Debug.Assert(_encService.EditSession == null);
Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0));
var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>();
// note: fills in activeStatementIds of projects that own the active statements:
GroupActiveStatements(s_pendingActiveStatements, byDocument);
// When stopped at exception: All documents are read-only, but the files might be changed outside of VS.
// So we start an edit session as usual and report a rude edit for all changes we see.
bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION;
var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects);
_encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException);
_trackingService.StartTracking(_encService.EditSession);
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
// When tracking is started the tagger is notified and the active statements are highlighted.
// Add the handler that notifies the debugger *after* that initial tagger notification,
// so that it's not triggered unless an actual change in leaf AS occurs.
_trackingService.TrackingSpansChanged += TrackingSpansChanged;
}
}
// The debugger ignores the result.
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
finally
{
// TODO: This is a workaround for a debugger bug.
// Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception.
if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount)
{
// we don't need these anymore:
s_pendingActiveStatements.Clear();
s_breakStateEnteredProjects.Clear();
s_breakStateEntrySolution = null;
}
}
}
private void TrackingSpansChanged(bool leafChanged)
{
//log.Write("Tracking spans changed: {0}", leafChanged);
//if (leafChanged)
//{
// // fire and forget:
// Application.Current.Dispatcher.InvokeAsync(() =>
// {
// log.Write("Notifying debugger of active statement change.");
// var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger));
// debugNotify.NotifyEncUpdateCurrentStatement();
// });
//}
}
private struct VsActiveStatement
{
public readonly DocumentId DocumentId;
public readonly uint StatementId;
public readonly ActiveStatementSpan Span;
public readonly VsENCRebuildableProjectImpl Owner;
public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span)
{
this.Owner = owner;
this.StatementId = statementId;
this.DocumentId = documentId;
this.Span = span;
}
}
private struct VsExceptionRegion
{
public readonly uint ActiveStatementId;
public readonly int Ordinal;
public readonly uint MethodToken;
public readonly LinePositionSpan Span;
public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span)
{
this.ActiveStatementId = activeStatementId;
this.Span = span;
this.MethodToken = methodToken;
this.Ordinal = ordinal;
}
}
// See InternalApis\vsl\inc\encbuild.idl
private const int TEXT_POSITION_ACTIVE_STATEMENT = 1;
private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements)
{
Debug.Assert(_activeMethods.Count == 0);
Debug.Assert(_exceptionRegions.Count == 0);
foreach (var vsActiveStatement in vsActiveStatements)
{
log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'",
unchecked((int)vsActiveStatement.id),
vsActiveStatement.tsPosition.iStartLine,
vsActiveStatement.tsPosition.iStartIndex,
vsActiveStatement.tsPosition.iEndLine,
vsActiveStatement.tsPosition.iEndIndex,
vsActiveStatement.filename);
// TODO (tomat):
// Active statement is in user hidden code. The only information that we have from the debugger
// is the method token. We don't need to track the statement (it's not in user code anyways),
// but we should probably track the list of such methods in order to preserve their local variables.
// Not sure what's exactly the scenario here, perhaps modifying async method/iterator?
// Dev12 just ignores these.
if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT)
{
continue;
}
var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO;
// Finds a document id in the solution with the specified file path.
DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename)
.Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault();
if (documentId != null)
{
var document = solution.GetDocument(documentId);
Debug.Assert(document != null);
SourceText source = document.GetTextAsync(default(CancellationToken)).Result;
LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan();
// If the PDB is out of sync with the source we might get bad spans.
var sourceLines = source.Lines;
if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak)
{
log.Write("AS out of bounds (line count is {0})", source.Lines.Count);
continue;
}
SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result;
var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>();
s_pendingActiveStatements.Add(new VsActiveStatement(
this,
vsActiveStatement.id,
document.Id,
new ActiveStatementSpan(flags, lineSpan)));
bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0;
var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf);
for (int i = 0; i < ehRegions.Length; i++)
{
_exceptionRegions.Add(new VsExceptionRegion(
vsActiveStatement.id,
i,
vsActiveStatement.methodToken,
ehRegions[i]));
}
}
_activeMethods.Add(vsActiveStatement.methodToken);
}
}
private static void GroupActiveStatements(
IEnumerable<VsActiveStatement> activeStatements,
Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument)
{
var spans = new List<ActiveStatementSpan>();
foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId))
{
var documentId = grouping.Key;
foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start))
{
int ordinal = spans.Count;
// register vsid with the project that owns the active statement:
activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal));
spans.Add(activeStatement.Span);
}
byDocument.Add(documentId, spans.AsImmutable());
spans.Clear();
}
}
/// <summary>
/// Returns the number of exception regions around current active statements.
/// This is called when the project is entering a break right after
/// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpanCount(out uint pcExceptionSpan)
{
pcExceptionSpan = (uint)_exceptionRegions.Count;
return VSConstants.S_OK;
}
/// <summary>
/// Returns information about exception handlers in the source.
/// </summary>
/// <remarks>
/// Called by EnC manager.
/// </remarks>
public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched)
{
Debug.Assert(celt == rgelt.Length);
Debug.Assert(celt == _exceptionRegions.Count);
for (int i = 0; i < _exceptionRegions.Count; i++)
{
rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN()
{
id = (uint)i,
methodToken = _exceptionRegions[i].MethodToken,
tsPosition = _exceptionRegions[i].Span.ToVsTextSpan()
};
}
pceltFetched = celt;
return VSConstants.S_OK;
}
/// <summary>
/// Called by the debugger whenever it needs to determine a position of an active statement.
/// E.g. the user clicks on a frame in a call stack.
/// </summary>
/// <remarks>
/// Called when applying change, when setting current IP, a notification is received from
/// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc.
/// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components.
/// </remarks>
public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
var session = _encService.EditSession;
var ids = _activeStatementIds;
// Can be called anytime, even outside of an edit/debug session.
// We might not have an active statement available if PDB got out of sync with the source.
if (session == null || ids == null || !ids.TryGetValue(vsId, out var id))
{
log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", unchecked((int)vsId));
return VSConstants.E_FAIL;
}
Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId);
SourceText text = document.GetTextAsync(default(CancellationToken)).Result;
LinePositionSpan lineSpan;
// Try to get spans from the tracking service first.
// We might get an imprecise result if the document analysis hasn't been finished yet and
// the active statement has structurally changed, but that's ok. The user won't see an updated tag
// for the statement until the analysis finishes anyways.
if (_trackingService.TryGetSpan(id, text, out var span) && span.Length > 0)
{
lineSpan = text.Lines.GetLinePositionSpan(span);
}
else
{
var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements;
if (activeSpans.IsDefault)
{
// The document has syntax errors and the tracking span is gone.
log.Write("Position not available for AS {0} due to syntax errors", unchecked((int)vsId));
return VSConstants.E_FAIL;
}
lineSpan = activeSpans[id.Ordinal];
}
ptsNewPosition[0] = lineSpan.ToVsTextSpan();
log.DebugWrite("AS position: {0} ({1},{2})-({3},{4}) {5}",
unchecked((int)vsId),
lineSpan.Start.Line, lineSpan.Start.Character, lineSpan.End.Line, lineSpan.End.Character,
(int)session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags);
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Returns the state of the changes made to the source.
/// The EnC manager calls this to determine whether there are any changes to the source
/// and if so whether there are any rude edits.
/// </summary>
public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1);
// GetENCBuildState is called outside of edit session (at least) in following cases:
// 1) when the debugger is determining whether a source file checksum matches the one in PDB.
// 2) when the debugger is setting the next statement and a change is pending
// See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange):
//
// pENC2->ExitBreakState();
// >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true);
// pENC2->EnterBreakState(m_pSession, GetEncBreakReason());
//
// The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur.
if (_changesApplied || _encService.EditSession == null)
{
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
}
else
{
// Fetch the latest snapshot of the project and get an analysis summary for any changes
// made since the break mode was entered.
var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id);
if (currentProject == null)
{
// If the project has yet to be loaded into the solution (which may be the case,
// since they are loaded on-demand), then it stands to reason that it has not yet
// been modified.
// TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary.
_lastEditSessionSummary = ProjectAnalysisSummary.NoChanges;
log.Write("Project '{0}' has not yet been loaded into the solution", _vsProject.DisplayName);
}
else
{
_projectBeingEmitted = currentProject;
_lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted);
}
_encService.EditSession.LogBuildState(_lastEditSessionSummary);
}
switch (_lastEditSessionSummary)
{
case ProjectAnalysisSummary.NoChanges:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED;
break;
case ProjectAnalysisSummary.CompilationErrors:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS;
break;
case ProjectAnalysisSummary.RudeEdits:
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS;
break;
case ProjectAnalysisSummary.ValidChanges:
case ProjectAnalysisSummary.ValidInsignificantChanges:
// The debugger doesn't distinguish between these two.
pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY;
break;
default:
throw ExceptionUtilities.UnexpectedValue(_lastEditSessionSummary);
}
log.Write("EnC state of '{0}' queried: {1}{2}",
_vsProject.DisplayName,
EncStateToString(pENCBuildState[0]),
_encService.EditSession != null ? "" : " (no session)");
return VSConstants.S_OK;
}
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static string EncStateToString(ENC_BUILD_STATE state)
{
switch (state)
{
case ENC_BUILD_STATE.ENC_NOT_MODIFIED: return "ENC_NOT_MODIFIED";
case ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS: return "ENC_NONCONTINUABLE_ERRORS";
case ENC_BUILD_STATE.ENC_COMPILE_ERRORS: return "ENC_COMPILE_ERRORS";
case ENC_BUILD_STATE.ENC_APPLY_READY: return "ENC_APPLY_READY";
default: return state.ToString();
}
}
private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project)
{
if (!IsDebuggable)
{
return ProjectAnalysisSummary.NoChanges;
}
var cancellationToken = default(CancellationToken);
return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result;
}
public int ExitBreakStateOnPE()
{
try
{
using (NonReentrantContext)
{
// The debugger calls Exit without previously calling Enter if the project's MVID isn't available.
if (!IsDebuggable)
{
return VSConstants.S_OK;
}
log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName);
// EnC service is global, but the debugger calls this for each project.
// Avoid ending the edit session if it has already been ended.
if (_encService.EditSession != null)
{
Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount);
_encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run);
_encService.EditSession.LogEditSession(s_encDebuggingSessionInfo);
_encService.EndEditSession();
_trackingService.EndTracking();
s_readOnlyDocumentTracker.UpdateWorkspaceDocuments();
_trackingService.TrackingSpansChanged -= TrackingSpansChanged;
}
_exceptionRegions.Clear();
_activeMethods.Clear();
_activeStatementIds.Clear();
s_breakStateProjectCount--;
Debug.Assert(s_breakStateProjectCount >= 0);
_changesApplied = false;
_diagnosticProvider.ClearDiagnostics(
new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId),
_vsProject.Workspace.CurrentSolution,
_vsProject.Id,
_documentsWithEmitError);
_documentsWithEmitError = ImmutableArray<DocumentId>.Empty;
}
// HResult ignored by the debugger
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
public unsafe int BuildForEnc(object pUpdatePE)
{
try
{
log.Write("Applying changes to {0}", _vsProject.DisplayName);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
// Non-debuggable project has no changes.
Debug.Assert(IsDebuggable);
if (_changesApplied)
{
log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName);
throw ExceptionUtilities.Unreachable;
}
// The debugger always calls GetENCBuildState right before BuildForEnc.
Debug.Assert(_projectBeingEmitted != null);
Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted));
// The debugger should have called GetENCBuildState before calling BuildForEnc.
// Unfortunately, there is no way how to tell the debugger that the changes were not significant,
// so we'll to emit an empty delta. See bug 839558.
Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges ||
_lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges);
var updater = (IDebugUpdateInMemoryPE2)pUpdatePE;
if (_committedBaseline == null)
{
var previousPdbReader = Interlocked.Exchange(ref _pdbReader, MarshalPdbReader(updater));
// PDB reader should have been nulled out when debugging stopped:
Contract.ThrowIfFalse(previousPdbReader == null);
_committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo);
}
// ISymUnmanagedReader can only be accessed from an MTA thread,
// so dispatch it to one of thread pool threads, which are MTA.
var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default);
Deltas delta;
using (NonReentrantContext)
{
delta = emitTask.Result;
if (delta == null)
{
// Non-fatal Watson has already been reported by the emit task
return VSConstants.E_FAIL;
}
}
var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId);
// Clear diagnostics, in case the project was built before and failed due to errors.
_diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, _documentsWithEmitError);
if (!delta.EmitResult.Success)
{
var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error);
_documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, errors);
_encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id));
return VSConstants.E_FAIL;
}
_documentsWithEmitError = ImmutableArray<DocumentId>.Empty;
SetFileUpdates(updater, delta.LineEdits);
updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length);
updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream));
updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length);
updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length);
_pendingBaseline = delta.EmitResult.Baseline;
#if DEBUG
fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0])
{
var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length);
var moduleDef = reader.GetModuleDefinition();
log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}",
moduleDef.Generation,
reader.GetGuid(moduleDef.Mvid).ToString(),
reader.GetGuid(moduleDef.BaseGenerationId).ToString(),
reader.GetGuid(moduleDef.GenerationId).ToString());
}
#endif
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private unsafe void SetFileUpdates(
IDebugUpdateInMemoryPE2 updater,
List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits)
{
int totalEditCount = edits.Sum(e => e.Value.Length);
if (totalEditCount == 0)
{
return;
}
var lineUpdates = new LINEUPDATE[totalEditCount];
fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates)
{
int index = 0;
var fileUpdates = new FILEUPDATE[edits.Count];
for (int f = 0; f < fileUpdates.Length; f++)
{
var documentId = edits[f].Key;
var deltas = edits[f].Value;
fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath;
fileUpdates[f].LineUpdateCount = (uint)deltas.Length;
fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index);
for (int l = 0; l < deltas.Length; l++)
{
lineUpdates[index + l].Line = (uint)deltas[l].OldLine;
lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine;
}
index += deltas.Length;
}
// The updater makes a copy of all data, we can release the buffer after the call.
updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length);
}
}
private Deltas EmitProjectDelta()
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken));
return emitTask.Result;
}
/// <summary>
/// Returns EnC debug information for initial version of the specified method.
/// </summary>
/// <exception cref="InvalidDataException">The debug information data is corrupt or can't be retrieved from the debugger.</exception>
private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle)
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
return GetEditAndContinueMethodDebugInfo(_pdbReader.Value, methodHandle);
}
// Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA).
private static ISymUnmanagedReader3 UnmarshalSymReader(IntPtr stream)
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA);
try
{
return (ISymUnmanagedReader3)NativeMethods.GetObjectAndRelease(stream);
}
catch (Exception exception) when (FatalError.ReportWithoutCrash(exception))
{
throw new InvalidDataException(exception.Message, exception);
}
}
private static EditAndContinueMethodDebugInformation GetEditAndContinueMethodDebugInfo(ISymUnmanagedReader3 symReader, MethodDefinitionHandle methodHandle)
{
return TryGetPortableEncDebugInfo(symReader, methodHandle, out var info) ? info : GetNativeEncDebugInfo(symReader, methodHandle);
}
private static unsafe bool TryGetPortableEncDebugInfo(ISymUnmanagedReader symReader, MethodDefinitionHandle methodHandle, out EditAndContinueMethodDebugInformation info)
{
if (!(symReader is ISymUnmanagedReader5 symReader5))
{
info = default(EditAndContinueMethodDebugInformation);
return false;
}
int hr = symReader5.GetPortableDebugMetadataByVersion(version: 1, metadata: out byte* metadata, size: out int size);
Marshal.ThrowExceptionForHR(hr);
if (hr != 0)
{
info = default(EditAndContinueMethodDebugInformation);
return false;
}
var pdbReader = new System.Reflection.Metadata.MetadataReader(metadata, size);
ImmutableArray<byte> GetCdiBytes(Guid kind) =>
TryGetCustomDebugInformation(pdbReader, methodHandle, kind, out var cdi) ? pdbReader.GetBlobContent(cdi.Value) : default(ImmutableArray<byte>);
info = EditAndContinueMethodDebugInformation.Create(
compressedSlotMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLocalSlotMap),
compressedLambdaMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap));
return true;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(System.Reflection.Metadata.MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
bool foundAny = false;
customDebugInfo = default(CustomDebugInformation);
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
private static EditAndContinueMethodDebugInformation GetNativeEncDebugInfo(ISymUnmanagedReader3 symReader, MethodDefinitionHandle methodHandle)
{
int methodToken = MetadataTokens.GetToken(methodHandle);
byte[] debugInfo;
try
{
debugInfo = symReader.GetCustomDebugInfo(methodToken, methodVersion: 1);
}
catch (ArgumentOutOfRangeException)
{
// Sometimes the debugger returns the HRESULT for ArgumentOutOfRangeException, rather than E_FAIL,
// for methods without custom debug info (https://github.com/dotnet/roslyn/issues/4138).
debugInfo = null;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger
{
throw new InvalidDataException(e.Message, e);
}
try
{
ImmutableArray<byte> localSlots, lambdaMap;
if (debugInfo != null)
{
localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap);
lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap);
}
else
{
localSlots = lambdaMap = default(ImmutableArray<byte>);
}
return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap);
}
catch (InvalidOperationException e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger
{
// TODO: CustomDebugInfoReader should throw InvalidDataException
throw new InvalidDataException(e.Message, e);
}
}
public int EncApplySucceeded(int hrApplyResult)
{
try
{
log.Write("Change applied to {0}", _vsProject.DisplayName);
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(_pendingBaseline != null);
// Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges.
_changesApplied = true;
_committedBaseline = _pendingBaseline;
_pendingBaseline = null;
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
/// <summary>
/// Called when changes are being applied.
/// </summary>
/// <param name="exceptionRegionId">
/// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>.
/// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>.
/// </param>
/// <param name="ptsNewPosition">Output value holder.</param>
public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition)
{
try
{
using (NonReentrantContext)
{
Debug.Assert(IsDebuggable);
Debug.Assert(_encService.EditSession != null);
Debug.Assert(!_encService.EditSession.StoppedAtException);
Debug.Assert(ptsNewPosition.Length == 1);
var exceptionRegion = _exceptionRegions[(int)exceptionRegionId];
var session = _encService.EditSession;
var asid = _activeStatementIds[exceptionRegion.ActiveStatementId];
var document = _projectBeingEmitted.GetDocument(asid.DocumentId);
var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken));
var regions = analysis.ExceptionRegions;
// the method shouldn't be called in presence of errors:
Debug.Assert(!analysis.HasChangesAndErrors);
Debug.Assert(!regions.IsDefault);
// Absence of rude edits guarantees that the exception regions around AS haven't semantically changed.
// Only their spans might have changed.
ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan();
}
return VSConstants.S_OK;
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
return VSConstants.E_FAIL;
}
}
private static Lazy<ISymUnmanagedReader3> MarshalPdbReader(IDebugUpdateInMemoryPE2 updater)
{
// ISymUnmanagedReader can only be accessed from an MTA thread, however, we need
// fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here
// in the STA. To further complicate things, we need to return synchronously from
// this method. Waiting for the MTA thread to complete so we can return synchronously
// blocks the STA thread, so we need to make sure the CLR doesn't try to marshal
// ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this
// happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to
// achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer
// over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal
// the object. The reader object was originally created on an MTA thread, and the
// instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the
// MTA, it "unwraps" the proxy, allowing us to directly call the implementation.
// Another way to achieve this would be for the symbol reader to implement IAgileObject,
// but the symbol reader we use today does not. If that changes, we should consider
// removing this marshal/unmarshal code.
updater.GetENCDebugInfo(out IENCDebugInfo debugInfo);
var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo;
symbolReaderProvider.GetSymbolReader(out object pdbReaderObjSta);
if (Marshal.IsComObject(pdbReaderObjSta))
{
int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out IntPtr stream);
Marshal.ReleaseComObject(pdbReaderObjSta);
Marshal.ThrowExceptionForHR(hr);
return new Lazy<ISymUnmanagedReader3>(() => UnmarshalSymReader(stream));
}
else
{
var managedSymReader = (ISymUnmanagedReader3)pdbReaderObjSta;
return new Lazy<ISymUnmanagedReader3>(() => managedSymReader);
}
}
#region Testing
#if DEBUG
// Fault injection:
// If set we'll fail to read MVID of specified projects to test error reporting.
internal static ImmutableArray<string> InjectMvidReadingFailure;
private void InjectFault_MvidRead()
{
if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName))
{
throw new IOException("Fault injection");
}
}
#else
[Conditional("DEBUG")]
private void InjectFault_MvidRead()
{
}
#endif
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Shared;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectItemDefinitionElement class
/// </summary>
public class ProjectItemDefinitionElement_Tests
{
/// <summary>
/// Read item definition with no children
/// </summary>
[Fact]
public void ReadNoChildren()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i/>
</ItemDefinitionGroup>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectItemDefinitionGroupElement itemDefinitionGroup = (ProjectItemDefinitionGroupElement)Helpers.GetFirst(project.Children);
ProjectItemDefinitionElement itemDefinition = Helpers.GetFirst(itemDefinitionGroup.ItemDefinitions);
Assert.Equal(0, Helpers.Count(itemDefinition.Metadata));
}
/// <summary>
/// Read an item definition with a child
/// </summary>
[Fact]
public void ReadBasic()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m1>v1</m1>
</i>
</ItemDefinitionGroup>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectItemDefinitionGroupElement itemDefinitionGroup = (ProjectItemDefinitionGroupElement)Helpers.GetFirst(project.Children);
ProjectItemDefinitionElement definition = Helpers.GetFirst(itemDefinitionGroup.ItemDefinitions);
Assert.Equal("i", definition.ItemType);
Assert.Equal(1, Helpers.Count(definition.Metadata));
Assert.Equal("m1", Helpers.GetFirst(definition.Metadata).Name);
Assert.Equal("v1", Helpers.GetFirst(definition.Metadata).Value);
}
/// <summary>
/// Read item with reserved element name
/// </summary>
/// <remarks>
/// Orcas inadvertently did not check for reserved item types (like "Choose") in item definitions,
/// as we do for item types in item groups. So we do not fail here.
/// </remarks>
[Fact]
public void ReadBuiltInElementName()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<PropertyGroup/>
</ItemDefinitionGroup>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an item definition with several metadata
/// </summary>
[Fact]
public void ReadMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i1 m1='v1'>
<m2 Condition='c'>v2</m2>
<m1>v3</m1>
</i1>
</ItemDefinitionGroup>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectItemDefinitionGroupElement itemDefinitionGroup = (ProjectItemDefinitionGroupElement)Helpers.GetFirst(project.Children);
ProjectItemDefinitionElement itemDefinition = Helpers.GetFirst(itemDefinitionGroup.ItemDefinitions);
var metadata = Helpers.MakeList(itemDefinition.Metadata);
Assert.Equal(3, metadata.Count);
Assert.Equal("m1", metadata[0].Name);
Assert.Equal("v1", metadata[0].Value);
Assert.Equal("m2", metadata[1].Name);
Assert.Equal("v2", metadata[1].Value);
Assert.Equal("c", metadata[1].Condition);
Assert.Equal("m1", metadata[2].Name);
Assert.Equal("v3", metadata[2].Value);
}
/// <summary>
/// Reads metadata as attributes that wouldn't be
/// metadata on items
/// </summary>
[Theory]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i Include='inc' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i Update='upd' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i Remove='rem' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i Exclude='excl' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i KeepMetadata='true' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i RemoveMetadata='true' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i KeepDuplicates='true' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i cOndiTion='true' />
</ItemDefinitionGroup>
</Project>
")]
[InlineData(@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i LabeL='text' />
</ItemDefinitionGroup>
</Project>
")]
public void DoNotReadInvalidMetadataAttributesOrAttributesValidOnItems(string content)
{
Assert.Throws<InvalidProjectFileException>(() =>
{
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
});
}
/// <summary>
/// Set the condition value
/// </summary>
[Fact]
public void SetCondition()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectItemDefinitionElement itemDefinition = project.AddItemDefinitionGroup().AddItemDefinition("i");
Helpers.ClearDirtyFlag(project);
itemDefinition.Condition = "c";
Assert.Equal("c", itemDefinition.Condition);
Assert.True(project.HasUnsavedChanges);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Text;
using System.Threading;
using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE;
using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON;
using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags;
using LUID = Interop.LUID;
using LSA_STRING = Interop.SspiCli.LSA_STRING;
using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS;
using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE;
using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE;
using System.Runtime.Serialization;
namespace System.Security.Principal
{
public class WindowsIdentity : ClaimsIdentity, IDisposable, ISerializable, IDeserializationCallback
{
private string _name = null;
private SecurityIdentifier _owner = null;
private SecurityIdentifier _user = null;
private IdentityReferenceCollection _groups = null;
private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle;
private string _authType = null;
private int _isAuthenticated = -1;
private volatile TokenImpersonationLevel _impersonationLevel;
private volatile bool _impersonationLevelInitialized;
public new const string DefaultIssuer = @"AD AUTHORITY";
[NonSerialized]
private string _issuerName = DefaultIssuer;
[NonSerialized]
private object _claimsIntiailizedLock = new object();
[NonSerialized]
private volatile bool _claimsInitialized;
[NonSerialized]
private List<Claim> _deviceClaims;
[NonSerialized]
private List<Claim> _userClaims;
//
// Constructors.
//
private WindowsIdentity()
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{ }
/// <summary>
/// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN).
/// </summary>
/// <remarks>
/// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current
/// thread privilege to include Tcb.
/// </remarks>
public WindowsIdentity(string sUserPrincipalName)
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{
// Desktop compat: See comments below for why we don't validate sUserPrincipalName.
using (SafeLsaHandle lsaHandle = ConnectToLsa())
{
int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A);
// 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api
// so we'll use the same name the CLR used even though we're not actually the "CLR."
byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 };
TOKEN_SOURCE sourceContext;
if (!Interop.Advapi32.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
throw new SecurityException(new Win32Exception().Message);
sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH];
Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length);
// Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws
// the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves
// and simulate the exception from Encoding.Unicode.GetBytes().
if (sUserPrincipalName == null)
throw new ArgumentNullException("s");
byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName);
if (upnBytes.Length > ushort.MaxValue)
{
// Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort,
// effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.)
Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue);
}
unsafe
{
//
// Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire
// structure to be contained within the same block of memory, so we need to allocate
// enough room for both the structure itself and the UPN string in a single buffer
// and do the marshalling into this buffer by hand.
//
int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length);
using (SafeLocalAllocHandle authenticationInfo = Interop.Kernel32.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength))))
{
if (authenticationInfo.IsInvalid)
throw new OutOfMemoryException();
KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle());
pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon;
pKerbS4uLogin->Flags = KerbS4uLogonFlags.None;
pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length);
IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1);
pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset;
Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length);
pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0;
pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero;
ushort sourceNameLength = checked((ushort)(sourceName.Length));
using (SafeLocalAllocHandle sourceNameBuffer = Interop.Kernel32.LocalAlloc(0, new UIntPtr(sourceNameLength)))
{
if (sourceNameBuffer.IsInvalid)
throw new OutOfMemoryException();
Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length);
LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength);
SafeLsaReturnBufferHandle profileBuffer;
int profileBufferLength;
LUID logonId;
SafeAccessTokenHandle accessTokenHandle;
QUOTA_LIMITS quota;
int subStatus;
int ntStatus = Interop.SspiCli.LsaLogonUser(
lsaHandle,
ref lsaOriginName,
SECURITY_LOGON_TYPE.Network,
packageId,
authenticationInfo.DangerousGetHandle(),
authenticationInfoLength,
IntPtr.Zero,
ref sourceContext,
out profileBuffer,
out profileBufferLength,
out logonId,
out accessTokenHandle,
out quota,
out subStatus);
if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0)
ntStatus = subStatus;
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
if (subStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(subStatus);
if (profileBuffer != null)
profileBuffer.Dispose();
_safeTokenHandle = accessTokenHandle;
}
}
}
}
}
private static SafeLsaHandle ConnectToLsa()
{
SafeLsaHandle lsaHandle;
int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle);
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
return lsaHandle;
}
private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName)
{
Debug.Assert(!string.IsNullOrEmpty(packageName));
unsafe
{
int packageId;
byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName);
fixed (byte* pAsciiPackageName = &asciiPackageName[0])
{
LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length)));
int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId);
if (ntStatus < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(ntStatus);
}
return packageId;
}
}
public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { }
public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { }
private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated)
: base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid)
{
CreateFromToken(userToken);
_authType = authType;
_isAuthenticated = isAuthenticated;
}
private void CreateFromToken(IntPtr userToken)
{
if (userToken == IntPtr.Zero)
throw new ArgumentException(SR.Argument_TokenZero);
Contract.EndContractBlock();
// Find out if the specified token is a valid.
uint dwLength = (uint)sizeof(uint);
bool result = Interop.Advapi32.GetTokenInformation(userToken, (uint)TokenInformationClass.TokenType,
SafeLocalAllocHandle.InvalidHandle, 0, out dwLength);
if (Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INVALID_HANDLE)
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
if (!Interop.Kernel32.DuplicateHandle(Interop.Kernel32.GetCurrentProcess(),
userToken,
Interop.Kernel32.GetCurrentProcess(),
ref _safeTokenHandle,
0,
true,
Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
throw new SecurityException(new Win32Exception().Message);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")]
public WindowsIdentity(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
void IDeserializationCallback.OnDeserialization(object sender)
{
throw new PlatformNotSupportedException();
}
//
// Factory methods.
//
public static WindowsIdentity GetCurrent()
{
return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false);
}
public static WindowsIdentity GetCurrent(bool ifImpersonating)
{
return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating);
}
public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
{
return GetCurrentInternal(desiredAccess, false);
}
// GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate
// the request is anonymous. It does not represent a real process or thread token so
// it cannot impersonate or do anything useful. Note this identity does not represent the
// usual concept of an anonymous token, and the name is simply misleading but we cannot change it now.
public static WindowsIdentity GetAnonymous()
{
return new WindowsIdentity();
}
//
// Properties.
//
// this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same.
public override sealed string AuthenticationType
{
get
{
// If this is an anonymous identity, return an empty string
if (_safeTokenHandle.IsInvalid)
return String.Empty;
if (_authType == null)
{
Interop.LUID authId = GetLogonAuthId(_safeTokenHandle);
if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID)
return String.Empty; // no authentication, just return an empty string
SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle;
try
{
int status = Interop.SspiCli.LsaGetLogonSessionData(ref authId, ref pLogonSessionData);
if (status < 0) // non-negative numbers indicate success
throw GetExceptionFromNtStatus(status);
pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>());
Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0);
return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer);
}
finally
{
if (!pLogonSessionData.IsInvalid)
pLogonSessionData.Dispose();
}
}
return _authType;
}
}
public TokenImpersonationLevel ImpersonationLevel
{
get
{
// In case of a race condition here here, both threads will set m_impersonationLevel to the same value,
// which is ok.
if (!_impersonationLevelInitialized)
{
TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None;
// If this is an anonymous identity
if (_safeTokenHandle.IsInvalid)
{
impersonationLevel = TokenImpersonationLevel.Anonymous;
}
else
{
TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType);
if (tokenType == TokenType.TokenPrimary)
{
impersonationLevel = TokenImpersonationLevel.None; // primary token;
}
else
{
/// This is an impersonation token, get the impersonation level
int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel);
impersonationLevel = (TokenImpersonationLevel)level + 1;
}
}
_impersonationLevel = impersonationLevel;
_impersonationLevelInitialized = true;
}
return _impersonationLevel;
}
}
public override bool IsAuthenticated
{
get
{
if (_isAuthenticated == -1)
{
// This approach will not work correctly for domain guests (will return false
// instead of true). This is a corner-case that is not very interesting.
_isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0;
}
return _isAuthenticated == 1;
}
}
private bool CheckNtTokenForSid(SecurityIdentifier sid)
{
Contract.EndContractBlock();
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
// CheckTokenMembership expects an impersonation token
SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle;
TokenImpersonationLevel til = ImpersonationLevel;
bool isMember = false;
try
{
if (til == TokenImpersonationLevel.None)
{
if (!Interop.Advapi32.DuplicateTokenEx(_safeTokenHandle,
(uint)TokenAccessLevels.Query,
IntPtr.Zero,
(uint)TokenImpersonationLevel.Identification,
(uint)TokenType.TokenImpersonation,
ref token))
throw new SecurityException(new Win32Exception().Message);
}
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
if (!Interop.Advapi32.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
}
finally
{
if (token != SafeAccessTokenHandle.InvalidHandle)
{
token.Dispose();
}
}
return isMember;
}
//
// IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always
// possible to extract this same information from the User SID property and the new
// (and more general) methods defined in the SID class (IsWellKnown, etc...).
//
public virtual bool IsGuest
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest }));
}
}
public virtual bool IsSystem
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return false;
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID });
return (this.User == sid);
}
}
public virtual bool IsAnonymous
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return true;
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID });
return (this.User == sid);
}
}
public override string Name
{
get
{
return GetName();
}
}
internal String GetName()
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return String.Empty;
if (_name == null)
{
// revert thread impersonation for the duration of the call to get the name.
RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate
{
NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount;
_name = ntAccount.ToString();
});
}
return _name;
}
public SecurityIdentifier Owner
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_owner == null)
{
using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner))
{
_owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true);
}
}
return _owner;
}
}
public SecurityIdentifier User
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_user == null)
{
using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser))
{
_user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true);
}
}
return _user;
}
}
public IdentityReferenceCollection Groups
{
get
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return null;
if (_groups == null)
{
IdentityReferenceCollection groups = new IdentityReferenceCollection();
using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups))
{
uint groupCount = pGroups.Read<uint>(0);
Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0);
Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount];
pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(),
groupDetails,
0,
groupDetails.Length);
foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails)
{
// Ignore disabled, logon ID, and deny-only groups.
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
groups.Add(new SecurityIdentifier(group.Sid, true));
}
}
}
Interlocked.CompareExchange(ref _groups, groups, null);
}
return _groups;
}
}
public SafeAccessTokenHandle AccessToken
{
get
{
return _safeTokenHandle;
}
}
public virtual IntPtr Token
{
get
{
return _safeTokenHandle.DangerousGetHandle();
}
}
//
// Public methods.
//
public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
RunImpersonatedInternal(safeAccessTokenHandle, action);
}
public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
T result = default(T);
RunImpersonatedInternal(safeAccessTokenHandle, () => result = func());
return result;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed)
_safeTokenHandle.Dispose();
}
_name = null;
_owner = null;
_user = null;
}
public void Dispose()
{
Dispose(true);
}
//
// internal.
//
private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged);
private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
{
bool isImpersonating;
int hr;
SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr);
if (previousToken == null || previousToken.IsInvalid)
throw new SecurityException(new Win32Exception(hr).Message);
s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null;
ExecutionContext currentContext = ExecutionContext.Capture();
// Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone
// on the way out.
ExecutionContext.Run(
currentContext,
delegate
{
if (!Interop.Advapi32.RevertToSelf())
Environment.FailFast(new Win32Exception().Message);
s_currentImpersonatedToken.Value = null;
if (!token.IsInvalid && !Interop.Advapi32.ImpersonateLoggedOnUser(token))
throw new SecurityException(SR.Argument_ImpersonateUser);
s_currentImpersonatedToken.Value = token;
action();
},
null);
}
private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args)
{
if (!args.ThreadContextChanged)
return; // we handle explicit Value property changes elsewhere.
if (!Interop.Advapi32.RevertToSelf())
Environment.FailFast(new Win32Exception().Message);
if (args.CurrentValue != null && !args.CurrentValue.IsInvalid)
{
if (!Interop.Advapi32.ImpersonateLoggedOnUser(args.CurrentValue))
Environment.FailFast(new Win32Exception().Message);
}
}
internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly)
{
int hr = 0;
bool isImpersonating;
SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr);
if (safeTokenHandle == null || safeTokenHandle.IsInvalid)
{
// either we wanted only ThreadToken - return null
if (threadOnly && !isImpersonating)
return null;
// or there was an error
throw new SecurityException(new Win32Exception(hr).Message);
}
WindowsIdentity wi = new WindowsIdentity();
wi._safeTokenHandle.Dispose();
wi._safeTokenHandle = safeTokenHandle;
return wi;
}
//
// private.
//
private static int GetHRForWin32Error(int dwLastError)
{
if ((dwLastError & 0x80000000) == 0x80000000)
return dwLastError;
else
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
private static Exception GetExceptionFromNtStatus(int status)
{
if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED)
return new UnauthorizedAccessException();
if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY)
return new OutOfMemoryException();
uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError((uint)status);
return new SecurityException(new Win32Exception(unchecked((int)win32ErrorCode)).Message);
}
private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr)
{
isImpersonating = true;
SafeAccessTokenHandle safeTokenHandle;
hr = 0;
bool success = Interop.Advapi32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle);
if (!success)
hr = Marshal.GetHRForLastWin32Error();
if (!success && hr == GetHRForWin32Error(Interop.Errors.ERROR_NO_TOKEN))
{
// No impersonation
isImpersonating = false;
if (!threadOnly)
safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr);
}
return safeTokenHandle;
}
private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr)
{
hr = 0;
SafeAccessTokenHandle safeTokenHandle;
if (!Interop.Advapi32.OpenProcessToken(Interop.Kernel32.GetCurrentProcess(), desiredAccess, out safeTokenHandle))
hr = GetHRForWin32Error(Marshal.GetLastWin32Error());
return safeTokenHandle;
}
/// <summary>
/// Get a property from the current token
/// </summary>
private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct
{
Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed");
using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass))
{
Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(),
"information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))");
return information.Read<T>(0);
}
}
private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle)
{
using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics))
{
Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0);
return statistics.AuthenticationId;
}
}
private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
{
SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
uint dwLength = (uint)sizeof(uint);
bool result = Interop.Advapi32.GetTokenInformation(tokenHandle,
(uint)tokenInformationClass,
safeLocalAllocHandle,
0,
out dwLength);
int dwErrorCode = Marshal.GetLastWin32Error();
switch (dwErrorCode)
{
case Interop.Errors.ERROR_BAD_LENGTH:
// special case for TokenSessionId. Falling through
case Interop.Errors.ERROR_INSUFFICIENT_BUFFER:
// ptrLength is an [In] param to LocalAlloc
UIntPtr ptrLength = new UIntPtr(dwLength);
safeLocalAllocHandle.Dispose();
safeLocalAllocHandle = Interop.Kernel32.LocalAlloc(0, ptrLength);
if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid)
throw new OutOfMemoryException();
safeLocalAllocHandle.Initialize(dwLength);
result = Interop.Advapi32.GetTokenInformation(tokenHandle,
(uint)tokenInformationClass,
safeLocalAllocHandle,
dwLength,
out dwLength);
if (!result)
throw new SecurityException(new Win32Exception().Message);
break;
case Interop.Errors.ERROR_INVALID_HANDLE:
throw new ArgumentException(SR.Argument_InvalidImpersonationToken);
default:
throw new SecurityException(new Win32Exception(dwErrorCode).Message);
}
return safeLocalAllocHandle;
}
protected WindowsIdentity(WindowsIdentity identity)
: base(identity, null, GetAuthType(identity), null, null)
{
bool mustDecrement = false;
try
{
if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
{
identity._safeTokenHandle.DangerousAddRef(ref mustDecrement);
if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
CreateFromToken(identity._safeTokenHandle.DangerousGetHandle());
_authType = identity._authType;
_isAuthenticated = identity._isAuthenticated;
}
}
finally
{
if (mustDecrement)
identity._safeTokenHandle.DangerousRelease();
}
}
private static string GetAuthType(WindowsIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
return identity._authType;
}
/// <summary>
/// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object.
/// </summary>
public override ClaimsIdentity Clone()
{
return new WindowsIdentity(this);
}
/// <summary>
/// Gets the 'User Claims' from the NTToken that represents this identity
/// </summary>
public virtual IEnumerable<Claim> UserClaims
{
get
{
InitializeClaims();
return _userClaims.ToArray();
}
}
/// <summary>
/// Gets the 'Device Claims' from the NTToken that represents the device the identity is using
/// </summary>
public virtual IEnumerable<Claim> DeviceClaims
{
get
{
InitializeClaims();
return _deviceClaims.ToArray();
}
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>.
/// Includes UserClaims and DeviceClaims.
/// </summary>
public override IEnumerable<Claim> Claims
{
get
{
if (!_claimsInitialized)
{
InitializeClaims();
}
foreach (Claim claim in base.Claims)
yield return claim;
foreach (Claim claim in _userClaims)
yield return claim;
foreach (Claim claim in _deviceClaims)
yield return claim;
}
}
/// <summary>
/// Intenal method to initialize the claim collection.
/// Lazy init is used so claims are not initialzed until needed
/// </summary>
private void InitializeClaims()
{
if (!_claimsInitialized)
{
lock (_claimsIntiailizedLock)
{
if (!_claimsInitialized)
{
_userClaims = new List<Claim>();
_deviceClaims = new List<Claim>();
if (!String.IsNullOrEmpty(Name))
{
//
// Add the name claim only if the WindowsIdentity.Name is populated
// WindowsIdentity.Name will be null when it is the fake anonymous user
// with a token value of IntPtr.Zero
//
_userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this));
}
// primary sid
AddPrimarySidClaim(_userClaims);
// group sids
AddGroupSidClaims(_userClaims);
_claimsInitialized = true;
}
}
}
}
/// <summary>
/// Creates a collection of SID claims that represent the users groups.
/// </summary>
private void AddGroupSidClaims(List<Claim> instanceClaims)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle;
try
{
// Retrieve the primary group sid
safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup);
Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle());
SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true);
// only add one primary group sid
bool foundPrimaryGroupSid = false;
// Retrieve all group sids, primary group sid is one of them
safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups);
int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle());
IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups"));
Claim claim;
for (int i = 0; i < count; ++i)
{
Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes);
uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true);
if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED)
{
if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
{
claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
foundPrimaryGroupSid = true;
}
//Primary group sid generates both regular groupsid claim and primary groupsid claim
claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value))
{
claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
foundPrimaryGroupSid = true;
}
//Primary group sid generates both regular groupsid claim and primary groupsid claim
claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>());
}
}
finally
{
safeAllocHandle.Dispose();
safeAllocHandlePrimaryGroup.Dispose();
}
}
/// <summary>
/// Creates a Windows SID Claim and adds to collection of claims.
/// </summary>
private void AddPrimarySidClaim(List<Claim> instanceClaims)
{
// special case the anonymous identity.
if (_safeTokenHandle.IsInvalid)
return;
SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle;
try
{
safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser);
Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle());
uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY;
SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true);
Claim claim;
if (user.Attributes == 0)
{
claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY)
{
claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this);
claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString());
instanceClaims.Add(claim);
}
}
finally
{
safeAllocHandle.Dispose();
}
}
}
internal enum WinSecurityContext
{
Thread = 1, // OpenAsSelf = false
Process = 2, // OpenAsSelf = true
Both = 3 // OpenAsSelf = true, then OpenAsSelf = false
}
internal enum TokenType : int
{
TokenPrimary = 1,
TokenImpersonation
}
internal enum TokenInformationClass : int
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
TokenIsAppContainer,
TokenCapabilities,
TokenAppContainerSid,
TokenAppContainerNumber,
TokenUserClaimAttributes,
TokenDeviceClaimAttributes,
TokenRestrictedUserClaimAttributes,
TokenRestrictedDeviceClaimAttributes,
TokenDeviceGroups,
TokenRestrictedDeviceGroups,
MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// SyncListPermissionResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Sync.V1.Service.SyncList
{
public class SyncListPermissionResource : Resource
{
private static Request BuildFetchRequest(FetchSyncListPermissionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions/" + options.PathIdentity + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a specific Sync List Permission.
/// </summary>
/// <param name="options"> Fetch SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static SyncListPermissionResource Fetch(FetchSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a specific Sync List Permission.
/// </summary>
/// <param name="options"> Fetch SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<SyncListPermissionResource> FetchAsync(FetchSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a specific Sync List Permission.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resource to fetch </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resource to fetch </param>
/// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync List Permission
/// resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static SyncListPermissionResource Fetch(string pathServiceSid,
string pathListSid,
string pathIdentity,
ITwilioRestClient client = null)
{
var options = new FetchSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a specific Sync List Permission.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resource to fetch </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resource to fetch </param>
/// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync List Permission
/// resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<SyncListPermissionResource> FetchAsync(string pathServiceSid,
string pathListSid,
string pathIdentity,
ITwilioRestClient client = null)
{
var options = new FetchSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteSyncListPermissionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions/" + options.PathIdentity + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a specific Sync List Permission.
/// </summary>
/// <param name="options"> Delete SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static bool Delete(DeleteSyncListPermissionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete a specific Sync List Permission.
/// </summary>
/// <param name="options"> Delete SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete a specific Sync List Permission.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resource to delete </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resource to delete </param>
/// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync List Permission
/// resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static bool Delete(string pathServiceSid,
string pathListSid,
string pathIdentity,
ITwilioRestClient client = null)
{
var options = new DeleteSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a specific Sync List Permission.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resource to delete </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resource to delete </param>
/// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync List Permission
/// resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathListSid,
string pathIdentity,
ITwilioRestClient client = null)
{
var options = new DeleteSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadSyncListPermissionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Permissions applying to a Sync List.
/// </summary>
/// <param name="options"> Read SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static ResourceSet<SyncListPermissionResource> Read(ReadSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<SyncListPermissionResource>.FromJson("permissions", response.Content);
return new ResourceSet<SyncListPermissionResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Permissions applying to a Sync List.
/// </summary>
/// <param name="options"> Read SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncListPermissionResource>> ReadAsync(ReadSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<SyncListPermissionResource>.FromJson("permissions", response.Content);
return new ResourceSet<SyncListPermissionResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Permissions applying to a Sync List.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resources to read </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static ResourceSet<SyncListPermissionResource> Read(string pathServiceSid,
string pathListSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncListPermissionOptions(pathServiceSid, pathListSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Permissions applying to a Sync List.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resources to read </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncListPermissionResource>> ReadAsync(string pathServiceSid,
string pathListSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncListPermissionOptions(pathServiceSid, pathListSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<SyncListPermissionResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<SyncListPermissionResource>.FromJson("permissions", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<SyncListPermissionResource> NextPage(Page<SyncListPermissionResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Sync)
);
var response = client.Request(request);
return Page<SyncListPermissionResource>.FromJson("permissions", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<SyncListPermissionResource> PreviousPage(Page<SyncListPermissionResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Sync)
);
var response = client.Request(request);
return Page<SyncListPermissionResource>.FromJson("permissions", response.Content);
}
private static Request BuildUpdateRequest(UpdateSyncListPermissionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Sync,
"/v1/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions/" + options.PathIdentity + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Update an identity's access to a specific Sync List.
/// </summary>
/// <param name="options"> Update SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static SyncListPermissionResource Update(UpdateSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Update an identity's access to a specific Sync List.
/// </summary>
/// <param name="options"> Update SyncListPermission parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<SyncListPermissionResource> UpdateAsync(UpdateSyncListPermissionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Update an identity's access to a specific Sync List.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resource to update </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resource to update </param>
/// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync List Permission
/// resource to update </param>
/// <param name="read"> Read access </param>
/// <param name="write"> Write access </param>
/// <param name="manage"> Manage access </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncListPermission </returns>
public static SyncListPermissionResource Update(string pathServiceSid,
string pathListSid,
string pathIdentity,
bool? read,
bool? write,
bool? manage,
ITwilioRestClient client = null)
{
var options = new UpdateSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity, read, write, manage);
return Update(options, client);
}
#if !NET35
/// <summary>
/// Update an identity's access to a specific Sync List.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Sync Service with the Sync List Permission resource to update </param>
/// <param name="pathListSid"> The SID of the Sync List with the Sync List Permission resource to update </param>
/// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync List Permission
/// resource to update </param>
/// <param name="read"> Read access </param>
/// <param name="write"> Write access </param>
/// <param name="manage"> Manage access </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncListPermission </returns>
public static async System.Threading.Tasks.Task<SyncListPermissionResource> UpdateAsync(string pathServiceSid,
string pathListSid,
string pathIdentity,
bool? read,
bool? write,
bool? manage,
ITwilioRestClient client = null)
{
var options = new UpdateSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity, read, write, manage);
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a SyncListPermissionResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> SyncListPermissionResource object represented by the provided JSON </returns>
public static SyncListPermissionResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<SyncListPermissionResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Sync Service that the resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The SID of the Sync List to which the Permission applies
/// </summary>
[JsonProperty("list_sid")]
public string ListSid { get; private set; }
/// <summary>
/// The identity of the user to whom the Sync List Permission applies
/// </summary>
[JsonProperty("identity")]
public string Identity { get; private set; }
/// <summary>
/// Read access
/// </summary>
[JsonProperty("read")]
public bool? _Read { get; private set; }
/// <summary>
/// Write access
/// </summary>
[JsonProperty("write")]
public bool? Write { get; private set; }
/// <summary>
/// Manage access
/// </summary>
[JsonProperty("manage")]
public bool? Manage { get; private set; }
/// <summary>
/// The absolute URL of the Sync List Permission resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private SyncListPermissionResource()
{
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ButtonColumn.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.Util;
/// <devdoc>
/// <para>Creates a column with a set of <see cref='System.Web.UI.WebControls.Button'/>
/// controls.</para>
/// </devdoc>
public class ButtonColumn : DataGridColumn {
private PropertyDescriptor textFieldDesc;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.ButtonColumn'/> class.</para>
/// </devdoc>
public ButtonColumn() {
}
/// <devdoc>
/// <para>Gets or sets the type of button to render in the
/// column.</para>
/// </devdoc>
[
WebCategory("Appearance"),
DefaultValue(ButtonColumnType.LinkButton),
WebSysDescriptionAttribute(SR.ButtonColumn_ButtonType)
]
public virtual ButtonColumnType ButtonType {
get {
object o = ViewState["ButtonType"];
if (o != null)
return(ButtonColumnType)o;
return ButtonColumnType.LinkButton;
}
set {
if (value < ButtonColumnType.LinkButton || value > ButtonColumnType.PushButton) {
throw new ArgumentOutOfRangeException("value");
}
ViewState["ButtonType"] = value;
OnColumnChanged();
}
}
[
DefaultValue(false),
WebSysDescriptionAttribute(SR.ButtonColumn_CausesValidation)
]
public virtual bool CausesValidation {
get {
object o = ViewState["CausesValidation"];
if (o != null) {
return (bool)o;
}
return false;
}
set {
ViewState["CausesValidation"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the command to perform when this <see cref='System.Web.UI.WebControls.Button'/>
/// is clicked.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(""),
WebSysDescriptionAttribute(SR.WebControl_CommandName)
]
public virtual string CommandName {
get {
object o = ViewState["CommandName"];
if (o != null)
return(string)o;
return string.Empty;
}
set {
ViewState["CommandName"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the field name from the data model that is
/// bound to the <see cref='System.Web.UI.WebControls.ButtonColumn.Text'/> property of the button in this column.</para>
/// </devdoc>
[
WebCategory("Data"),
DefaultValue(""),
WebSysDescriptionAttribute(SR.ButtonColumn_DataTextField)
]
public virtual string DataTextField {
get {
object o = ViewState["DataTextField"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["DataTextField"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the string used to format the data bound to
/// the <see cref='System.Web.UI.WebControls.ButtonColumn.Text'/> property of the button.</para>
/// </devdoc>
[
WebCategory("Data"),
DefaultValue(""),
WebSysDescriptionAttribute(SR.ButtonColumn_DataTextFormatString)
]
public virtual string DataTextFormatString {
get {
object o = ViewState["DataTextFormatString"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["DataTextFormatString"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the caption text displayed on the <see cref='System.Web.UI.WebControls.Button'/>
/// in this column.</para>
/// </devdoc>
[
Localizable(true),
WebCategory("Appearance"),
DefaultValue(""),
WebSysDescriptionAttribute(SR.ButtonColumn_Text)
]
public virtual string Text {
get {
object o = ViewState["Text"];
if (o != null)
return(string)o;
return String.Empty;
}
set {
ViewState["Text"] = value;
OnColumnChanged();
}
}
[
DefaultValue(""),
WebSysDescriptionAttribute(SR.ButtonColumn_ValidationGroup)
]
public virtual string ValidationGroup {
get {
object o = ViewState["ValidationGroup"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
ViewState["ValidationGroup"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// </devdoc>
protected virtual string FormatDataTextValue(object dataTextValue) {
string formattedTextValue = String.Empty;
if (!DataBinder.IsNull(dataTextValue)) {
string formatting = DataTextFormatString;
if (formatting.Length == 0) {
formattedTextValue = dataTextValue.ToString();
}
else {
formattedTextValue = String.Format(CultureInfo.CurrentCulture, formatting, dataTextValue);
}
}
return formattedTextValue;
}
/// <devdoc>
/// </devdoc>
public override void Initialize() {
base.Initialize();
textFieldDesc = null;
}
/// <devdoc>
/// <para>Initializes a cell in the <see cref='System.Web.UI.WebControls.ButtonColumn'/> .</para>
/// </devdoc>
public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType) {
base.InitializeCell(cell, columnIndex, itemType);
if ((itemType != ListItemType.Header) &&
(itemType != ListItemType.Footer)) {
WebControl buttonControl = null;
if (ButtonType == ButtonColumnType.LinkButton) {
LinkButton button = new DataGridLinkButton();
button.Text = Text;
button.CommandName = CommandName;
button.CausesValidation = CausesValidation;
button.ValidationGroup = ValidationGroup;
buttonControl = button;
}
else {
Button button = new Button();
button.Text = Text;
button.CommandName = CommandName;
button.CausesValidation = CausesValidation;
button.ValidationGroup = ValidationGroup;
buttonControl = button;
}
if (DataTextField.Length != 0) {
buttonControl.DataBinding += new EventHandler(this.OnDataBindColumn);
}
cell.Controls.Add(buttonControl);
}
}
/// <devdoc>
/// </devdoc>
private void OnDataBindColumn(object sender, EventArgs e) {
Debug.Assert(DataTextField.Length != 0, "Shouldn't be DataBinding without a DataTextField");
Control boundControl = (Control)sender;
DataGridItem item = (DataGridItem)boundControl.NamingContainer;
object dataItem = item.DataItem;
if (textFieldDesc == null) {
string dataField = DataTextField;
textFieldDesc = TypeDescriptor.GetProperties(dataItem).Find(dataField, true);
if ((textFieldDesc == null) && !DesignMode) {
throw new HttpException(SR.GetString(SR.Field_Not_Found, dataField));
}
}
string dataValue;
if (textFieldDesc != null) {
object data = textFieldDesc.GetValue(dataItem);
dataValue = FormatDataTextValue(data);
}
else {
Debug.Assert(DesignMode == true);
dataValue = SR.GetString(SR.Sample_Databound_Text);
}
if (boundControl is LinkButton) {
((LinkButton)boundControl).Text = dataValue;
}
else {
Debug.Assert(boundControl is Button, "Expected the bound control to be a Button");
((Button)boundControl).Text = dataValue;
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace SPO_ContentTypes
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Timers.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Annotations;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
namespace Akka.Streams.Implementation
{
/// <summary>
/// INTERNAL API
///
/// Various stages for controlling timeouts on IO related streams (although not necessarily).
///
/// The common theme among the processing stages here that
/// - they wait for certain event or events to happen
/// - they have a timer that may fire before these events
/// - if the timer fires before the event happens, these stages all fail the stream
/// - otherwise, these streams do not interfere with the element flow, ordinary completion or failure
/// </summary>
[InternalApi]
public static class Timers
{
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
/// <returns>TBD</returns>
public static TimeSpan IdleTimeoutCheckInterval(TimeSpan timeout)
=> new TimeSpan(Math.Min(Math.Max(timeout.Ticks/8, 100*TimeSpan.TicksPerMillisecond), timeout.Ticks/2));
/// <summary>
/// TBD
/// </summary>
public const string GraphStageLogicTimer = "GraphStageLogicTimer";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
[InternalApi]
public sealed class Initial<T> : SimpleLinearGraphStage<T>
{
#region Logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly Initial<T> _stage;
private bool _initialHasPassed;
public Logic(Initial<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Inlet, this);
SetHandler(stage.Outlet, this);
}
public void OnPush()
{
_initialHasPassed = true;
Push(_stage.Outlet, Grab(_stage.Inlet));
}
public void OnUpstreamFinish() => CompleteStage();
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull() => Pull(_stage.Inlet);
public void OnDownstreamFinish() => CompleteStage();
protected internal override void OnTimer(object timerKey)
{
if (!_initialHasPassed)
FailStage(new TimeoutException($"The first element has not yet passed through in {_stage.Timeout}."));
}
public override void PreStart() => ScheduleOnce(Timers.GraphStageLogicTimer, _stage.Timeout);
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Timeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
public Initial(TimeSpan timeout)
{
Timeout = timeout;
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.Initial;
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "InitialTimeoutTimer";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
[InternalApi]
public sealed class Completion<T> : SimpleLinearGraphStage<T>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly Completion<T> _stage;
public Logic(Completion<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(stage.Inlet, this);
SetHandler(stage.Outlet, this);
}
public void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet));
public void OnUpstreamFinish() => CompleteStage();
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull() => Pull(_stage.Inlet);
public void OnDownstreamFinish() => CompleteStage();
protected internal override void OnTimer(object timerKey)
=> FailStage(new TimeoutException($"The stream has not been completed in {_stage.Timeout}."));
public override void PreStart() => ScheduleOnce(Timers.GraphStageLogicTimer, _stage.Timeout);
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Timeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
public Completion(TimeSpan timeout)
{
Timeout = timeout;
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.Completion;
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "CompletionTimeout";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
[InternalApi]
public sealed class Idle<T> : SimpleLinearGraphStage<T>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly Idle<T> _stage;
private long _nextDeadline;
public Logic(Idle<T> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow.Ticks + stage.Timeout.Ticks;
SetHandler(stage.Inlet, this);
SetHandler(stage.Outlet, this);
}
public void OnPush()
{
_nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks;
Push(_stage.Outlet, Grab(_stage.Inlet));
}
public void OnUpstreamFinish() => CompleteStage();
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull() => Pull(_stage.Inlet);
public void OnDownstreamFinish() => CompleteStage();
protected internal override void OnTimer(object timerKey)
{
if (_nextDeadline - DateTime.UtcNow.Ticks < 0)
FailStage(new TimeoutException($"No elements passed in the last {_stage.Timeout}."));
}
public override void PreStart()
=> ScheduleRepeatedly(Timers.GraphStageLogicTimer, Timers.IdleTimeoutCheckInterval(_stage.Timeout));
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Timeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
public Idle(TimeSpan timeout)
{
Timeout = timeout;
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.Idle;
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "IdleTimeout";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
[InternalApi]
public sealed class BackpressureTimeout<T> : SimpleLinearGraphStage<T>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly BackpressureTimeout<T> _stage;
private long _nextDeadline;
private bool _waitingDemand = true;
public Logic(BackpressureTimeout<T> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow.Ticks + stage.Timeout.Ticks;
SetHandler(stage.Inlet, this);
SetHandler(stage.Outlet, this);
}
public void OnPush()
{
Push(_stage.Outlet, Grab(_stage.Inlet));
_nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks;
_waitingDemand = true;
}
public void OnUpstreamFinish() => CompleteStage();
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull()
{
_waitingDemand = false;
Pull(_stage.Inlet);
}
public void OnDownstreamFinish() => CompleteStage();
protected internal override void OnTimer(object timerKey)
{
if (_waitingDemand && (_nextDeadline - DateTime.UtcNow.Ticks < 0))
FailStage(new TimeoutException($"No demand signalled in the last {_stage.Timeout}."));
}
public override void PreStart()
=> ScheduleRepeatedly(Timers.GraphStageLogicTimer, Timers.IdleTimeoutCheckInterval(_stage.Timeout));
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Timeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
public BackpressureTimeout(TimeSpan timeout)
{
Timeout = timeout;
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.BackpressureTimeout;
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "BackpressureTimeout";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
[InternalApi]
public sealed class IdleTimeoutBidi<TIn, TOut> : GraphStage<BidiShape<TIn, TIn, TOut, TOut>>
{
#region Logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly IdleTimeoutBidi<TIn, TOut> _stage;
private long _nextDeadline;
public Logic(IdleTimeoutBidi<TIn, TOut> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks;
SetHandler(_stage.In1, this);
SetHandler(_stage.Out1, this);
SetHandler(_stage.In2, onPush: () =>
{
OnActivity();
Push(_stage.Out2, Grab(_stage.In2));
},
onUpstreamFinish: () => Complete(_stage.Out2));
SetHandler(_stage.Out2,
onPull: () => Pull(_stage.In2),
onDownstreamFinish: () => Cancel(_stage.In2));
}
public void OnPush()
{
OnActivity();
Push(_stage.Out1, Grab(_stage.In1));
}
public void OnUpstreamFinish() => Complete(_stage.Out1);
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull() => Pull(_stage.In1);
public void OnDownstreamFinish() => Cancel(_stage.In1);
protected internal override void OnTimer(object timerKey)
{
if (_nextDeadline - DateTime.UtcNow.Ticks < 0)
FailStage(new TimeoutException($"No elements passed in the last {_stage.Timeout}."));
}
public override void PreStart()
=> ScheduleRepeatedly(Timers.GraphStageLogicTimer, Timers.IdleTimeoutCheckInterval(_stage.Timeout));
private void OnActivity() => _nextDeadline = DateTime.UtcNow.Ticks + _stage.Timeout.Ticks;
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Timeout;
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<TIn> In1 = new Inlet<TIn>("in1");
/// <summary>
/// TBD
/// </summary>
public readonly Inlet<TOut> In2 = new Inlet<TOut>("in2");
/// <summary>
/// TBD
/// </summary>
public readonly Outlet<TIn> Out1 = new Outlet<TIn>("out1");
/// <summary>
/// TBD
/// </summary>
public readonly Outlet<TOut> Out2 = new Outlet<TOut>("out2");
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
public IdleTimeoutBidi(TimeSpan timeout)
{
Timeout = timeout;
Shape = new BidiShape<TIn, TIn, TOut, TOut>(In1, Out1, In2, Out2);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.IdleTimeoutBidi;
/// <summary>
/// TBD
/// </summary>
public override BidiShape<TIn, TIn, TOut, TOut> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "IdleTimeoutBidi";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
[InternalApi]
public sealed class DelayInitial<T> : SimpleLinearGraphStage<T>
{
#region stage logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly DelayInitial<T> _stage;
private bool _isOpen;
public Logic(DelayInitial<T> stage) : base(stage.Shape)
{
_stage = stage;
SetHandler(_stage.Inlet, this);
SetHandler(_stage.Outlet, this);
}
public void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet));
public void OnUpstreamFinish() => CompleteStage();
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull()
{
if (_isOpen)
Pull(_stage.Inlet);
}
public void OnDownstreamFinish() => CompleteStage();
protected internal override void OnTimer(object timerKey)
{
_isOpen = true;
if (IsAvailable(_stage.Outlet))
Pull(_stage.Inlet);
}
public override void PreStart()
{
if (_stage.Delay == TimeSpan.Zero)
_isOpen = true;
else
ScheduleOnce(Timers.GraphStageLogicTimer, _stage.Delay);
}
}
#endregion
/// <summary>
/// TBD
/// </summary>
public readonly TimeSpan Delay;
/// <summary>
/// TBD
/// </summary>
/// <param name="delay">TBD</param>
public DelayInitial(TimeSpan delay) : base("DelayInitial")
{
Delay = delay;
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.DelayInitial;
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "DelayTimer";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
[InternalApi]
public sealed class IdleInject<TIn, TOut> : GraphStage<FlowShape<TIn, TOut>> where TIn : TOut
{
#region Logic
private sealed class Logic : TimerGraphStageLogic, IInHandler, IOutHandler
{
private readonly IdleInject<TIn, TOut> _stage;
private long _nextDeadline;
public Logic(IdleInject<TIn, TOut> stage) : base(stage.Shape)
{
_stage = stage;
_nextDeadline = DateTime.UtcNow.Ticks + _stage._timeout.Ticks;
SetHandler(_stage._in, this);
SetHandler(_stage._out, this);
}
public void OnPush()
{
_nextDeadline = DateTime.UtcNow.Ticks + _stage._timeout.Ticks;
CancelTimer(Timers.GraphStageLogicTimer);
if (IsAvailable(_stage._out))
{
Push(_stage._out, Grab(_stage._in));
Pull(_stage._in);
}
}
public void OnUpstreamFinish()
{
if (!IsAvailable(_stage._in))
CompleteStage();
}
public void OnUpstreamFailure(Exception e) => FailStage(e);
public void OnPull()
{
if (IsAvailable(_stage._in))
{
Push(_stage._out, Grab(_stage._in));
if (IsClosed(_stage._in))
CompleteStage();
else
Pull(_stage._in);
}
else
{
var time = DateTime.UtcNow.Ticks;
if (_nextDeadline - time < 0)
{
_nextDeadline = time + _stage._timeout.Ticks;
Push(_stage._out, _stage._inject());
}
else
ScheduleOnce(Timers.GraphStageLogicTimer, TimeSpan.FromTicks(_nextDeadline - time));
}
}
public void OnDownstreamFinish() => CompleteStage();
protected internal override void OnTimer(object timerKey)
{
var time = DateTime.UtcNow.Ticks;
if ((_nextDeadline - time < 0) && IsAvailable(_stage._out))
{
Push(_stage._out, _stage._inject());
_nextDeadline = DateTime.UtcNow.Ticks + _stage._timeout.Ticks;
}
}
// Prefetching to ensure priority of actual upstream elements
public override void PreStart() => Pull(_stage._in);
}
#endregion
private readonly TimeSpan _timeout;
private readonly Func<TOut> _inject;
private readonly Inlet<TIn> _in = new Inlet<TIn>("IdleInject.in");
private readonly Outlet<TOut> _out = new Outlet<TOut>("IdleInject.out");
/// <summary>
/// TBD
/// </summary>
/// <param name="timeout">TBD</param>
/// <param name="inject">TBD</param>
public IdleInject(TimeSpan timeout, Func<TOut> inject)
{
_timeout = timeout;
_inject = inject;
Shape = new FlowShape<TIn, TOut>(_in, _out);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.IdleInject;
/// <summary>
/// TBD
/// </summary>
public override FlowShape<TIn, TOut> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "IdleTimer";
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using Bam.Core;
using System.Linq;
namespace Installer
{
/// <summary>
/// Module representing the input file to tar
/// </summary>
class TarInputFiles :
Bam.Core.Module
{
private readonly System.Collections.Generic.Dictionary<Bam.Core.Module, string> Files = new System.Collections.Generic.Dictionary<Bam.Core.Module, string>();
private readonly System.Collections.Generic.Dictionary<Bam.Core.Module, string> Paths = new System.Collections.Generic.Dictionary<Bam.Core.Module, string>();
// TODO: this could be improved, as it is assuming that only the first directory added to the tar file
// is of interest as inputs, and ignores all remaining directories, and all individual files
/// <summary>
/// Access to Module-pathkey tuples
/// </summary>
public (Bam.Core.Module, string) ModulePathTuple => (this.Paths.First().Key, this.Paths.First().Value);
/// <summary>
/// Initialize this module
/// </summary>
protected override void
Init()
{
base.Init();
var parentModule = Bam.Core.Graph.Instance.ModuleStack.Peek();
this.ScriptPath = this.CreateTokenizedString(
"$(buildroot)/$(0)/$(config)/tarinput.txt",
new[] { parentModule.Macros[Bam.Core.ModuleMacroNames.ModuleName] }
);
}
/// <summary>
/// Get the script path used for writing tars
/// </summary>
public Bam.Core.TokenizedString ScriptPath { get; private set; }
/// <summary>
/// Add a file from a module
/// </summary>
/// <param name="module">Module to add</param>
/// <param name="key">Path key from Module</param>
public void
AddFile(
Bam.Core.Module module,
string key)
{
this.DependsOn(module);
this.Files.Add(module, key);
}
/// <summary>
/// Add a path (a directory) from a module
/// </summary>
/// <param name="module">Module to add</param>
/// <param name="key">Path key from module</param>
public void
AddPath(
Bam.Core.Module module,
string key)
{
this.DependsOn(module);
this.Paths.Add(module, key);
}
protected override void
EvaluateInternal()
{
// do nothing
}
/// <summary>
/// Execute the tool on this module
/// </summary>
/// <param name="context">in this context</param>
protected override void
ExecuteInternal(
Bam.Core.ExecutionContext context)
{
var path = this.ScriptPath.ToString();
var dir = System.IO.Path.GetDirectoryName(path);
Bam.Core.IOWrapper.CreateDirectoryIfNotExists(dir);
using (var scriptWriter = new System.IO.StreamWriter(path))
{
foreach (var dep in this.Files)
{
var filePath = dep.Key.GeneratedPaths[dep.Value].ToString();
var fileDir = System.IO.Path.GetDirectoryName(filePath);
// TODO: this should probably be a setting
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX))
{
scriptWriter.WriteLine("-C");
scriptWriter.WriteLine(fileDir);
}
else
{
scriptWriter.WriteLine($"-C{fileDir}");
}
scriptWriter.WriteLine(System.IO.Path.GetFileName(filePath));
}
foreach (var dep in this.Paths)
{
var fileDir = dep.Key.GeneratedPaths[dep.Value].ToString();
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX))
{
scriptWriter.WriteLine("-C");
scriptWriter.WriteLine(fileDir);
}
else
{
scriptWriter.WriteLine($"-C{fileDir}");
}
scriptWriter.WriteLine(".");
}
}
}
}
/// <summary>
/// Prebuilt tool module for tar
/// </summary>
sealed class TarCompiler :
Bam.Core.PreBuiltTool
{
/// <summary>
/// \copydoc Bam.Core.ITool.SettingsType
/// </summary>
public override System.Type SettingsType => typeof(TarBallSettings);
/// <summary>
/// Executable path to the tar compiler
/// </summary>
public override Bam.Core.TokenizedString Executable => Bam.Core.TokenizedString.CreateVerbatim(Bam.Core.OSUtilities.GetInstallLocation("tar").First());
}
/// <summary>
/// Derive from this module to create a tarball of the specified files.
/// </summary>
[Bam.Core.PlatformFilter(Bam.Core.EPlatform.Linux | Bam.Core.EPlatform.OSX)]
abstract class TarBall :
Bam.Core.Module
{
/// <summary>
/// Path key to the tarball
/// </summary>
public const string TarBallKey = "TarBall Installer";
private TarInputFiles InputFiles;
/// <summary>
/// Initialize the module
/// </summary>
protected override void
Init()
{
base.Init();
this.RegisterGeneratedFile(
TarBallKey,
this.CreateTokenizedString("$(buildroot)/$(config)/$(OutputName)$(tarext)")
);
this.InputFiles = Bam.Core.Module.Create<TarInputFiles>();
this.DependsOn(this.InputFiles);
this.Tool = Bam.Core.Graph.Instance.FindReferencedModule<TarCompiler>();
this.Requires(this.Tool);
}
/// <summary>
/// Include the specified file into the tarball.
/// </summary>
/// <param name="key">Key.</param>
/// <typeparam name="DependentModule">The 1st type parameter.</typeparam>
public void
Include<DependentModule>(
string key
) where DependentModule : Bam.Core.Module, new()
{
var dependent = Bam.Core.Graph.Instance.FindReferencedModule<DependentModule>();
if (null == dependent)
{
return;
}
this.InputFiles.AddFile(dependent, key);
}
/// <summary>
/// Include the folder into the tarball, usually one of the results of Publishing collation.
/// </summary>
/// <param name="key">Key.</param>
/// <typeparam name="DependentModule">The 1st type parameter.</typeparam>
public void
SourceFolder<DependentModule>(
string key
) where DependentModule : Bam.Core.Module, new()
{
var dependent = Bam.Core.Graph.Instance.FindReferencedModule<DependentModule>();
if (null == dependent)
{
return;
}
this.InputFiles.AddPath(dependent, key);
}
protected sealed override void
EvaluateInternal()
{
// do nothing
}
/// <summary>
/// Execute the tool on this module
/// </summary>
/// <param name="context">in this context</param>
protected sealed override void
ExecuteInternal(
Bam.Core.ExecutionContext context)
{
switch (Bam.Core.Graph.Instance.Mode)
{
#if D_PACKAGE_MAKEFILEBUILDER
case "MakeFile":
MakeFileBuilder.Support.Add(this);
break;
#endif
#if D_PACKAGE_NATIVEBUILDER
case "Native":
NativeBuilder.Support.RunCommandLineTool(this, context);
break;
#endif
#if D_PACKAGE_XCODEBUILDER
case "Xcode":
Bam.Core.Log.DebugMessage("Tar not supported on Xcode builds");
break;
#endif
default:
throw new System.NotSupportedException();
}
}
/// <summary>
/// /copydoc Bam.Core.Module.InputModulePaths
/// </summary>
public override System.Collections.Generic.IEnumerable<(Bam.Core.Module module, string pathKey)> InputModulePaths
{
get
{
yield return this.InputFiles.ModulePathTuple;
}
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using MLifter.BusinessLayer;
using MLifter.Controls.Properties;
using MLifter.Components;
namespace MLifter.Controls.LearningWindow
{
/// <summary>
/// The main learning window.
/// </summary>
/// <remarks>Documented by Dev02, 2008-04-22</remarks>
public partial class LearningWindow : UserControl, ILearnUserControl
{
private LearnLogic learnlogic = null;
private int stackHeight = -1;
private int windowWidth = -1;
/// <summary>
/// Initializes a new instance of the <see cref="LearningWindow"/> class.
/// </summary>
/// <remarks>Documented by Dev02, 2008-04-22</remarks>
public LearningWindow()
{
InitializeComponent();
splitContainerHorizontal.Panel1MinSize = Settings.Default.QuestionAnswerPanelMinHeight;
dockingButtonStack.Text = StackVisible ? Resources.DOCKING_BUTTON_STACK_HIDE : Resources.DOCKING_BUTTON_STACK_SHOW;
if (StackVisible)
stackHeight = splitContainerHorizontal.Height - splitContainerHorizontal.SplitterDistance;
windowWidth = splitContainerVertical.Width - splitContainerVertical.SplitterDistance;
this.VisibleChanged += new EventHandler(LearningWindow_VisibleChanged);
answerPanel.FileDropped += new FileDroppedEventHandler(Panel_FileDropped);
questionPanel.FileDropped += new FileDroppedEventHandler(Panel_FileDropped);
answerPanel.BrowserKeyDown += new PreviewKeyDownEventHandler(Panel_BrowserKeyDown);
questionPanel.BrowserKeyDown += new PreviewKeyDownEventHandler(Panel_BrowserKeyDown);
buttonsPanelMainControl.ButtonNextClicked += new EventHandler(buttonsPanelMainControl_ButtonNextClicked);
buttonsPanelMainControl.ButtonPreviousCardClicked += new EventHandler(buttonsPanelMainControl_ButtonPreviousCardClicked);
buttonsPanelMainControl.ButtonQuestionClicked += new EventHandler(buttonsPanelMainControl_ButtonQuestionClicked);
buttonsPanelMainControl.ButtonSelfAssesmentDontKnowClicked += new EventHandler(buttonsPanelMainControl_ButtonSelfAssesmentDontKnowClicked);
buttonsPanelMainControl.ButtonSelfAssesmentDoKnowClicked += new EventHandler(buttonsPanelMainControl_ButtonSelfAssesmentDoKnowClicked);
answerPanel.SelfAssesmentKeyUp += new EventHandler(answerPanel_SelfAssesmentButtonDoKnowClick);
answerPanel.SelfAssesmentKeyDown += new EventHandler(answerPanel_SelfAssesmentButtonDontKnowClick);
answerPanel.SetButtonFocus += new LearnLogic.CardStateChangedEventHandler(answerPanel_SetButtonFocus);
}
public void UpdateCulture()
{
answerPanel.UpdateCulture();
buttonsPanelMainControl.UpdateCulture();
dockingButtonStack.Text = new ComponentResourceManager(this.GetType()).GetString(dockingButtonStack.Name + ".Text");
}
void answerPanel_SetButtonFocus(object sender, CardStateChangedEventArgs e)
{
buttonsPanelMainControl.SetButtonFocus(e);
}
private void answerPanel_SelfAssesmentButtonDontKnowClick(object sender, EventArgs e)
{
buttonsPanelMainControl.SelfAssesmentClickDontKnow();
}
private void answerPanel_SelfAssesmentButtonDoKnowClick(object sender, EventArgs e)
{
buttonsPanelMainControl.SelfAssesmentClickDoKnow();
}
/// <summary>
/// Handles the ButtonSelfAssesmentDoKnowClicked event of the buttonsPanelMainControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev07, 2009-04-16</remarks>
private void buttonsPanelMainControl_ButtonSelfAssesmentDoKnowClicked(object sender, EventArgs e)
{
answerPanel.SubmitSelfAssessmentReponse(true, false);
}
private void buttonsPanelMainControl_ButtonSelfAssesmentDontKnowClicked(object sender, EventArgs e)
{
answerPanel.SubmitSelfAssessmentReponse(false, false);
}
/// <summary>
/// Handles the ButtonQuestionClicked event of the buttonsPanelMainControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev07, 2009-04-16</remarks>
private void buttonsPanelMainControl_ButtonQuestionClicked(object sender, EventArgs e)
{
answerPanel.CheckAnswer();
}
private void buttonsPanelMainControl_ButtonPreviousCardClicked(object sender, EventArgs e)
{
questionPanel.showPreviousCard();
}
/// <summary>
/// Handles the ButtonNextClicked event of the buttonsPanelMainControl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev07, 2009-04-16</remarks>
private void buttonsPanelMainControl_ButtonNextClicked(object sender, EventArgs e)
{
answerPanel.ShowNextCard();
}
/// <summary>
/// Handles the VisibleChanged event of the LearningWindow control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-06</remarks>
private void LearningWindow_VisibleChanged(object sender, EventArgs e)
{
//ensure that the learning window always is at the top of the z order
if (this.Visible)
this.BringToFront();
else
MLifter.Components.InfoBar.CleanUpInfobars(splitContainerHorizontal.Panel1);
}
#region LearnLogic Registration
/// <summary>
/// Registers the learn logic.
/// </summary>
/// <param name="learnlogic">The learnlogic.</param>
/// <remarks>Documented by Dev02, 2008-04-22</remarks>
public void RegisterLearnLogic(LearnLogic learnlogic)
{
if (this.learnlogic == null || this.learnlogic != learnlogic)
{
this.learnlogic = learnlogic;
RegisterLearnLogicAllControls(this.Controls);
RegisterLearnLogicAllComponents(this.components.Components);
this.Visible = learnlogic.DictionaryReadyForLearning;
this.learnlogic.LearningModuleClosed += new EventHandler(learnlogic_LearningModuleClosed);
this.learnlogic.LearningModuleOptionsChanged += new EventHandler(learnlogic_LearningModuleOptionsChanged);
this.learnlogic.UserDialog += new LearnLogic.UserDialogEventHandler(learnlogic_UserDialog);
this.learnlogic.OnLearningModuleOptionsChanged();
}
}
/// <summary>
/// Handles the LearningModuleOptionsChanged event of the learnlogic control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-06</remarks>
private void learnlogic_LearningModuleOptionsChanged(object sender, EventArgs e)
{
this.Visible = learnlogic.DictionaryReadyForLearning;
MLifter.Components.InfoBar.CleanUpInfobars(this);
MLifter.Components.InfoBar.CleanUpInfobars(answerPanel.InfoBarControl);
}
/// <summary>
/// Handles the LearningModuleClosed event of the learnlogic control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-06</remarks>
private void learnlogic_LearningModuleClosed(object sender, EventArgs e)
{
this.Visible = false;
}
/// <summary>
/// Registers the learn logic all controls.
/// </summary>
/// <param name="controls">The controls.</param>
/// <remarks>Documented by Dev02, 2008-04-22</remarks>
private void RegisterLearnLogicAllControls(ControlCollection controls)
{
foreach (Control control in controls)
{
RegisterLearnLogicObject(control);
if (control.Controls.Count > 0)
RegisterLearnLogicAllControls(control.Controls);
}
}
/// <summary>
/// Registers the learn logic all components.
/// </summary>
/// <param name="components">The components.</param>
/// <remarks>Documented by Dev02, 2008-04-24</remarks>
private void RegisterLearnLogicAllComponents(ComponentCollection components)
{
foreach (Component component in components)
RegisterLearnLogicObject(component);
}
/// <summary>
/// Registers the learn logic object.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="type">The type.</param>
/// <remarks>Documented by Dev02, 2008-04-24</remarks>
private void RegisterLearnLogicObject(Object obj)
{
//check for each object if it has a "RegisterLearnLogic"-Method, and invoke it, if yes
//System.Reflection.MethodInfo registermethod = obj.GetType().GetMethod("RegisterLearnLogic");
//if (registermethod != null && registermethod.GetParameters().Length == 1)
// if (registermethod.GetParameters()[0].Name == "learnlogic" && registermethod.GetParameters()[0].ParameterType == typeof(LearnLogic))
// registermethod.Invoke(obj, new object[] { learnlogic });
//check for each object if it implements the ILearnUserControl interface
if (obj is ILearnUserControl)
((ILearnUserControl)obj).RegisterLearnLogic(learnlogic);
}
#endregion
/// <summary>
/// Gets or sets a value indicating whether [stack visible].
/// </summary>
/// <value><c>true</c> if [stack visible]; otherwise, <c>false</c>.</value>
/// <remarks>Documented by Dev02, 2008-04-24</remarks>
[DefaultValue(typeof(bool), "True")]
public bool StackVisible
{
get
{
return !splitContainerHorizontal.Panel2Collapsed;
}
set
{
splitContainerHorizontal.Panel2Collapsed = !value;
dockingButtonStack.Text = StackVisible ? Resources.DOCKING_BUTTON_STACK_HIDE : Resources.DOCKING_BUTTON_STACK_SHOW;
}
}
/// <summary>
/// Gets or sets the "layout values" (Splitter Positions).
/// If the stack if hidden, it returns the old splitter value multiplied with -1.
/// </summary>
/// <value>The layout values.</value>
/// <remarks>Documented by Dev02, 2008-05-06</remarks>
[Browsable(false), ReadOnly(true)]
public Size LayoutValues
{
get
{
if (!this.Visible)
return new Size(windowWidth, stackHeight);
//bool wasVisible = this.Visible;
//this.Visible = true;
this.SuspendLayout();
//control must be visible for the layout logic to work (performlayout does not seem to suffice)
int width, height;
if (StackVisible)
stackHeight = height = splitContainerHorizontal.Height - splitContainerHorizontal.SplitterDistance;
else
height = stackHeight;
windowWidth = width = splitContainerVertical.Width - splitContainerVertical.SplitterDistance;
//if (!StackVisible)
// height = height * (-1);
this.ResumeLayout();
//this.Visible = wasVisible;
return new Size(width, height);
}
set
{
//control must be visible for the layout logic to work (performlayout does not seem to suffice)
bool wasVisible = this.Visible;
this.Visible = true;
this.SuspendLayout();
int horizontalSplitterDistance = splitContainerHorizontal.Height - Math.Abs(value.Height);
int verticalSplitterDistance = splitContainerVertical.Width - value.Width;
if (horizontalSplitterDistance > 0 && horizontalSplitterDistance < splitContainerHorizontal.Height)
splitContainerHorizontal.SplitterDistance = horizontalSplitterDistance;
if (verticalSplitterDistance > 0 && verticalSplitterDistance < splitContainerVertical.Width)
splitContainerVertical.SplitterDistance = verticalSplitterDistance;
if (value.Height < 0)
StackVisible = false;
stackHeight = value.Height;
this.ResumeLayout();
this.Visible = wasVisible;
}
}
/// <summary>
/// Occurs when [file dropped].
/// </summary>
/// <remarks>Documented by Dev02, 2008-05-08</remarks>
[Description("Occurs when a file was dropped onto this control.")]
public event FileDroppedEventHandler FileDropped;
/// <summary>
/// Raises the <see cref="E:FileDropped"/> event.
/// </summary>
/// <param name="e">The <see cref="MLifter.Controls.LearningWindow.FileDroppedEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-08</remarks>
private void OnFileDropped(FileDroppedEventArgs e)
{
if (FileDropped != null)
FileDropped(this, e);
}
/// <summary>
/// Handles the FileDropped event of the Panel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MLifter.Controls.LearningWindow.FileDroppedEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-08</remarks>
void Panel_FileDropped(object sender, FileDroppedEventArgs e)
{
OnFileDropped(e);
}
/// <summary>
/// Occurs when [browser key down].
/// </summary>
/// <remarks>Documented by Dev02, 2008-05-13</remarks>
public event PreviewKeyDownEventHandler BrowserKeyDown;
/// <summary>
/// Handles the BrowserKeyDown event of the Panel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.PreviewKeyDownEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-13</remarks>
void Panel_BrowserKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//[ML-1568] Hitting 'Enter' should always go to the next card
if (e.KeyCode == Keys.Enter && answerPanel.ResultPageVisible)
answerPanel.ShowNextCard();
if (BrowserKeyDown != null)
BrowserKeyDown(sender, e);
}
/// <summary>
/// Sets the stack card back colors.
/// </summary>
/// <param name="styleHandler">The style handler.</param>
/// <remarks>Documented by Dev02, 2008-05-09</remarks>
public void SetStackCardBackColors(MLifter.Components.StyleHandler styleHandler)
{
stackFlow.SetStackCardBackColors(styleHandler);
}
/// <summary>
/// Handles the UserDialog event of the learnlogic control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MLifter.BusinessLayer.UserDialogEventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev02, 2008-05-21</remarks>
void learnlogic_UserDialog(object sender, UserDialogEventArgs e)
{
if (e is UserNotifyDialogEventArgs)
{
UserNotifyDialogEventArgs args = (UserNotifyDialogEventArgs)e;
string message = string.Empty;
bool dontShowAgainMessage = false;
switch (args.dialogkind)
{
case UserNotifyDialogEventArgs.NotifyDialogKind.PoolEmpty:
message = Properties.Resources.POOL_EMPTY_TEXT;
break;
case UserNotifyDialogEventArgs.NotifyDialogKind.NotEnoughMultipleChoices:
message = string.Format(Properties.Resources.MULTIPLE_CHOICE_TEXT, e.dictionary.Settings.MultipleChoiceOptions.NumberOfChoices.Value);
break;
case UserNotifyDialogEventArgs.NotifyDialogKind.SelectedLearnModeNotAllowed:
if (Settings.Default.DontShowSelectedLearnModeNotAllowedMessage)
break;
dontShowAgainMessage = true;
//[ML-2115] LearnModes for Infobar not localized
message = string.Format(Properties.Resources.SELECTED_LEARNMODE_NOT_ALLOWED,
(e.OptionalParamter is MLifter.BusinessLayer.LearnModes) ? Resources.ResourceManager.GetString("LEARNING_MODE_" + e.OptionalParamter.ToString().ToUpper()) : e.OptionalParamter);
break;
case UserNotifyDialogEventArgs.NotifyDialogKind.NoWords:
//gets displayed in UserDialogComponent
break;
default:
break;
}
if (!string.IsNullOrEmpty(message))
{
InfoBar infobar;
infobar = new InfoBar(message, answerPanel.InfoBarControl, DockStyle.Top, true, dontShowAgainMessage, answerPanel.AdditionalInfoBarSuspendControl);
infobar.DontShowAgainChanged += new EventHandler(infobar_DontShowAgainChanged);
}
}
}
/// <summary>
/// Handles the DontShowAgainChanged event of the infobar control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev08, 2009-04-10</remarks>
private void infobar_DontShowAgainChanged(object sender, EventArgs e)
{
if (sender is InfoBar)
{
Settings.Default.DontShowSelectedLearnModeNotAllowedMessage = ((InfoBar)sender).DontShowAgain;
Settings.Default.Save();
}
}
/// <summary>
/// Handles the Click event of the dockingButtonStack control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks>Documented by Dev08, 2009-04-16</remarks>
private void dockingButtonStack_Click(object sender, EventArgs e)
{
StackVisible = !StackVisible;
if (StackVisible)
stackHeight = Math.Abs(stackHeight);
else
stackHeight = Math.Abs(stackHeight) * -1;
}
private void stackFlow_SizeChanged(object sender, EventArgs e)
{
if (StackVisible)
stackHeight = stackFlow.Height;
}
private void questionPanel_SizeChanged(object sender, EventArgs e)
{
windowWidth = splitContainerVertical.Width - splitContainerVertical.SplitterDistance;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableDictionary<TKey, TValue>
{
/// <summary>
/// A dictionary that mutates with little or no memory allocations,
/// can produce and/or build on immutable dictionary instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/>
/// and other bulk change methods already provide fast bulk change operations on the collection, this class allows
/// multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))]
public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// The root of the binary tree that stores the collection. Contents are typically not entirely frozen.
/// </summary>
private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode;
/// <summary>
/// The comparers.
/// </summary>
private Comparers _comparers;
/// <summary>
/// The number of elements in this collection.
/// </summary>
private int _count;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableDictionary<TKey, TValue> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class.
/// </summary>
/// <param name="map">The map that serves as the basis for this Builder.</param>
internal Builder(ImmutableDictionary<TKey, TValue> map)
{
Requires.NotNull(map, "map");
_root = map._root;
_count = map._count;
_comparers = map._comparers;
_immutable = map;
}
/// <summary>
/// Gets or sets the key comparer.
/// </summary>
/// <value>
/// The key comparer.
/// </value>
public IEqualityComparer<TKey> KeyComparer
{
get
{
return _comparers.KeyComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.KeyComparer)
{
var comparers = Comparers.Get(value, this.ValueComparer);
var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers, 0);
var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input);
_immutable = null;
_comparers = comparers;
_count = result.CountAdjustment; // offset from 0
this.Root = result.Root;
}
}
}
/// <summary>
/// Gets or sets the value comparer.
/// </summary>
/// <value>
/// The value comparer.
/// </value>
public IEqualityComparer<TValue> ValueComparer
{
get
{
return _comparers.ValueComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.ValueComparer)
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
_comparers = _comparers.WithValueComparer(value);
_immutable = null; // invalidate cached immutable
}
}
}
#region IDictionary<TKey, TValue> Properties
/// <summary>
/// Gets the number of elements contained in the <see cref="ICollection{T}"/>.
/// </summary>
/// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TKey> Keys
{
get
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
yield return item.Key;
}
}
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TValue> Values
{
get
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
yield return item.Value;
}
}
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
this.Remove((TKey)key);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
#endregion
#region ICollection methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (var item in this)
{
array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++);
}
}
#endregion
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets the initial data to pass to a query or mutation method.
/// </summary>
private MutationInput Origin
{
get { return new MutationInput(this.Root, _comparers, _count); }
}
/// <summary>
/// Gets or sets the root of this data structure.
/// </summary>
private SortedInt32KeyNode<HashBucket> Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>The element with the specified key.</returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception>
/// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception>
public TValue this[TKey key]
{
get
{
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin);
this.Apply(result);
}
}
#region Public Methods
/// <summary>
/// Adds a sequence of values to this collection.
/// </summary>
/// <param name="items">The items.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin);
this.Apply(result);
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="keys">The keys for entries to remove from the dictionary.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
foreach (var key in keys)
{
this.Remove(key);
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_root, this);
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
/// <summary>
/// Creates an immutable dictionary based on the contents of this instance.
/// </summary>
/// <returns>An immutable map.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableDictionary<TKey, TValue> ToImmutable()
{
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count);
}
return _immutable;
}
#endregion
#region IDictionary<TKey, TValue> Members
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception>
/// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception>
public void Add(TKey key, TValue value)
{
var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin);
this.Apply(result);
}
/// <summary>
/// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param>
/// <returns>
/// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool ContainsKey(TKey key)
{
return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin);
}
/// <summary>
/// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (this.ValueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
///
/// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception>
public bool Remove(TKey key)
{
var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin);
return this.Apply(result);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool TryGetValue(TKey key, out TValue value)
{
return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey);
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception>
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception>
public void Clear()
{
this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode;
_count = 0;
}
/// <summary>
/// Determines whether the <see cref="ICollection{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin);
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Requires.NotNull(array, "array");
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Members
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>.
/// </returns>
/// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
// Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well.
if (this.Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
#endregion
#region IEnumerator<T> methods
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Applies the result of some mutation operation to this instance.
/// </summary>
/// <param name="result">The result.</param>
private bool Apply(MutationResult result)
{
this.Root = result.Root;
_count += result.CountAdjustment;
return result.CountAdjustment != 0;
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableDictionary<TKey, TValue>.Builder _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull(map, "map");
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray(_map.Count);
}
return _contents;
}
}
}
}
| |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Elastic.Clients.Elasticsearch.Aggregations;
using Elastic.Transport;
namespace Elastic.Clients.Elasticsearch
{
internal sealed class TestAttribute : Attribute { }
internal sealed class ResolvableDictionaryFormatterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) => false;
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();
}
//internal sealed class ReadOnlyDictionaryConverter
internal sealed class ReadOnlyIndexNameDictionaryConverter : JsonConverterAttribute
{
public ReadOnlyIndexNameDictionaryConverter(Type valueType) => ValueType = valueType;
public Type ValueType { get; }
public override JsonConverter? CreateConverter(Type typeToConvert) => (JsonConverter)Activator.CreateInstance(typeof(IntermediateConverter<>).MakeGenericType(ValueType));
}
internal sealed class IntermediateConverter<TValue> : JsonConverter<IReadOnlyDictionary<IndexName, TValue>>
{
public override IReadOnlyDictionary<IndexName, TValue>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var converter = options.GetConverter(typeof(ReadOnlyIndexNameDictionary<>).MakeGenericType(typeof(TValue)));
if (converter is ReadOnlyIndexNameDictionaryConverter<TValue> specialisedConverter)
{
return specialisedConverter.Read(ref reader, typeToConvert, options);
}
return null;
}
public override void Write(Utf8JsonWriter writer, IReadOnlyDictionary<IndexName, TValue> value, JsonSerializerOptions options) => throw new NotImplementedException();
}
internal sealed class ReadOnlyIndexNameDictionaryConverterFactory : JsonConverterFactory
{
private readonly IElasticsearchClientSettings _settings;
public ReadOnlyIndexNameDictionaryConverterFactory(IElasticsearchClientSettings settings) => _settings = settings;
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
var canConvert = typeof(ReadOnlyIndexNameDictionary<>) == typeToConvert.GetGenericTypeDefinition();
return canConvert;
}
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
{
var valueType = type.GetGenericArguments()[0];
return (JsonConverter)Activator.CreateInstance(typeof(ReadOnlyIndexNameDictionaryConverter<>).MakeGenericType(valueType), _settings);
}
//private class ReadOnlyIndexNameDictionaryConverter<TValue> : JsonConverter<ReadOnlyIndexNameDictionary<TValue>>
//{
// private readonly IElasticsearchClientSettings _settings;
// public ReadOnlyIndexNameDictionaryConverter(IElasticsearchClientSettings settings) => _settings = settings;
// public override ReadOnlyIndexNameDictionary<TValue>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
// {
// var initialDictionary = JsonSerializer.Deserialize<Dictionary<IndexName, TValue>>(ref reader, options);
// var readOnlyDictionary = new ReadOnlyIndexNameDictionary<TValue>(initialDictionary, _settings);
// return readOnlyDictionary;
// }
// public override void Write(Utf8JsonWriter writer, ReadOnlyIndexNameDictionary<TValue> value, JsonSerializerOptions options) => throw new NotImplementedException();
//}
}
internal sealed class SourceConverterAttribute : JsonConverterAttribute
{
public override JsonConverter? CreateConverter(Type typeToConvert) => (JsonConverter)Activator.CreateInstance(typeof(IntermediateSourceConverter<>).MakeGenericType(typeToConvert));
}
internal sealed class IntermediateSourceConverter<T> : JsonConverter<T>
{
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var converter = options.GetConverter(typeof(SourceMarker<>).MakeGenericType(typeToConvert));
if (converter is SourceConverter<T> sourceConverter)
{
var source = sourceConverter.Read(ref reader, typeToConvert, options);
return source.Source;
}
return default;
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
var converter = options.GetConverter(typeof(SourceMarker<>).MakeGenericType(typeof(T)));
if (converter is SourceConverter<T> sourceConverter)
{
sourceConverter.Write(writer, new SourceMarker<T> { Source = value }, options);
}
}
}
internal sealed class SourceConverterFactory : JsonConverterFactory
{
private readonly IElasticsearchClientSettings _settings;
public SourceConverterFactory(IElasticsearchClientSettings settings) => _settings = settings;
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
var canConvert = typeof(SourceMarker<>) == typeToConvert.GetGenericTypeDefinition();
return canConvert;
}
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
{
var valueType = type.GetGenericArguments()[0];
return (JsonConverter)Activator.CreateInstance(typeof(SourceConverter<>).MakeGenericType(valueType), _settings);
}
}
internal interface ISourceMarker<T> { }
internal sealed class SourceMarker<T>
{
public T Source { get; set; }
}
internal sealed class SourceConverter<T> : JsonConverter<SourceMarker<T>>
{
private readonly IElasticsearchClientSettings _settings;
public SourceConverter(IElasticsearchClientSettings settings) => _settings = settings;
public override SourceMarker<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => new()
{
Source = SourceSerialisation.Deserialize<T>(ref reader, _settings)
};
public override void Write(Utf8JsonWriter writer, SourceMarker<T> value, JsonSerializerOptions options) => SourceSerialisation.Serialize<T>(value.Source, writer, _settings);
}
internal sealed class ReadOnlyIndexNameDictionaryConverter<TValue> : JsonConverter<IReadOnlyDictionary<IndexName, TValue>>
{
private readonly IElasticsearchClientSettings _settings;
public ReadOnlyIndexNameDictionaryConverter(IElasticsearchClientSettings settings) => _settings = settings;
public override IReadOnlyDictionary<IndexName, TValue>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var initialDictionary = JsonSerializer.Deserialize<Dictionary<IndexName, TValue>>(ref reader, options);
var readOnlyDictionary = new ReadOnlyIndexNameDictionary<TValue>(initialDictionary, _settings);
return readOnlyDictionary;
}
public override void Write(Utf8JsonWriter writer, IReadOnlyDictionary<IndexName, TValue> value, JsonSerializerOptions options) => throw new NotImplementedException();
}
/// <summary>
/// A specialised readonly dictionary for <typeparamref name="TValue"/> data, keyed by <see cref="IndexName"/>.
/// <para>This supports inferrence enabled lookups by ensuring keys are sanitized when storing the values and when performing lookups.</para>
/// </summary>
/// <typeparam name="TValue"></typeparam>
public struct ReadOnlyIndexNameDictionary<TValue> : IReadOnlyDictionary<IndexName, TValue>
{
private readonly Dictionary<IndexName, TValue> _backingDictionary;
private readonly IElasticsearchClientSettings? _settings;
public ReadOnlyIndexNameDictionary()
{
_backingDictionary = new Dictionary<IndexName,TValue>(0);
_settings = null;
}
internal ReadOnlyIndexNameDictionary(Dictionary<IndexName, TValue> source, IElasticsearchClientSettings settings)
{
_settings = settings;
// This is an "optimised version" which doesn't cause a second dictionary to be allocated.
// Since we expect this to be used only for deserialisation, the keys received will already have been strings,
// so no further sanitisation is required.
//var backingDictionary = new Dictionary<IndexName, TValue>(source.Count);
if (source == null)
{
_backingDictionary = new Dictionary<IndexName, TValue>(0);
return;
}
//foreach (var key in source.Keys)
// backingDictionary[Sanitize(key)] = source[key];
_backingDictionary = source;
}
private string Sanitize(IndexName key) => _settings is not null ? key?.GetString(_settings) : string.Empty;
public TValue this[IndexName key] => _backingDictionary.TryGetValue(Sanitize(key), out var v) ? v : default;
public TValue this[string key] => _backingDictionary.TryGetValue(key, out var v) ? v : default;
public IEnumerable<IndexName> Keys => _backingDictionary.Keys;
public IEnumerable<TValue> Values => _backingDictionary.Values;
public int Count => _backingDictionary.Count;
public bool ContainsKey(IndexName key) => _backingDictionary.ContainsKey(Sanitize(key));
public IEnumerator<KeyValuePair<IndexName, TValue>> GetEnumerator() => _backingDictionary.GetEnumerator();
public bool TryGetValue(IndexName key, out TValue value) => _backingDictionary.TryGetValue(Sanitize(key), out value);
IEnumerator IEnumerable.GetEnumerator() => _backingDictionary.GetEnumerator();
}
internal static class SerializationConstants
{
public const byte Newline = (byte)'\n';
}
internal static class AggregationContainerSerializationHelper
{
public static AggregationContainer ReadContainer<T>(ref Utf8JsonReader reader, JsonSerializerOptions options) where T : AggregationBase
{
var variant = JsonSerializer.Deserialize<T?>(ref reader, options);
var container = new AggregationContainer(variant);
return container;
}
public static AggregationContainer ReadContainer<T>(string variantName, ref Utf8JsonReader reader, JsonSerializerOptions options) where T : AggregationBase
{
var variant = JsonSerializer.Deserialize<T?>(ref reader, options);
//variant.Name = variantName;
var container = new AggregationContainer(variant);
//reader.Read();
return container;
}
}
internal static class UtilExtensions
{
private const long MillisecondsInAWeek = MillisecondsInADay * 7;
private const long MillisecondsInADay = MillisecondsInAnHour * 24;
private const long MillisecondsInAnHour = MillisecondsInAMinute * 60;
private const long MillisecondsInAMinute = MillisecondsInASecond * 60;
private const long MillisecondsInASecond = 1000;
internal static string Utf8String(this byte[] bytes) => bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length);
internal static string Utf8String(this MemoryStream ms)
{
if (ms is null)
return null;
if (!ms.TryGetBuffer(out var buffer) || buffer.Array is null)
return Encoding.UTF8.GetString(ms.ToArray());
return Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
}
//internal static byte[] Utf8Bytes(this string s) => s.IsNullOrEmpty() ? null : Encoding.UTF8.GetBytes(s);
//internal static void ThrowIfEmpty<T>(this IEnumerable<T> @object, string parameterName)
//{
// var enumerated = @object == null ? null : (@object as T[] ?? @object.ToArray());
// enumerated.ThrowIfNull(parameterName);
// if (!enumerated!.Any())
// throw new ArgumentException("Argument can not be an empty collection", parameterName);
//}
//internal static bool HasAny<T>(this IEnumerable<T> list) => list != null && list.Any();
//internal static bool HasAny<T>(this IEnumerable<T> list, out T[] enumerated)
//{
// enumerated = list == null ? null : (list as T[] ?? list.ToArray());
// return enumerated.HasAny();
//}
//internal static Exception AsAggregateOrFirst(this IEnumerable<Exception> exceptions)
//{
// var es = exceptions as Exception[] ?? exceptions?.ToArray();
// if (es == null || es.Length == 0)
// return null;
// return es.Length == 1 ? es[0] : new AggregateException(es);
//}
//internal static void ThrowIfNull<T>(this T value, string name) where T : class
//{
// if (value == null)
// throw new ArgumentNullException(name);
//}
//internal static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value);
//internal static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property) =>
// items.GroupBy(property).Select(x => x.First());
//internal static string ToTimeUnit(this TimeSpan timeSpan)
//{
// var ms = timeSpan.TotalMilliseconds;
// string interval;
// double factor;
// if (ms >= MillisecondsInAWeek)
// {
// factor = ms / MillisecondsInAWeek;
// interval = "w";
// }
// else if (ms >= MillisecondsInADay)
// {
// factor = ms / MillisecondsInADay;
// interval = "d";
// }
// else if (ms >= MillisecondsInAnHour)
// {
// factor = ms / MillisecondsInAnHour;
// interval = "h";
// }
// else if (ms >= MillisecondsInAMinute)
// {
// factor = ms / MillisecondsInAMinute;
// interval = "m";
// }
// else if (ms >= MillisecondsInASecond)
// {
// factor = ms / MillisecondsInASecond;
// interval = "s";
// }
// else
// {
// factor = ms;
// interval = "ms";
// }
// return factor.ToString("0.##", CultureInfo.InvariantCulture) + interval;
//}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// A simple coordination data structure that we use for fork/join style parallelism.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Represents a synchronization primitive that is signaled when its count reaches zero.
/// </summary>
/// <remarks>
/// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used
/// concurrently from multiple threads, with the exception of Dispose, which
/// must only be used when all other operations on the <see cref="CountdownEvent"/> have
/// completed, and Reset, which should only be used when no other threads are
/// accessing the event.
/// </remarks>
[DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")]
public class CountdownEvent : IDisposable
{
// CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a
// latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can
// wait on the latch at any point; when the latch count reaches 0, all threads are woken and
// subsequent waiters return without waiting. The implementation internally lazily creates a true
// Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a
// wait.
private int _initialCount; // The original # of signals the latch was instantiated with.
private volatile int _currentCount; // The # of outstanding signals before the latch transitions to a signaled state.
private ManualResetEventSlim _event; // An event used to manage blocking and signaling.
private volatile bool _disposed; // Whether the latch has been disposed.
/// <summary>
/// Initializes a new instance of <see cref="T:System.Threading.CountdownEvent"/> class with the
/// specified count.
/// </summary>
/// <param name="initialCount">The number of signals required to set the <see
/// cref="T:System.Threading.CountdownEvent"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less
/// than 0.</exception>
public CountdownEvent(int initialCount)
{
if (initialCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(initialCount));
}
_initialCount = initialCount;
_currentCount = initialCount;
// Allocate a thin event, which internally defers creation of an actual Win32 event.
_event = new ManualResetEventSlim();
// If the latch was created with a count of 0, then it's already in the signaled state.
if (initialCount == 0)
{
_event.Set();
}
}
/// <summary>
/// Gets the number of remaining signals required to set the event.
/// </summary>
/// <value>
/// The number of remaining signals required to set the event.
/// </value>
public int CurrentCount
{
get
{
int observedCount = _currentCount;
return observedCount < 0 ? 0 : observedCount;
}
}
/// <summary>
/// Gets the numbers of signals initially required to set the event.
/// </summary>
/// <value>
/// The number of signals initially required to set the event.
/// </value>
public int InitialCount
{
get { return _initialCount; }
}
/// <summary>
/// Determines whether the event is set.
/// </summary>
/// <value>true if the event is set; otherwise, false.</value>
public bool IsSet
{
get
{
// The latch is "completed" if its current count has reached 0. Note that this is NOT
// the same thing is checking the event's IsCompleted property. There is a tiny window
// of time, after the final decrement of the current count to 0 and before setting the
// event, where the two values are out of sync.
return (_currentCount <= 0);
}
}
/// <summary>
/// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.
/// </summary>
/// <value>A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been disposed.</exception>
/// <remarks>
/// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases
/// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/>
/// to be set, the <see cref="Wait()"/> method should be preferred.
/// </remarks>
public WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
return _event.WaitHandle;
}
}
/// <summary>
/// Releases all resources used by the current instance of <see cref="T:System.Threading.CountdownEvent"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
public void Dispose()
{
// Gets rid of this latch's associated resources. This can consist of a Win32 event
// which is (lazily) allocated by the underlying thin event. This method is not safe to
// call concurrently -- i.e. a caller must coordinate to ensure only one thread is using
// the latch at the time of the call to Dispose.
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// When overridden in a derived class, releases the unmanaged resources used by the
/// <see cref="T:System.Threading.CountdownEvent"/>, and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release
/// only unmanaged resources.</param>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_event.Dispose();
_disposed = true;
}
}
/// <summary>
/// Registers a signal with the <see cref="T:System.Threading.CountdownEvent"/>, decrementing its
/// count.
/// </summary>
/// <returns>true if the signal caused the count to reach zero and the event was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.InvalidOperationException">The current instance is already set.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Signal()
{
ThrowIfDisposed();
Debug.Assert(_event != null);
if (_currentCount <= 0)
{
throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
}
#pragma warning disable 0420
int newCount = Interlocked.Decrement(ref _currentCount);
#pragma warning restore 0420
if (newCount == 0)
{
_event.Set();
return true;
}
else if (newCount < 0)
{
//if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here
//because there was a thread already which decremented it to zero and set the event
throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
}
return false;
}
/// <summary>
/// Registers multiple signals with the <see cref="T:System.Threading.CountdownEvent"/>,
/// decrementing its count by the specified amount.
/// </summary>
/// <param name="signalCount">The number of signals to register.</param>
/// <returns>true if the signals caused the count to reach zero and the event was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.InvalidOperationException">
/// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see
/// cref="CurrentCount"/>.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
/// than 1.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Signal(int signalCount)
{
if (signalCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(signalCount));
}
ThrowIfDisposed();
Debug.Assert(_event != null);
int observedCount;
SpinWait spin = new SpinWait();
while (true)
{
observedCount = _currentCount;
// If the latch is already signaled, we will fail.
if (observedCount < signalCount)
{
throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
}
// This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning
// for this statement. This warning is clearly senseless for Interlocked operations.
#pragma warning disable 0420
if (Interlocked.CompareExchange(ref _currentCount, observedCount - signalCount, observedCount) == observedCount)
#pragma warning restore 0420
{
break;
}
// The CAS failed. Spin briefly and try again.
spin.SpinOnce();
}
// If we were the last to signal, set the event.
if (observedCount == signalCount)
{
_event.Set();
return true;
}
Debug.Assert(_currentCount >= 0, "latch was decremented below zero");
return false;
}
/// <summary>
/// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The current instance is already
/// set.</exception>
/// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="T:System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The current instance has already been disposed.
/// </exception>
public void AddCount()
{
AddCount(1);
}
/// <summary>
/// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one.
/// </summary>
/// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
/// already at zero. this will return false.</returns>
/// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="T:System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool TryAddCount()
{
return TryAddCount(1);
}
/// <summary>
/// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a specified
/// value.
/// </summary>
/// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than
/// 0.</exception>
/// <exception cref="T:System.InvalidOperationException">The current instance is already
/// set.</exception>
/// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="T:System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void AddCount(int signalCount)
{
if (!TryAddCount(signalCount))
{
throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyZero);
}
}
/// <summary>
/// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a
/// specified value.
/// </summary>
/// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
/// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
/// already at zero this will return false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
/// than 0.</exception>
/// <exception cref="T:System.InvalidOperationException">The current instance is already
/// set.</exception>
/// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
/// cref="T:System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool TryAddCount(int signalCount)
{
if (signalCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(signalCount));
}
ThrowIfDisposed();
// Loop around until we successfully increment the count.
int observedCount;
SpinWait spin = new SpinWait();
while (true)
{
observedCount = _currentCount;
if (observedCount <= 0)
{
return false;
}
else if (observedCount > (Int32.MaxValue - signalCount))
{
throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyMax);
}
// This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning
// for this statement. This warning is clearly senseless for Interlocked operations.
#pragma warning disable 0420
if (Interlocked.CompareExchange(ref _currentCount, observedCount + signalCount, observedCount) == observedCount)
#pragma warning restore 0420
{
break;
}
// The CAS failed. Spin briefly and try again.
spin.SpinOnce();
}
return true;
}
/// <summary>
/// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed..</exception>
public void Reset()
{
Reset(_initialCount);
}
/// <summary>
/// Resets the <see cref="CurrentCount"/> to a specified value.
/// </summary>
/// <param name="count">The number of signals required to set the <see
/// cref="T:System.Threading.CountdownEvent"/>.</param>
/// <remarks>
/// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not
/// thread-safe and may not be used concurrently with other members of this instance.
/// </remarks>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="count"/> is
/// less than 0.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has alread been disposed.</exception>
public void Reset(int count)
{
ThrowIfDisposed();
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
_currentCount = count;
_initialCount = count;
if (count == 0)
{
_event.Set();
}
else
{
_event.Reset();
}
}
/// <summary>
/// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set.
/// </summary>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void Wait()
{
Wait(Timeout.Infinite, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, while
/// observing a <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <remarks>
/// The caller of this method blocks indefinitely until the current instance is set. The caller will
/// return immediately if the event is currently in a set state. If the
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> being observed
/// is canceled during the wait operation, an <see cref="T:System.OperationCanceledException"/>
/// will be thrown.
/// </remarks>
/// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been
/// canceled.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public void Wait(CancellationToken cancellationToken)
{
Wait(Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a
/// <see cref="T:System.TimeSpan"/> to measure the time interval.
/// </summary>
/// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of
/// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to
/// wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Wait(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using
/// a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a
/// <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of
/// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to
/// wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
/// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
/// than <see cref="System.Int32.MaxValue"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has
/// been canceled.</exception>
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
return Wait((int)totalMilliseconds, cancellationToken);
}
/// <summary>
/// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a
/// 32-bit signed integer to measure the time interval.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
public bool Wait(int millisecondsTimeout)
{
return Wait(millisecondsTimeout, new CancellationToken());
}
/// <summary>
/// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a
/// 32-bit signed integer to measure the time interval, while observing a
/// <see cref="T:System.Threading.CancellationToken"/>.
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
/// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
/// observe.</param>
/// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
/// false.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has already been
/// disposed.</exception>
/// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has
/// been canceled.</exception>
public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
}
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
bool returnValue = IsSet;
// If not completed yet, wait on the event.
if (!returnValue)
{
// ** the actual wait
returnValue = _event.Wait(millisecondsTimeout, cancellationToken);
//the Wait will throw OCE itself if the token is canceled.
}
return returnValue;
}
// --------------------------------------
// Private methods
/// <summary>
/// Throws an exception if the latch has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException("CountdownEvent");
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.Modules.Scripting
{
public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager
{
//private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int ALL_SIDES = -1;
public const int DISP_EXPIRE = 1;
public const int DISP_TEMP = 2;
private readonly Dictionary<UUID, IScene> RegisteredScenes = new Dictionary<UUID, IScene>();
private readonly Dictionary<string, IDynamicTextureRender> RenderPlugins =
new Dictionary<string, IDynamicTextureRender>();
private readonly Dictionary<UUID, DynamicTextureUpdater> Updaters =
new Dictionary<UUID, DynamicTextureUpdater>();
public bool IsSharedModule
{
get { return true; }
}
#region IDynamicTextureManager Members
public void RegisterRender(string handleType, IDynamicTextureRender render)
{
if (!RenderPlugins.ContainsKey(handleType))
{
RenderPlugins.Add(handleType, render);
}
}
/// <summary>
/// Called by code which actually renders the dynamic texture to supply texture data.
/// </summary>
/// <param name = "id"></param>
/// <param name = "data"></param>
public void ReturnData(UUID id, byte[] data)
{
DynamicTextureUpdater updater = null;
lock (Updaters)
{
if (Updaters.ContainsKey(id))
{
updater = Updaters[id];
}
}
if (updater != null)
{
if (RegisteredScenes.ContainsKey(updater.SimUUID))
{
IScene scene = RegisteredScenes[updater.SimUUID];
updater.DataReceived(data, scene);
}
}
if (updater.UpdateTimer == 0)
{
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Remove(updater.UpdaterID);
}
}
}
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, UUID oldAssetID, string contentType, string url,
string extraParams, int updateTimer)
{
return AddDynamicTextureURL(simID, primID, oldAssetID, contentType, url, extraParams, updateTimer, false,
255);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, UUID oldAssetID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureURL(simID, primID, oldAssetID, contentType, url,
extraParams, updateTimer, SetBlending,
(DISP_TEMP | DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, UUID oldAssetID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending,
int disp, byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
{
DynamicTextureUpdater updater = new DynamicTextureUpdater
{
SimUUID = simID,
PrimID = primID,
ContentType = contentType,
Url = url,
UpdateTimer = updateTimer,
UpdaterID = UUID.Random(),
Params = extraParams,
BlendWithOldTexture = SetBlending,
FrontAlpha = AlphaValue,
Face = face,
Disp = disp,
LastAssetID = oldAssetID
};
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
return updater.UpdaterID;
}
return UUID.Zero;
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, UUID oldAssetID, string contentType, string data,
string extraParams, int updateTimer)
{
return AddDynamicTextureData(simID, primID, oldAssetID, contentType, data, extraParams, updateTimer, false,
255);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, UUID oldAssetID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureData(simID, primID, oldAssetID, contentType, data, extraParams, updateTimer,
SetBlending,
(DISP_TEMP | DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, UUID oldAssetID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, int disp,
byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
{
DynamicTextureUpdater updater = new DynamicTextureUpdater
{
SimUUID = simID,
PrimID = primID,
ContentType = contentType,
BodyData = data,
UpdateTimer = updateTimer,
UpdaterID = UUID.Random(),
Params = extraParams,
BlendWithOldTexture = SetBlending,
FrontAlpha = AlphaValue,
Face = face,
Url = "Local image",
Disp = disp,
LastAssetID = oldAssetID
};
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
return updater.UpdaterID;
}
return UUID.Zero;
}
public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
if (RenderPlugins.ContainsKey(contentType))
{
RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize);
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
}
public void AddRegion(IScene scene)
{
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
scene.RegisterModuleInterface<IDynamicTextureManager>(this);
}
}
public void RemoveRegion(IScene scene)
{
}
public void RegionLoaded(IScene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "DynamicTextureModule"; }
}
#endregion
#region Nested type: DynamicTextureUpdater
public class DynamicTextureUpdater
{
public bool BlendWithOldTexture;
public string BodyData;
public string ContentType;
public int Disp;
public int Face;
public byte FrontAlpha = 255;
public UUID LastAssetID = UUID.Zero;
public string Params;
public UUID PrimID;
public bool SetNewFrontAlpha;
public UUID SimUUID;
public int UpdateTimer;
public UUID UpdaterID;
public string Url;
public DynamicTextureUpdater()
{
UpdateTimer = 0;
BodyData = null;
}
/// <summary>
/// Called once new texture data has been received for this updater.
/// </summary>
public void DataReceived(byte[] data, IScene scene)
{
ISceneChildEntity part = scene.GetSceneObjectPart(PrimID);
if (part == null || data == null || data.Length <= 1)
{
string msg =
String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
IChatModule chatModule = scene.RequestModuleInterface<IChatModule>();
if (chatModule != null)
chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
part.ParentEntity.AbsolutePosition, part.Name, part.UUID, false, scene);
return;
}
byte[] assetData = null;
AssetBase oldAsset = null;
if (BlendWithOldTexture)
{
Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
if (defaultFace != null)
{
oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());
if (oldAsset != null)
assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha, scene);
}
}
if (assetData == null)
{
assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length);
}
AssetBase asset = null;
if (LastAssetID != UUID.Zero)
{
asset = scene.AssetService.Get(LastAssetID.ToString());
asset.Description = String.Format("URL image : {0}", Url);
asset.Data = assetData;
if ((asset.Flags & AssetFlags.Local) == AssetFlags.Local)
{
asset.Flags = asset.Flags & ~AssetFlags.Local;
}
if (((asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) != ((Disp & DISP_TEMP) != 0))
{
if ((Disp & DISP_TEMP) != 0) asset.Flags |= AssetFlags.Temporary;
else asset.Flags = asset.Flags & ~AssetFlags.Temporary;
}
asset.ID = scene.AssetService.Store(asset);
}
else
{
// Create a new asset for user
asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000),
AssetType.Texture,
scene.RegionInfo.RegionID)
{Data = assetData, Description = String.Format("URL image : {0}", Url)};
if ((Disp & DISP_TEMP) != 0) asset.Flags = AssetFlags.Temporary;
asset.ID = scene.AssetService.Store(asset);
}
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
{
cacheLayerDecode.Decode(asset.ID, asset.Data);
cacheLayerDecode = null;
LastAssetID = asset.ID;
}
UUID oldID = UUID.Zero;
lock (part)
{
// mostly keep the values from before
Primitive.TextureEntry tmptex = part.Shape.Textures;
// remove the old asset from the cache
oldID = tmptex.DefaultTexture.TextureID;
if (Face == ALL_SIDES)
{
tmptex.DefaultTexture.TextureID = asset.ID;
}
else
{
try
{
Primitive.TextureEntryFace texface = tmptex.CreateFace((uint) Face);
texface.TextureID = asset.ID;
tmptex.FaceTextures[Face] = texface;
}
catch (Exception)
{
tmptex.DefaultTexture.TextureID = asset.ID;
}
}
// I'm pretty sure we always want to force this to true
// I'm pretty sure noone whats to set fullbright true if it wasn't true before.
// tmptex.DefaultTexture.Fullbright = true;
part.UpdateTexture(tmptex, true);
}
if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
{
if (oldAsset == null) oldAsset = scene.AssetService.Get(oldID.ToString());
if (oldAsset != null)
{
if ((oldAsset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary)
{
scene.AssetService.Delete(oldID);
}
}
}
}
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha,
IScene scene)
{
Image image = scene.RequestModuleInterface<IJ2KDecoder>().DecodeToImage(frontImage);
if (image != null)
{
Bitmap image1 = new Bitmap(image);
image = scene.RequestModuleInterface<IJ2KDecoder>().DecodeToImage(backImage);
if (image != null)
{
Bitmap image2 = new Bitmap(image);
if (setNewAlpha)
SetAlpha(ref image1, newAlpha);
Bitmap joint = MergeBitMaps(image1, image2);
byte[] result = new byte[0];
try
{
result = OpenJPEG.EncodeFromImage(joint, true);
}
catch (Exception)
{
MainConsole.Instance.Error("[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Empty byte data returned!");
}
return result;
}
}
return null;
}
public Bitmap MergeBitMaps(Bitmap front, Bitmap back)
{
Bitmap joint;
Graphics jG;
joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb);
jG = Graphics.FromImage(joint);
jG.DrawImage(back, 0, 0, back.Width, back.Height);
jG.DrawImage(front, 0, 0, back.Width, back.Height);
return joint;
}
private void SetAlpha(ref Bitmap b, byte alpha)
{
for (int w = 0; w < b.Width; w++)
{
for (int h = 0; h < b.Height; h++)
{
b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h)));
}
}
}
}
#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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_DynamicArgument()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
/*<bind>*/c.M2(d)/*</bind>*/;
}
public void M2(int i)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(d)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_MultipleApplicableSymbols()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c.M2(d)/*</bind>*/;
}
public void M2(int i)
{
}
public void M2(long i)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(d)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_MultipleArgumentsAndApplicableSymbols()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
char ch = 'c';
var x = /*<bind>*/c.M2(d, ch)/*</bind>*/;
}
public void M2(int i, char ch)
{
}
public void M2(long i, char ch)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(d, ch)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ILocalReferenceExpression: ch (OperationKind.LocalReferenceExpression, Type: System.Char) (Syntax: 'ch')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_ArgumentNames()
{
string source = @"
class C
{
void M(C c, dynamic d, dynamic e)
{
var x = /*<bind>*/c.M2(i: d, ch: e)/*</bind>*/;
}
public void M2(int i, char ch)
{
}
public void M2(long i, char ch)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(i: d, ch: e)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""ch""
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_ArgumentRefKinds()
{
string source = @"
class C
{
void M(C c, object d, dynamic e)
{
int k;
var x = /*<bind>*/c.M2(ref d, out k, e)/*</bind>*/;
}
public void M2(ref object i, out int j, char c)
{
j = 0;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(ref d, out k, e)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(3):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'd')
ILocalReferenceExpression: k (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'k')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(0)
ArgumentRefKinds(3):
Ref
Out
None
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_DelegateInvocation()
{
string source = @"
using System;
class C
{
public Action<object> F;
void M(dynamic i)
{
var x = /*<bind>*/F(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'F(i)')
Expression:
IFieldReferenceExpression: System.Action<System.Object> C.F (OperationKind.FieldReferenceExpression, Type: System.Action<System.Object>) (Syntax: 'F')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'F')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0649: Field 'C.F' is never assigned to, and will always have its default value null
// public Action<object> F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "null").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_WithDynamicReceiver()
{
string source = @"
class C
{
void M(dynamic d, int i)
{
var x = /*<bind>*/d(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'd(i)')
Expression:
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_WithDynamicMemberReceiver()
{
string source = @"
class C
{
void M(dynamic c, int i)
{
var x = /*<bind>*/c.M2(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(i)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: dynamic) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_WithDynamicTypedMemberReceiver()
{
string source = @"
class C
{
dynamic M2 = null;
void M(C c, int i)
{
var x = /*<bind>*/c.M2(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(i)')
Expression:
IFieldReferenceExpression: dynamic C.M2 (OperationKind.FieldReferenceExpression, Type: dynamic) (Syntax: 'c.M2')
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_AllFields()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
int i = 0;
var x = /*<bind>*/c.M2(ref i, c: d)/*</bind>*/;
}
public void M2(ref int i, char c)
{
}
public void M2(ref int i, long c)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(ref i, c: d)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(2):
""null""
""c""
ArgumentRefKinds(2):
Ref
None
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_ErrorBadDynamicMethodArgLambda()
{
string source = @"
using System;
class C
{
public void M(C c)
{
dynamic y = null;
var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/;
}
public void M2(Action a, Action y)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic, IsInvalid) (Syntax: 'c.M2(delegate { }, y)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IAnonymousFunctionExpression (Symbol: lambda expression) (OperationKind.AnonymousFunctionExpression, Type: null, IsInvalid) (Syntax: 'delegate { }')
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: '{ }')
IReturnStatement (OperationKind.ReturnStatement, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
ILocalReferenceExpression: y (OperationKind.LocalReferenceExpression, Type: dynamic) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_OverloadResolutionFailure()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c.M2(d)/*</bind>*/;
}
public void M2()
{
}
public void M2(int i, int j)
{
}
}
";
string expectedOperationTree = @"
IInvalidExpression (OperationKind.InvalidExpression, Type: System.Void, IsInvalid) (Syntax: 'c.M2(d)')
Children(2):
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C, IsInvalid) (Syntax: 'c')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic, IsInvalid) (Syntax: 'd')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.M2(int, int)'
// var x = /*<bind>*/c.M2(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("j", "C.M2(int, int)").WithLocation(6, 29),
// CS0815: Cannot assign void to an implicitly-typed variable
// var x = /*<bind>*/c.M2(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/c.M2(d)").WithArguments("void").WithLocation(6, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapAttributeSchema.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using Novell.Directory.Ldap.Utilclass;
namespace Novell.Directory.Ldap
{
/// <summary> The definition of an attribute type in the schema.
///
/// LdapAttributeSchema is used to discover an attribute's
/// syntax, and add or delete an attribute definition.
/// RFC 2252, "Lightweight Directory Access Protocol (v3):
/// Attribute Syntax Definitions" contains a description
/// of the information on the Ldap representation of schema.
/// draft-sermerseim-nds-ldap-schema-02, "Ldap Schema for NDS"
/// defines the schema descriptions and non-standard syntaxes
/// used by Novell eDirectory.
///
/// </summary>
/// <seealso cref="LdapSchema">
/// </seealso>
public class LdapAttributeSchema:LdapSchemaElement
{
private void InitBlock()
{
usage = USER_APPLICATIONS;
}
/// <summary> Returns the object identifer of the syntax of the attribute, in
/// dotted numerical format.
///
/// </summary>
/// <returns> The object identifer of the attribute's syntax.
/// </returns>
virtual public System.String SyntaxString
{
get
{
return syntaxString;
}
}
/// <summary> Returns the name of the attribute type which this attribute derives
/// from, or null if there is no superior attribute.
///
/// </summary>
/// <returns> The attribute's superior attribute, or null if there is none.
/// </returns>
virtual public System.String Superior
{
get
{
return superior;
}
}
/// <summary> Returns true if the attribute is single-valued.
///
/// </summary>
/// <returns> True if the attribute is single-valued; false if the attribute
/// is multi-valued.
/// </returns>
virtual public bool SingleValued
{
get
{
return single;
}
}
/// <summary> Returns the matching rule for this attribute.
///
/// </summary>
/// <returns> The attribute's equality matching rule; null if it has no equality
/// matching rule.
/// </returns>
virtual public System.String EqualityMatchingRule
{
get
{
return equality;
}
}
/// <summary> Returns the ordering matching rule for this attribute.
///
/// </summary>
/// <returns> The attribute's ordering matching rule; null if it has no ordering
/// matching rule.
/// </returns>
virtual public System.String OrderingMatchingRule
{
get
{
return ordering;
}
}
/// <summary> Returns the substring matching rule for this attribute.
///
/// </summary>
/// <returns> The attribute's substring matching rule; null if it has no substring
/// matching rule.
/// </returns>
virtual public System.String SubstringMatchingRule
{
get
{
return substring;
}
}
/// <summary> Returns true if the attribute is a collective attribute.
///
/// </summary>
/// <returns> True if the attribute is a collective; false if the attribute
/// is not a collective attribute.
/// </returns>
virtual public bool Collective
{
get
{
return collective;
}
}
/// <summary> Returns false if the attribute is read-only.
///
/// </summary>
/// <returns> False if the attribute is read-only; true if the attribute
/// is read-write.
/// </returns>
virtual public bool UserModifiable
{
get
{
return userMod;
}
}
/// <summary> Returns the usage of the attribute.
///
/// </summary>
/// <returns> One of the following values: USER_APPLICATIONS,
/// DIRECTORY_OPERATION, DISTRIBUTED_OPERATION or
/// DSA_OPERATION.
/// </returns>
virtual public int Usage
{
get
{
return usage;
}
}
private System.String syntaxString;
private bool single = false;
private System.String superior;
private System.String equality;
private System.String ordering;
private System.String substring;
private bool collective = false;
private bool userMod = true;
private int usage;
/// <summary> Indicates that the attribute usage is for ordinary application
/// or user data.
/// </summary>
public const int USER_APPLICATIONS = 0;
/// <summary> Indicates that the attribute usage is for directory operations.
/// Values are vendor specific.
/// </summary>
public const int DIRECTORY_OPERATION = 1;
/// <summary> Indicates that the attribute usage is for distributed operational
/// attributes. These hold server (DSA) information that is shared among
/// servers holding replicas of the entry.
/// </summary>
public const int DISTRIBUTED_OPERATION = 2;
/// <summary> Indicates that the attribute usage is for local operational attributes.
/// These hold server (DSA) information that is local to a server.
/// </summary>
public const int DSA_OPERATION = 3;
/// <summary> Constructs an attribute definition for adding to or deleting from a
/// directory's schema.
///
/// </summary>
/// <param name="names">Names of the attribute.
///
/// </param>
/// <param name="oid"> Object identifer of the attribute, in
/// dotted numerical format.
///
/// </param>
/// <param name="description"> Optional description of the attribute.
///
/// </param>
/// <param name="syntaxString"> Object identifer of the syntax of the
/// attribute, in dotted numerical format.
///
/// </param>
/// <param name="single"> True if the attribute is to be single-valued.
///
/// </param>
/// <param name="superior"> Optional name of the attribute type which this
/// attribute type derives from; null if there is no
/// superior attribute type.
///
/// </param>
/// <param name="obsolete"> True if the attribute is obsolete.
///
/// </param>
/// <param name="equality"> Optional matching rule name; null if there is not
/// an equality matching rule for this attribute.
///
/// </param>
/// <param name="ordering">Optional matching rule name; null if there is not
/// an ordering matching rule for this attribute.
///
/// </param>
/// <param name="substring"> Optional matching rule name; null if there is not
/// a substring matching rule for this attribute.
///
/// </param>
/// <param name="collective"> True of this attribute is a collective attribute
///
/// </param>
/// <param name="isUserModifiable"> False if this attribute is a read-only attribute
///
/// </param>
/// <param name="usage"> Describes what the attribute is used for. Must be
/// one of the following: USER_APPLICATIONS,
/// DIRECTORY_OPERATION, DISTRIBUTED_OPERATION or
/// DSA_OPERATION.
/// </param>
public LdapAttributeSchema(System.String[] names, System.String oid, System.String description, System.String syntaxString, bool single, System.String superior, bool obsolete, System.String equality, System.String ordering, System.String substring, bool collective, bool isUserModifiable, int usage):base(LdapSchema.schemaTypeNames[LdapSchema.ATTRIBUTE])
{
InitBlock();
base.names = names;
base.oid = oid;
base.description = description;
base.obsolete = obsolete;
this.syntaxString = syntaxString;
this.single = single;
this.equality = equality;
this.ordering = ordering;
this.substring = substring;
this.collective = collective;
this.userMod = isUserModifiable;
this.usage = usage;
this.superior = superior;
base.Value = formatString();
return ;
}
/// <summary> Constructs an attribute definition from the raw string value returned
/// on a directory query for "attributetypes".
///
/// </summary>
/// <param name="raw"> The raw string value returned on a directory
/// query for "attributetypes".
/// </param>
public LdapAttributeSchema(System.String raw):base(LdapSchema.schemaTypeNames[LdapSchema.ATTRIBUTE])
{
InitBlock();
try
{
SchemaParser parser = new SchemaParser(raw);
if (parser.Names != null)
base.names = parser.Names;
if ((System.Object) parser.ID != null)
base.oid = parser.ID;
if ((System.Object) parser.Description != null)
base.description = parser.Description;
if ((System.Object) parser.Syntax != null)
syntaxString = parser.Syntax;
if ((System.Object) parser.Superior != null)
superior = parser.Superior;
single = parser.Single;
base.obsolete = parser.Obsolete;
System.Collections.IEnumerator qualifiers = parser.Qualifiers;
AttributeQualifier attrQualifier;
while (qualifiers.MoveNext())
{
attrQualifier = (AttributeQualifier) qualifiers.Current;
setQualifier(attrQualifier.Name, attrQualifier.Values);
}
base.Value = formatString();
}
catch (System.IO.IOException e)
{
throw new System.SystemException(e.ToString());
}
return ;
}
/// <summary> Returns a string in a format suitable for directly adding to a
/// directory, as a value of the particular schema element attribute.
///
/// </summary>
/// <returns> A string representation of the attribute's definition.
/// </returns>
protected internal override System.String formatString()
{
System.Text.StringBuilder valueBuffer = new System.Text.StringBuilder("( ");
System.String token;
System.String[] strArray;
if ((System.Object) (token = ID) != null)
{
valueBuffer.Append(token);
}
strArray = Names;
if (strArray != null)
{
valueBuffer.Append(" NAME ");
if (strArray.Length == 1)
{
valueBuffer.Append("'" + strArray[0] + "'");
}
else
{
valueBuffer.Append("( ");
for (int i = 0; i < strArray.Length; i++)
{
valueBuffer.Append(" '" + strArray[i] + "'");
}
valueBuffer.Append(" )");
}
}
if ((System.Object) (token = Description) != null)
{
valueBuffer.Append(" DESC ");
valueBuffer.Append("'" + token + "'");
}
if (Obsolete)
{
valueBuffer.Append(" OBSOLETE");
}
if ((System.Object) (token = Superior) != null)
{
valueBuffer.Append(" SUP ");
valueBuffer.Append("'" + token + "'");
}
if ((System.Object) (token = EqualityMatchingRule) != null)
{
valueBuffer.Append(" EQUALITY ");
valueBuffer.Append("'" + token + "'");
}
if ((System.Object) (token = OrderingMatchingRule) != null)
{
valueBuffer.Append(" ORDERING ");
valueBuffer.Append("'" + token + "'");
}
if ((System.Object) (token = SubstringMatchingRule) != null)
{
valueBuffer.Append(" SUBSTR ");
valueBuffer.Append("'" + token + "'");
}
if ((System.Object) (token = SyntaxString) != null)
{
valueBuffer.Append(" SYNTAX ");
valueBuffer.Append(token);
}
if (SingleValued)
{
valueBuffer.Append(" SINGLE-VALUE");
}
if (Collective)
{
valueBuffer.Append(" COLLECTIVE");
}
if (UserModifiable == false)
{
valueBuffer.Append(" NO-USER-MODIFICATION");
}
int useType;
if ((useType = Usage) != USER_APPLICATIONS)
{
switch (useType)
{
case DIRECTORY_OPERATION:
valueBuffer.Append(" USAGE directoryOperation");
break;
case DISTRIBUTED_OPERATION:
valueBuffer.Append(" USAGE distributedOperation");
break;
case DSA_OPERATION:
valueBuffer.Append(" USAGE dSAOperation");
break;
default:
break;
}
}
System.Collections.IEnumerator en = QualifierNames;
while (en.MoveNext())
{
token = ((System.String) en.Current);
if (((System.Object) token != null))
{
valueBuffer.Append(" " + token);
strArray = getQualifier(token);
if (strArray != null)
{
if (strArray.Length > 1)
valueBuffer.Append("(");
for (int i = 0; i < strArray.Length; i++)
{
valueBuffer.Append(" '" + strArray[i] + "'");
}
if (strArray.Length > 1)
valueBuffer.Append(" )");
}
}
}
valueBuffer.Append(" )");
return valueBuffer.ToString();
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
namespace OpenSim.Region.Framework.Scenes
{
public partial class Scene
{
/// <summary>
/// Sends a chat message to clients in the region
/// </summary>
/// <param name="message">The message to send to users</param>
/// <param name="type">The type of message (say, shout, whisper, owner say, etc)</param>
/// <param name="channel">The channel to speak the message on</param>
/// <param name="part">The SceneObjectPart that is sending this chat message</param>
public void SimChat(string message, ChatTypeEnum type, int channel, SceneObjectPart part)
{
SimChat(message, type, channel, part.AbsolutePosition, part.Name, part.UUID, UUID.Zero, part.OwnerID, false);
}
/// <summary>
/// Sends a chat message to clients in the region
/// </summary>
/// <param name="message">The message to send to users</param>
/// <param name="type">The type of message (say, shout, whisper, owner say, etc)</param>
/// <param name="channel">The channel to speak the message on</param>
/// <param name="part">The SceneObjectPart that is sending this chat message</param>
/// <param name="destID">The user or object that is being spoken to (UUID.Zero specifies all users will get the message)</param>
/// <param name="broadcast">Whether the message will be sent regardless of distance from the sender</param>
public void SimChat(string message, ChatTypeEnum type, int channel, SceneObjectPart part,
UUID destID, bool broadcast = false)
{
SimChat(message, type, channel, part.AbsolutePosition, part.Name, part.UUID, destID, part.OwnerID, broadcast);
}
/// <summary>
/// Sends a chat message to clients in the region
/// </summary>
/// <param name="message">The message to send to users</param>
/// <param name="type">The type of message (say, shout, whisper, owner say, etc)</param>
/// <param name="channel">The channel to speak the message on</param>
/// <param name="presence">The ScenePresence that is sending this chat message</param>
public void SimChat(string message, ChatTypeEnum type, int channel, ScenePresence presence)
{
SimChat(message, type, channel, presence.AbsolutePosition, presence.Name, presence.UUID, UUID.Zero, presence.UUID, false);
}
/// <summary>
/// Sends a chat message to clients in the region
/// </summary>
/// <param name="message">The message to send to users</param>
/// <param name="type">The type of message (say, shout, whisper, owner say, etc)</param>
/// <param name="channel">The channel to speak the message on</param>
/// <param name="presence">The ScenePresence that is sending this chat message</param>
/// <param name="destID">The user or object that is being spoken to (UUID.Zero specifies all users will get the message)</param>
/// <param name="broadcast">Whether the message will be sent regardless of distance from the sender</param>
public void SimChat(string message, ChatTypeEnum type, int channel, ScenePresence presence,
UUID destID, bool broadcast = false)
{
SimChat(message, type, channel, presence.AbsolutePosition, presence.Name, presence.UUID, destID, presence.UUID, broadcast);
}
/// <summary>
/// Sends a chat message to clients in the region
/// </summary>
/// <param name="message">The message to send to users</param>
/// <param name="type">The type of message (say, shout, whisper, owner say, etc)</param>
/// <param name="channel">The channel to speak the message on</param>
/// <param name="fromPos">The position of the speaker (the SceneObjectPart or ScenePresence)</param>
/// <param name="fromName">The name of the speaker (the SceneObjectPart or ScenePresence)</param>
/// <param name="fromID">The UUID of the speaker (the SceneObjectPart or ScenePresence)</param>
/// <param name="destID">The user or object that is being spoken to (UUID.Zero specifies all users will get the message)</param>
/// <param name="generatingAvatarID">The avatar ID that has generated this message regardless of
/// if it is a script owned by this avatar, or the avatar itself</param>
/// <param name="broadcast">Whether the message will be sent regardless of distance from the sender</param>
public void SimChat(string message, ChatTypeEnum type, int channel, Vector3 fromPos,
string fromName, UUID fromID, UUID destID, UUID generatingAvatarID, bool broadcast)
{
OSChatMessage args = new OSChatMessage()
{
Channel = channel,
DestinationUUID = destID,
From = fromName,
GeneratingAvatarID = generatingAvatarID,
Message = message,
Position = fromPos,
Scene = this,
SenderUUID = fromID,
Type = type
};
if (broadcast)
EventManager.TriggerOnChatBroadcast(this, args);
else
EventManager.TriggerOnChatFromWorld(this, args);
}
/// <summary>
/// Invoked when the client requests a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void RequestPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectGroup obj = this.GetGroupByPrim(primLocalID);
if (obj != null)
{
//The viewer didn't have the cached prim like we thought - force a full update
// so that they will get the full prim
obj.SendFullUpdateToClient(remoteClient, PrimUpdateFlags.ForcedFullUpdate);
}
return;
}
/// <summary>
/// Invoked when the client selects a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectGroup group = m_sceneGraph.GetGroupByPrim(primLocalID);
if (group == null) return;
if (group.LocalId == primLocalID)
{
group.GetProperties(remoteClient);
group.IsSelected = true;
// A prim is only tainted if it's allowed to be edited by the person clicking it.
if (Permissions.CanEditObject(group.UUID, remoteClient.AgentId,0)
|| Permissions.CanMoveObject(group.UUID, remoteClient.AgentId))
{
EventManager.TriggerParcelPrimCountTainted();
}
}
else
{
//it's one of the child prims
SceneObjectPart part = group.GetChildPart(primLocalID);
part.GetProperties(remoteClient);
}
}
/// <summary>
/// Handle the deselection of a prim from the client.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void DeselectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (part == null)
return;
// The prim is in the process of being deleted.
if (null == part.ParentGroup.RootPart)
return;
// A deselect packet contains all the local prims being deselected. However, since selection is still
// group based we only want the root prim to trigger a full update - otherwise on objects with many prims
// we end up sending many duplicate ObjectUpdates
if (part.ParentGroup.RootPart.LocalId != part.LocalId)
return;
bool isAttachment = false;
// This is wrong, wrong, wrong. Selection should not be
// handled by group, but by prim. Legacy cruft.
// TODO: Make selection flagging per prim!
//
part.ParentGroup.IsSelected = false;
if (part.ParentGroup.IsAttachment)
isAttachment = true;
// Regardless of if it is an attachment or not, we need to resend the position in case it moved or changed.
part.ParentGroup.ScheduleGroupForFullUpdate(PrimUpdateFlags.FindBest);
// If it's not an attachment, and we are allowed to move it,
// then we might have done so. If we moved across a parcel
// boundary, we will need to recount prims on the parcels.
// For attachments, that makes no sense.
//
if (!isAttachment)
{
if (Permissions.CanEditObject(
part.ParentGroup.UUID, remoteClient.AgentId, 0)
|| Permissions.CanMoveObject(
part.ParentGroup.UUID, remoteClient.AgentId))
EventManager.TriggerParcelPrimCountTainted();
}
}
public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
int transactiontype, string description)
{
EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount,
transactiontype, description);
EventManager.TriggerMoneyTransfer(this, args);
}
public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned,
bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated)
{
EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned,
removeContribution, parcelLocalID, parcelArea,
parcelPrice, authenticated);
// First, allow all validators a stab at it
m_eventManager.TriggerValidateLandBuy(this, args);
// Then, check validation and transfer
m_eventManager.TriggerLandBuy(this, args);
}
public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
SceneObjectGroup obj = this.GetGroupByPrim(localID);
if (obj != null)
{
// Is this prim part of the group
if (obj.HasChildPrim(localID))
{
// Currently only grab/touch for the single prim
// the client handles rez correctly
obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
SceneObjectPart part = obj.GetChildPart(localID);
int touchEvents = ((int)ScriptEvents.touch_start | (int)ScriptEvents.touch | (int)ScriptEvents.touch_end);
bool hasTouchEvent = (((int)part.ScriptEvents & touchEvents) != 0);
// If the touched prim handles touches, deliver it
if (hasTouchEvent)
EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// If not, or if PassTouches and we haven't just delivered it to the root prim, deliver it there
if ((!hasTouchEvent) || (part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
}
}
public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
SceneObjectGroup obj = this.GetGroupByPrim(localID);
// Is this prim part of the group
if (obj != null && obj.HasChildPrim(localID))
{
SceneObjectPart part=obj.GetChildPart(localID);
SceneObjectGroup group = part.ParentGroup;
if (part != null)
{
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
ScriptEvents eventsThatNeedDegrab = (ScriptEvents.touch_end | ScriptEvents.touch);
if ((part.ScriptEvents & eventsThatNeedDegrab) != 0)
{
EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg);
}
else if ((group.RootPart.ScriptEvents & eventsThatNeedDegrab) != 0)
{
EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg);
}
// Always send an object degrab.
m_sceneGraph.DegrabObject(localID, remoteClient, surfaceArgs);
return;
}
return;
}
}
public void ProcessAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query)
{
//EventManager.TriggerAvatarPickerRequest();
List<AvatarPickerAvatar> AvatarResponses = new List<AvatarPickerAvatar>();
AvatarResponses = m_sceneGridService.GenerateAgentPickerRequestResponse(RequestID, query);
AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
// TODO: don't create new blocks if recycling an old packet
AvatarPickerReplyPacket.DataBlock[] searchData =
new AvatarPickerReplyPacket.DataBlock[AvatarResponses.Count];
AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
agentData.AgentID = avatarID;
agentData.QueryID = RequestID;
replyPacket.AgentData = agentData;
//byte[] bytes = new byte[AvatarResponses.Count*32];
int i = 0;
foreach (AvatarPickerAvatar item in AvatarResponses)
{
UUID translatedIDtem = item.AvatarID;
searchData[i] = new AvatarPickerReplyPacket.DataBlock();
searchData[i].AvatarID = translatedIDtem;
searchData[i].FirstName = Utils.StringToBytes((string) item.firstName);
searchData[i].LastName = Utils.StringToBytes((string) item.lastName);
i++;
}
if (AvatarResponses.Count == 0)
{
searchData = new AvatarPickerReplyPacket.DataBlock[0];
}
replyPacket.Data = searchData;
AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs();
agent_data.AgentID = replyPacket.AgentData.AgentID;
agent_data.QueryID = replyPacket.AgentData.QueryID;
List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>();
for (i = 0; i < replyPacket.Data.Length; i++)
{
AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs();
data_arg.AvatarID = replyPacket.Data[i].AvatarID;
data_arg.FirstName = replyPacket.Data[i].FirstName;
data_arg.LastName = replyPacket.Data[i].LastName;
data_args.Add(data_arg);
}
client.SendAvatarPickerReply(agent_data, data_args);
}
public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID,
UUID itemID)
{
SceneObjectPart part=GetSceneObjectPart(objectID);
if (part == null)
return;
if (Permissions.CanResetScript(part.ParentGroup.UUID, itemID, remoteClient.AgentId))
{
EventManager.TriggerScriptReset(part.LocalId, itemID);
}
}
/// <summary>
/// Handle a fetch inventory request from the client
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="ownerID"></param>
public void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID)
{
if (ownerID == CommsManager.LibraryRoot.Owner)
{
//m_log.Debug("request info for library item");
return;
}
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
InventoryItemBase item = userProfile.FindItem(itemID);
if (item != null)
{
remoteClient.SendInventoryItemDetails(ownerID, item);
}
}
/// <summary>
/// Tell the client about the various child items and folders contained in the requested folder.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder)
{
// TODO: This code for looking in the folder for the library should be folded back into the
// CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold = null;
if ((fold = CommsManager.LibraryRoot.FindFolder(folderID)) != null)
{
remoteClient.SendInventoryFolderDetails(
fold.Owner, fold, fold.RequestListOfItems(),
fold.RequestListOfFolders(), fetchFolders, fetchItems);
return;
}
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
userProfile.SendInventoryDecendents(remoteClient, folderID, fetchFolders, fetchItems);
}
/// <summary>
/// Handle the caps inventory descendents fetch.
///
/// Since the folder structure is sent to the client on login, I believe we only need to handle items.
/// </summary>
/// <param name="agentID"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
/// <returns>null if the inventory look up failed</returns>
public List<InventoryItemBase> HandleFetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder)
{
// m_log.DebugFormat(
// "[INVENTORY CACHE]: Fetching folders ({0}), items ({1}) from {2} for agent {3}",
// fetchFolders, fetchItems, folderID, agentID);
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded back into the
// CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold;
if ((fold = CommsManager.LibraryRoot.FindFolder(folderID)) != null)
{
return fold.RequestListOfItems();
}
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(agentID);
if (null == userProfile)
{
m_log.ErrorFormat("[AGENT INVENTORY]: Could not find user profile for {0}", agentID);
return null;
}
if (UserDoesntOwnFolder(agentID, folderID))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not fetching descendents of {0} for user {1}, user does not own the folder",
folderID, agentID);
return null;
}
return null;
/*if ((fold = userProfile.FindFolderAtt(folderID)) != null)
{
return fold.RequestListOfItems();
}
else
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Could not find folder {0} requested by user {1}",
folderID, agentID);
return null;
}*/
}
/// <summary>
/// Handle an inventory folder creation request from the client.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="folderType"></param>
/// <param name="folderName"></param>
/// <param name="parentID"></param>
public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType,
string folderName, UUID parentID)
{
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
if (folderID == UUID.Zero)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not creating zero uuid folder for {0}",
remoteClient.Name);
return;
}
userProfile.CreateFolder(folderName, folderID, (short)folderType, parentID);
}
/// <summary>
/// Handle a client request to update the inventory folder
/// </summary>
///
/// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE
/// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing,
/// and needs to be changed.
///
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="parentID"></param>
public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name,
UUID parentID)
{
// m_log.DebugFormat(
// "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId);
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
InventoryFolderBase folder = userProfile.GetFolderAttributes(folderID);
if (folder.Owner != remoteClient.AgentId)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not updating folder {0} for user {2}, user does not own the folder",
folderID, remoteClient.Name);
return;
}
folder.Name = name;
folder.Type = (short)type;
folder.ParentID = parentID;
if (!userProfile.UpdateFolder(folder))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to update folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
private bool UserDoesntOwnFolder(UUID userId, UUID folderId)
{
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(userId);
//make sure the user owns the source folder
InventoryFolderBase folder = userProfile.GetFolderAttributes(folderId);
if (folder.Owner != userId)
{
return true;
}
return false;
}
/// <summary>
/// Handle an inventory folder move request from the client.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="parentID"></param>
public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID)
{
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
m_log.InfoFormat(
"[AGENT INVENTORY]: Moving folder {0} to {1} for user {2}",
folderID, parentID, remoteClient.Name);
if (!userProfile.MoveFolder(folderID, parentID))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to move folder {0} to {1} for user {2}",
folderID, parentID, remoteClient.Name);
}
}
/// <summary>
/// This should recursively delete all the items and folders in the given directory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID)
{
Util.FireAndForget(Util.PoolSelection.LongIO, delegate(object obj)
{
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
//make sure the user owns the source folder
InventoryFolderBase folder = userProfile.GetFolderAttributes(folderID);
if (folder.Owner != remoteClient.AgentId)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not purging descendents of {0} for user {1}, user does not own the folder",
folderID, remoteClient.Name);
return;
}
//make sure the folder is either the lost and found, the trash, or a descendant of it
if (!CheckFolderHeirarchyIsAppropriateForPurge(folder, userProfile))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not purging descendents of {0} for user {1}, folder is not part of a purgeable heirarchy",
folderID, remoteClient.Name);
return;
}
m_log.InfoFormat("[AGENT INVENTORY]: Purging descendents of {0} {1} for user {2}", folderID, folder.Name, remoteClient.Name);
if (!userProfile.PurgeFolderContents(folder))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to purge folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
});
}
/// <summary>
/// This should delete the given directory and all its descendents recursively.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
public void HandlePurgeInventoryFolder(IClientAPI remoteClient, UUID folderID)
{
Util.FireAndForget(Util.PoolSelection.LongIO, delegate(object obj)
{
CachedUserInfo userProfile = CommsManager.UserService.GetUserDetails(remoteClient.AgentId);
if (null == userProfile)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Could not find user profile for {0} {1}",
remoteClient.Name, remoteClient.AgentId);
return;
}
//make sure the user owns the source folder
InventoryFolderBase folder = userProfile.GetFolderAttributes(folderID);
if (folder.Owner != remoteClient.AgentId)
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not purging descendents of {0} for user {1}, user does not own the folder",
folderID, remoteClient.Name);
return;
}
//make sure the folder is either the lost and found, the trash, or a descendant of it
if (!CheckFolderHeirarchyIsAppropriateForPurge(folder, userProfile))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Not purging descendents of {0} for user {1}, folder is not part of a purgeable heirarchy",
folderID, remoteClient.Name);
return;
}
m_log.InfoFormat("[AGENT INVENTORY]: Purging {0} {1} for user {2}", folderID, folder.Name, remoteClient.Name);
if (!userProfile.PurgeFolder(folder))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to purge folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
});
}
private bool CheckFolderHeirarchyIsAppropriateForPurge(InventoryFolderBase folder, CachedUserInfo userProfile)
{
if (folder.Type == (short)FolderType.Trash||
folder.Type == (short)FolderType.LostAndFound)
{
return true;
}
if (folder.ParentID == UUID.Zero ||
folder.Type == (short)FolderType.Root)
{
//got to the top, didnt find squat
return false;
}
InventoryFolderBase parent = userProfile.GetFolderAttributes(folder.ParentID);
return CheckFolderHeirarchyIsAppropriateForPurge(parent, userProfile);
}
protected void GrabUpdate(UUID objectID, Vector3 startPos, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
SceneObjectGroup group = m_sceneGraph.GetGroupByPrim(objectID);
if (group != null)
{
SceneObjectPart part = group.GetChildPart(objectID);
if (part != null)
{
SurfaceTouchEventArgs surfaceArg = null;
Vector3 grabOffset = Vector3.Zero;
if (surfaceArgs != null && surfaceArgs.Count > 0)
{
surfaceArg = surfaceArgs[0];
if (surfaceArg.FaceIndex >= 0)
grabOffset = surfaceArg.Position - startPos;
else
grabOffset = pos - startPos;
}
// If the touched prim handles touches, deliver it
// If not, deliver to root prim,if the root prim doesnt
// handle it, deliver a grab to the scene graph
if ((part.ScriptEvents & ScriptEvents.touch) != 0)
{
EventManager.TriggerObjectGrabUpdate(part.LocalId, 0, grabOffset, remoteClient, surfaceArg);
}
else if ((group.RootPart.ScriptEvents & ScriptEvents.touch) != 0)
{
EventManager.TriggerObjectGrabUpdate(group.RootPart.LocalId, part.LocalId, grabOffset, remoteClient, surfaceArg);
}
else
{
//no one can handle it, send a grab
m_sceneGraph.MoveObject(objectID, startPos, pos, remoteClient, surfaceArgs);
}
}
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
using Amazon.Runtime;
using System.IO;
using System.Text;
using NUnit.Framework;
using CommonTests.Framework;
namespace CommonTests.IntegrationTests
{
[TestFixture]
public class KeyManagementService : TestBase<AmazonKeyManagementServiceClient>
{
private const string keyDescription = ".NET Test Key";
private const string copyText = " Copy";
private const int keySize = 1024;
private const int numberOfRandomBytes = 1023;
private const string testContents = "This is test data";
private static string keyAlias = "alias/net_key" + DateTime.Now.ToFileTime();
private static MemoryStream testData = new MemoryStream(Encoding.UTF8.GetBytes(testContents));
private static TimeSpan keyMaxWait = TimeSpan.FromSeconds(30);
private static TimeSpan keyDescribeWait = TimeSpan.FromSeconds(5);
private static List<string> allOperations = new List<string>
{
"Decrypt",
"Encrypt",
"GenerateDataKey",
"GenerateDataKeyWithoutPlaintext",
"ReEncryptFrom",
"ReEncryptTo",
"CreateGrant"
};
[OneTimeTearDown]
public void Cleanup()
{
BaseClean();
}
// This test is disabled because it creates resources that cannot be removed, KMS keys.
//[Test]
[Category("KMS")]
public void TestService()
{
var keys = GetKeys();
var keysCount = keys.Count;
var keyMetadata = Client.CreateKeyAsync(new CreateKeyRequest
{
KeyUsage = KeyUsageType.ENCRYPT_DECRYPT,
Description = keyDescription
}).Result.KeyMetadata;
ValidateKeyMetadata(keyMetadata, keyEnabled: true);
var keyId = keyMetadata.KeyId;
string reEncryptKeyId = null;
try
{
keys = GetKeys();
Assert.AreEqual(keysCount + 1, keys.Count);
keyMetadata = Client.DescribeKeyAsync(keyId).Result.KeyMetadata;
ValidateKeyMetadata(keyMetadata, keyEnabled: true);
TestAliases(keyId);
TestGrants(keyId);
TestEncryption(keyId, out reEncryptKeyId);
TestGeneration(keyId);
TestKeyChanges(keyId);
TestRotation(keyId);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
finally
{
if (keyId != null)
Client.DisableKeyAsync(keyId).Wait();
if (reEncryptKeyId != null)
Client.DisableKeyAsync(reEncryptKeyId).Wait();
}
}
private void TestGeneration(string keyId)
{
var gdkResult = Client.GenerateDataKeyAsync(new GenerateDataKeyRequest
{
KeyId = keyId,
NumberOfBytes = keySize,
}).Result;
Assert.IsNotNull(gdkResult.CiphertextBlob);
Assert.IsNotNull(gdkResult.Plaintext);
Assert.IsNotNull(gdkResult.KeyId);
Assert.IsTrue(gdkResult.KeyId.IndexOf(keyId, StringComparison.OrdinalIgnoreCase) >= 0);
Assert.AreEqual(keySize, gdkResult.Plaintext.Length);
var gdkwpResult = Client.GenerateDataKeyWithoutPlaintextAsync(new GenerateDataKeyWithoutPlaintextRequest
{
KeyId = keyId,
KeySpec = DataKeySpec.AES_256,
}).Result;
Assert.IsNotNull(gdkwpResult.CiphertextBlob);
Assert.IsNotNull(gdkwpResult.KeyId);
Assert.IsTrue(gdkwpResult.KeyId.IndexOf(keyId, StringComparison.OrdinalIgnoreCase) >= 0);
var random = Client.GenerateRandomAsync(numberOfRandomBytes).Result.Plaintext;
Assert.IsNotNull(random);
Assert.AreEqual(numberOfRandomBytes, random.Length);
}
private void TestEncryption(string keyId, out string reEncryptKeyId)
{
var encryptResponse = Client.EncryptAsync(new EncryptRequest
{
KeyId = keyId,
Plaintext = testData
}).Result;
Assert.IsTrue(encryptResponse.KeyId.IndexOf(keyId, StringComparison.OrdinalIgnoreCase) >= 0);
var cb = encryptResponse.CiphertextBlob;
Assert.IsNotNull(cb);
Assert.AreNotEqual(0, cb.Length);
var decryptResponse = Client.DecryptAsync(new DecryptRequest
{
CiphertextBlob = cb
}).Result;
Assert.IsTrue(decryptResponse.KeyId.IndexOf(keyId, StringComparison.OrdinalIgnoreCase) >= 0);
var plaintext = decryptResponse.Plaintext;
ValidateEncryptedData(cb, plaintext);
reEncryptKeyId = Client.CreateKeyAsync(new CreateKeyRequest
{
KeyUsage = KeyUsageType.ENCRYPT_DECRYPT,
Description = keyDescription + " For ReEncryption"
}).Result.KeyMetadata.KeyId;
var reEncryptResponse = Client.ReEncryptAsync(new ReEncryptRequest
{
CiphertextBlob = cb,
DestinationKeyId = reEncryptKeyId
}).Result;
Assert.IsTrue(reEncryptResponse.SourceKeyId.IndexOf(keyId, StringComparison.OrdinalIgnoreCase) >= 0);
Assert.IsTrue(reEncryptResponse.KeyId.IndexOf(reEncryptKeyId, StringComparison.OrdinalIgnoreCase) >= 0);
var reEncryptedCb = reEncryptResponse.CiphertextBlob;
decryptResponse = Client.DecryptAsync(new DecryptRequest
{
CiphertextBlob = reEncryptedCb
}).Result;
Assert.IsTrue(decryptResponse.KeyId.IndexOf(reEncryptKeyId, StringComparison.OrdinalIgnoreCase) >= 0);
plaintext = decryptResponse.Plaintext;
ValidateEncryptedData(cb, plaintext);
}
private void TestKeyChanges(string keyId)
{
Client.DisableKeyAsync(keyId).Wait();
ValidateKey(keyId, keyEnabled: false);
Client.EnableKeyAsync(keyId).Wait();
ValidateKey(keyId, keyEnabled: true);
var newKeyDescription = keyDescription + copyText;
Client.UpdateKeyDescriptionAsync(keyId, newKeyDescription).Wait();
ValidateKey(keyId, keyEnabled: true, isCopy: true);
var policyNames = Client.ListKeyPoliciesAsync(new ListKeyPoliciesRequest
{
KeyId = keyId
}).Result.PolicyNames;
Assert.AreEqual(1, policyNames.Count);
var policyName = policyNames.First();
var policy = Client.GetKeyPolicyAsync(keyId, policyName).Result.Policy;
Assert.IsTrue(policy.Length > 0);
Client.PutKeyPolicyAsync(keyId, policy, policyName).Wait();
policyNames = Client.ListKeyPoliciesAsync(new ListKeyPoliciesRequest
{
KeyId = keyId
}).Result.PolicyNames;
Assert.AreEqual(1, policyNames.Count);
}
private void TestGrants(string keyId)
{
var accountId = UtilityMethods.AccountId;
var grants = GetGrants(keyId);
var grantsCount = grants.Count;
var createdGrant = Client.CreateGrantAsync(new CreateGrantRequest
{
KeyId = keyId,
GranteePrincipal = accountId,
Operations = allOperations,
RetiringPrincipal = accountId
}).Result;
var grantId = createdGrant.GrantId;
var grantToken = createdGrant.GrantToken;
grants = GetGrants(keyId);
Assert.AreEqual(grantsCount + 1, grants.Count);
var grant = GetGrant(keyId, grantId);
Assert.IsNotNull(grant);
Client.RetireGrantAsync(grantToken).Wait();
grant = GetGrant(keyId, grantId);
Assert.IsNull(grant);
Client.RevokeGrantAsync(grantId, keyId).Wait();
grant = GetGrant(keyId, grantId);
Assert.IsNull(grant);
}
private void TestRotation(string keyId)
{
var rotationEnabled = Client.GetKeyRotationStatusAsync(keyId).Result.KeyRotationEnabled;
Assert.IsFalse(rotationEnabled);
Client.EnableKeyRotationAsync(keyId).Wait();
rotationEnabled = Client.GetKeyRotationStatusAsync(keyId).Result.KeyRotationEnabled;
Assert.IsTrue(rotationEnabled);
Client.DisableKeyRotationAsync(keyId).Wait();
rotationEnabled = Client.GetKeyRotationStatusAsync(keyId).Result.KeyRotationEnabled;
Assert.IsFalse(rotationEnabled);
}
private void TestAliases(string keyId)
{
var aliases = GetAliases();
var aliasesCount = aliases.Count;
Client.CreateAliasAsync(keyAlias, keyId).Wait();
aliases = GetAliases();
Assert.AreEqual(aliasesCount + 1, aliases.Count);
Client.DeleteAliasAsync(keyAlias).Wait();
aliases = GetAliases();
Assert.AreEqual(aliasesCount, aliases.Count);
}
public List<KeyListEntry> GetKeys()
{
var keys = new List<KeyListEntry>();
string nextMarker = null;
do
{
var response = Client.ListKeysAsync(new ListKeysRequest
{
Marker = nextMarker
}).Result;
nextMarker = response.NextMarker;
keys.AddRange(response.Keys);
} while (!string.IsNullOrEmpty(nextMarker));
return keys;
}
private List<AliasListEntry> GetAliases()
{
var aliases = new List<AliasListEntry>();
string nextMarker = null;
do
{
var response = Client.ListAliasesAsync(new ListAliasesRequest
{
Marker = nextMarker
}).Result;
nextMarker = response.NextMarker;
aliases.AddRange(response.Aliases);
} while (!string.IsNullOrEmpty(nextMarker));
return aliases;
}
private List<GrantListEntry> GetGrants(string keyId)
{
var grants = new List<GrantListEntry>();
string nextMarker = null;
do
{
var response = Client.ListGrantsAsync(new ListGrantsRequest
{
KeyId = keyId,
Marker = nextMarker
}).Result;
nextMarker = response.NextMarker;
grants.AddRange(response.Grants);
} while (!string.IsNullOrEmpty(nextMarker));
return grants;
}
private GrantListEntry GetGrant(string keyId, string grantId)
{
var grants = GetGrants(keyId);
foreach (var grant in grants)
if (string.Equals(grant.GrantId, grantId, StringComparison.OrdinalIgnoreCase))
return grant;
return null;
}
private void ValidateEncryptedData(MemoryStream cb, MemoryStream plaintext)
{
var sourceBytes = testData.ToArray();
var encryptedBytes = cb.ToArray();
var decryptedBytes = plaintext.ToArray();
CollectionAssert.AreEqual(sourceBytes, decryptedBytes);
CollectionAssert.AreNotEqual(sourceBytes, encryptedBytes);
var text = Encoding.UTF8.GetString(decryptedBytes);
Assert.AreEqual(testContents, text);
}
private void ValidateKey(string keyId, bool keyEnabled, bool isCopy = false)
{
var stopTime = DateTime.Now + keyMaxWait;
KeyMetadata keyMetadata = null;
while(DateTime.Now < stopTime)
{
try
{
keyMetadata = Client.DescribeKeyAsync(keyId).Result.KeyMetadata;
ValidateKeyMetadata(keyMetadata, keyEnabled);
break;
}
catch(AssertionException)
{
UtilityMethods.Sleep(keyDescribeWait);
}
}
ValidateKeyMetadata(keyMetadata, keyEnabled);
}
private static void ValidateKeyMetadata(KeyMetadata keyMetadata, bool keyEnabled, bool isCopy = false)
{
Assert.IsNotNull(keyMetadata);
Assert.IsNotNull(keyMetadata.Arn);
Assert.IsNotNull(keyMetadata.AWSAccountId);
Assert.IsNotNull(keyMetadata.Description);
Assert.IsTrue(keyMetadata.Description.IndexOf(keyDescription, StringComparison.Ordinal) >= 0);
if (isCopy)
Assert.IsTrue(keyMetadata.Description.IndexOf(copyText, StringComparison.Ordinal) >= 0);
Assert.IsNotNull(keyMetadata.KeyId);
Assert.AreEqual(keyMetadata.KeyUsage, KeyUsageType.ENCRYPT_DECRYPT);
Assert.AreEqual(keyEnabled, keyMetadata.Enabled);
Assert.AreNotEqual(DateTime.MinValue, keyMetadata.CreationDate);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// API details.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class ApiContract : Resource
{
/// <summary>
/// Initializes a new instance of the ApiContract class.
/// </summary>
public ApiContract()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ApiContract class.
/// </summary>
/// <param name="path">Relative URL uniquely identifying this API and
/// all of its resource paths within the API Management service
/// instance. It is appended to the API endpoint base URL specified
/// during the service instance creation to form a public URL for this
/// API.</param>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type for API Management
/// resource.</param>
/// <param name="description">Description of the API. May include HTML
/// formatting tags.</param>
/// <param name="authenticationSettings">Collection of authentication
/// settings included into this API.</param>
/// <param name="subscriptionKeyParameterNames">Protocols over which
/// API is made available.</param>
/// <param name="apiType">Type of API. Possible values include: 'http',
/// 'soap'</param>
/// <param name="apiRevision">Describes the Revision of the Api. If no
/// value is provided, default revision 1 is created</param>
/// <param name="isCurrent">Indicates if API revision is current api
/// revision.</param>
/// <param name="isOnline">Indicates if API revision is accessible via
/// the gateway.</param>
/// <param name="displayName">API name.</param>
/// <param name="serviceUrl">Absolute URL of the backend service
/// implementing this API.</param>
/// <param name="protocols">Describes on which protocols the operations
/// in this API can be invoked.</param>
public ApiContract(string path, string id = default(string), string name = default(string), string type = default(string), string description = default(string), AuthenticationSettingsContract authenticationSettings = default(AuthenticationSettingsContract), SubscriptionKeyParameterNamesContract subscriptionKeyParameterNames = default(SubscriptionKeyParameterNamesContract), string apiType = default(string), string apiRevision = default(string), bool? isCurrent = default(bool?), bool? isOnline = default(bool?), string displayName = default(string), string serviceUrl = default(string), IList<Protocol?> protocols = default(IList<Protocol?>))
: base(id, name, type)
{
Description = description;
AuthenticationSettings = authenticationSettings;
SubscriptionKeyParameterNames = subscriptionKeyParameterNames;
ApiType = apiType;
ApiRevision = apiRevision;
IsCurrent = isCurrent;
IsOnline = isOnline;
DisplayName = displayName;
ServiceUrl = serviceUrl;
Path = path;
Protocols = protocols;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets description of the API. May include HTML formatting
/// tags.
/// </summary>
[JsonProperty(PropertyName = "properties.description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets collection of authentication settings included into
/// this API.
/// </summary>
[JsonProperty(PropertyName = "properties.authenticationSettings")]
public AuthenticationSettingsContract AuthenticationSettings { get; set; }
/// <summary>
/// Gets or sets protocols over which API is made available.
/// </summary>
[JsonProperty(PropertyName = "properties.subscriptionKeyParameterNames")]
public SubscriptionKeyParameterNamesContract SubscriptionKeyParameterNames { get; set; }
/// <summary>
/// Gets or sets type of API. Possible values include: 'http', 'soap'
/// </summary>
[JsonProperty(PropertyName = "properties.type")]
public string ApiType { get; set; }
/// <summary>
/// Gets or sets describes the Revision of the Api. If no value is
/// provided, default revision 1 is created
/// </summary>
[JsonProperty(PropertyName = "properties.apiRevision")]
public string ApiRevision { get; set; }
/// <summary>
/// Gets or sets indicates if API revision is current api revision.
/// </summary>
[JsonProperty(PropertyName = "properties.isCurrent")]
public bool? IsCurrent { get; set; }
/// <summary>
/// Gets or sets indicates if API revision is accessible via the
/// gateway.
/// </summary>
[JsonProperty(PropertyName = "properties.isOnline")]
public bool? IsOnline { get; set; }
/// <summary>
/// Gets or sets API name.
/// </summary>
[JsonProperty(PropertyName = "properties.displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets absolute URL of the backend service implementing this
/// API.
/// </summary>
[JsonProperty(PropertyName = "properties.serviceUrl")]
public string ServiceUrl { get; set; }
/// <summary>
/// Gets or sets relative URL uniquely identifying this API and all of
/// its resource paths within the API Management service instance. It
/// is appended to the API endpoint base URL specified during the
/// service instance creation to form a public URL for this API.
/// </summary>
[JsonProperty(PropertyName = "properties.path")]
public string Path { get; set; }
/// <summary>
/// Gets or sets describes on which protocols the operations in this
/// API can be invoked.
/// </summary>
[JsonProperty(PropertyName = "properties.protocols")]
public IList<Protocol?> Protocols { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Path == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Path");
}
if (ApiRevision != null)
{
if (ApiRevision.Length > 100)
{
throw new ValidationException(ValidationRules.MaxLength, "ApiRevision", 100);
}
if (ApiRevision.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "ApiRevision", 1);
}
}
if (DisplayName != null)
{
if (DisplayName.Length > 300)
{
throw new ValidationException(ValidationRules.MaxLength, "DisplayName", 300);
}
if (DisplayName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "DisplayName", 1);
}
}
if (ServiceUrl != null)
{
if (ServiceUrl.Length > 2000)
{
throw new ValidationException(ValidationRules.MaxLength, "ServiceUrl", 2000);
}
if (ServiceUrl.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "ServiceUrl", 1);
}
}
if (Path != null)
{
if (Path.Length > 400)
{
throw new ValidationException(ValidationRules.MaxLength, "Path", 400);
}
if (Path.Length < 0)
{
throw new ValidationException(ValidationRules.MinLength, "Path", 0);
}
}
}
}
}
| |
// 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.Globalization;
using System.Threading;
using System.Threading.Tasks;
// TODO: Move these tests to CoreFX once they can be run on CoreRT
internal static class Runner
{
private const int Pass = 100;
public static int Main()
{
Console.WriteLine(" WaitSubsystemTests.DoubleSetOnEventWithTimedOutWaiterShouldNotStayInWaitersList");
WaitSubsystemTests.DoubleSetOnEventWithTimedOutWaiterShouldNotStayInWaitersList();
Console.WriteLine(" WaitSubsystemTests.ManualResetEventTest");
WaitSubsystemTests.ManualResetEventTest();
Console.WriteLine(" WaitSubsystemTests.AutoResetEventTest");
WaitSubsystemTests.AutoResetEventTest();
Console.WriteLine(" WaitSubsystemTests.SemaphoreTest");
WaitSubsystemTests.SemaphoreTest();
Console.WriteLine(" WaitSubsystemTests.MutexTest");
WaitSubsystemTests.MutexTest();
Console.WriteLine(" WaitSubsystemTests.WaitDurationTest");
WaitSubsystemTests.WaitDurationTest();
// This test takes a long time to run in release and especially in debug builds. Enable for manual testing.
//Console.WriteLine(" WaitSubsystemTests.MutexMaximumReacquireCountTest");
//WaitSubsystemTests.MutexMaximumReacquireCountTest();
Console.WriteLine(" ThreadPoolTests.RunProcessorCountItemsInParallel");
ThreadPoolTests.RunProcessorCountItemsInParallel();
Console.WriteLine(" ThreadPoolTests.RunMoreThanMaxJobsMakesOneJobWaitForStarvationDetection");
ThreadPoolTests.RunMoreThanMaxJobsMakesOneJobWaitForStarvationDetection();
Console.WriteLine(" ThreadPoolTests.ThreadPoolCanPickUpOneJobWhenThreadIsAvailable");
ThreadPoolTests.ThreadPoolCanPickUpOneJobWhenThreadIsAvailable();
Console.WriteLine(" ThreadPoolTests.ThreadPoolCanPickUpMultipleJobsWhenThreadsAreAvailable");
ThreadPoolTests.ThreadPoolCanPickUpMultipleJobsWhenThreadsAreAvailable();
// This test takes a long time to run (min 42 seconds sleeping). Enable for manual testing.
// Console.WriteLine(" ThreadPoolTests.RunJobsAfterThreadTimeout");
// ThreadPoolTests.RunJobsAfterThreadTimeout();
Console.WriteLine(" ThreadPoolTests.WorkQueueDepletionTest");
ThreadPoolTests.WorkQueueDepletionTest();
Console.WriteLine(" ThreadPoolTests.WorkerThreadStateReset");
ThreadPoolTests.WorkerThreadStateReset();
// This test is not applicable (and will not pass) on Windows since it uses the Windows OS-provided thread pool.
// Console.WriteLine(" ThreadPoolTests.SettingMinThreadsWillCreateThreadsUpToMinimum");
// ThreadPoolTests.SettingMinThreadsWillCreateThreadsUpToMinimum();
Console.WriteLine(" WaitThreadTests.SignalingRegisteredHandleCallsCalback");
WaitThreadTests.SignalingRegisteredHandleCallsCalback();
Console.WriteLine(" WaitThreadTests.TimingOutRegisteredHandleCallsCallback");
WaitThreadTests.TimingOutRegisteredHandleCallsCallback();
Console.WriteLine(" WaitThreadTests.UnregisteringBeforeSignalingDoesNotCallCallback");
WaitThreadTests.UnregisteringBeforeSignalingDoesNotCallCallback();
Console.WriteLine(" WaitThreadTests.RepeatingWaitFiresUntilUnregistered");
WaitThreadTests.RepeatingWaitFiresUntilUnregistered();
Console.WriteLine(" WaitThreadTests.UnregisterEventSignaledWhenUnregistered");
WaitThreadTests.UnregisterEventSignaledWhenUnregistered();
Console.WriteLine(" WaitThreadTests.CanRegisterMoreThan64Waits");
WaitThreadTests.CanRegisterMoreThan64Waits();
Console.WriteLine(" WaitThreadTests.StateIsPasssedThroughToCallback");
WaitThreadTests.StateIsPasssedThroughToCallback();
// This test takes a long time to run. Enable for manual testing.
// Console.WriteLine(" WaitThreadTests.WaitWithLongerTimeoutThanWaitThreadCanStillTimeout");
// WaitThreadTests.WaitWithLongerTimeoutThanWaitThreadCanStillTimeout();
Console.WriteLine(" WaitThreadTests.UnregisterCallbackIsNotCalledAfterCallbackFinishesIfAnotherCallbackOnSameWaitRunning");
WaitThreadTests.UnregisterCallbackIsNotCalledAfterCallbackFinishesIfAnotherCallbackOnSameWaitRunning();
Console.WriteLine(" WaitThreadTests.CallingUnregisterOnAutomaticallyUnregisteredHandleReturnsTrue");
WaitThreadTests.CallingUnregisterOnAutomaticallyUnregisteredHandleReturnsTrue();
Console.WriteLine(" WaitThreadTests.EventSetAfterUnregisterNotObservedOnWaitThread");
WaitThreadTests.EventSetAfterUnregisterNotObservedOnWaitThread();
Console.WriteLine(" WaitThreadTests.BlockingUnregister");
WaitThreadTests.BlockingUnregister();
Console.WriteLine(" WaitThreadTests.CanDisposeEventAfterUnblockingUnregister");
WaitThreadTests.CanDisposeEventAfterUnblockingUnregister();
Console.WriteLine(" WaitThreadTests.UnregisterEventSignaledWhenUnregisteredEvenIfAutoUnregistered");
WaitThreadTests.UnregisterEventSignaledWhenUnregisteredEvenIfAutoUnregistered();
Console.WriteLine(" WaitThreadTests.BlockingUnregisterBlocksEvenIfCallbackExecuting");
WaitThreadTests.BlockingUnregisterBlocksEvenIfCallbackExecuting();
return Pass;
}
}
internal static class WaitSubsystemTests
{
private const int AcceptableEarlyWaitTerminationDiffMilliseconds = -100;
private const int AcceptableLateWaitTerminationDiffMilliseconds = 300;
[Fact]
public static void ManualResetEventTest()
{
// Constructor and dispose
var e = new ManualResetEvent(false);
Assert.False(e.WaitOne(0));
e.Dispose();
Assert.Throws<ObjectDisposedException>(() => e.Reset());
Assert.Throws<ObjectDisposedException>(() => e.Set());
Assert.Throws<ObjectDisposedException>(() => e.WaitOne(0));
e = new ManualResetEvent(true);
Assert.True(e.WaitOne(0));
// Set and reset
e = new ManualResetEvent(true);
e.Reset();
Assert.False(e.WaitOne(0));
Assert.False(e.WaitOne(0));
e.Reset();
Assert.False(e.WaitOne(0));
e.Set();
Assert.True(e.WaitOne(0));
Assert.True(e.WaitOne(0));
e.Set();
Assert.True(e.WaitOne(0));
// Wait
e.Set();
Assert.True(e.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.True(e.WaitOne());
e.Reset();
Assert.False(e.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
e = null;
// Multi-wait with all indexes set
var es =
new ManualResetEvent[]
{
new ManualResetEvent(true),
new ManualResetEvent(true),
new ManualResetEvent(true),
new ManualResetEvent(true)
};
Assert.Equal(0, WaitHandle.WaitAny(es, 0));
Assert.Equal(0, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.Equal(0, WaitHandle.WaitAny(es));
Assert.True(WaitHandle.WaitAll(es, 0));
Assert.True(WaitHandle.WaitAll(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.True(WaitHandle.WaitAll(es));
for (int i = 0; i < es.Length; ++i)
{
Assert.True(es[i].WaitOne(0));
}
// Multi-wait with indexes 1 and 2 set
es[0].Reset();
es[3].Reset();
Assert.Equal(1, WaitHandle.WaitAny(es, 0));
Assert.Equal(1, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.False(WaitHandle.WaitAll(es, 0));
Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i == 1 || i == 2, es[i].WaitOne(0));
}
// Multi-wait with all indexes reset
es[1].Reset();
es[2].Reset();
Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, 0));
Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
Assert.False(WaitHandle.WaitAll(es, 0));
Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.False(es[i].WaitOne(0));
}
}
[Fact]
public static void AutoResetEventTest()
{
// Constructor and dispose
var e = new AutoResetEvent(false);
Assert.False(e.WaitOne(0));
e.Dispose();
Assert.Throws<ObjectDisposedException>(() => e.Reset());
Assert.Throws<ObjectDisposedException>(() => e.Set());
Assert.Throws<ObjectDisposedException>(() => e.WaitOne(0));
e = new AutoResetEvent(true);
Assert.True(e.WaitOne(0));
// Set and reset
e = new AutoResetEvent(true);
e.Reset();
Assert.False(e.WaitOne(0));
Assert.False(e.WaitOne(0));
e.Reset();
Assert.False(e.WaitOne(0));
e.Set();
Assert.True(e.WaitOne(0));
Assert.False(e.WaitOne(0));
e.Set();
e.Set();
Assert.True(e.WaitOne(0));
// Wait
e.Set();
Assert.True(e.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.False(e.WaitOne(0));
e.Set();
Assert.True(e.WaitOne());
Assert.False(e.WaitOne(0));
e.Reset();
Assert.False(e.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
e = null;
// Multi-wait with all indexes set
var es =
new AutoResetEvent[]
{
new AutoResetEvent(true),
new AutoResetEvent(true),
new AutoResetEvent(true),
new AutoResetEvent(true)
};
Assert.Equal(0, WaitHandle.WaitAny(es, 0));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i > 0, es[i].WaitOne(0));
es[i].Set();
}
Assert.Equal(0, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i > 0, es[i].WaitOne(0));
es[i].Set();
}
Assert.Equal(0, WaitHandle.WaitAny(es));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i > 0, es[i].WaitOne(0));
es[i].Set();
}
Assert.True(WaitHandle.WaitAll(es, 0));
for (int i = 0; i < es.Length; ++i)
{
Assert.False(es[i].WaitOne(0));
es[i].Set();
}
Assert.True(WaitHandle.WaitAll(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.False(es[i].WaitOne(0));
es[i].Set();
}
Assert.True(WaitHandle.WaitAll(es));
for (int i = 0; i < es.Length; ++i)
{
Assert.False(es[i].WaitOne(0));
}
// Multi-wait with indexes 1 and 2 set
es[1].Set();
es[2].Set();
Assert.Equal(1, WaitHandle.WaitAny(es, 0));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i == 2, es[i].WaitOne(0));
}
es[1].Set();
es[2].Set();
Assert.Equal(1, WaitHandle.WaitAny(es, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i == 2, es[i].WaitOne(0));
}
es[1].Set();
es[2].Set();
Assert.False(WaitHandle.WaitAll(es, 0));
Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.Equal(i == 1 || i == 2, es[i].WaitOne(0));
}
// Multi-wait with all indexes reset
Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, 0));
Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
Assert.False(WaitHandle.WaitAll(es, 0));
Assert.False(WaitHandle.WaitAll(es, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
for (int i = 0; i < es.Length; ++i)
{
Assert.False(es[i].WaitOne(0));
}
}
[Fact]
public static void SemaphoreTest()
{
// Constructor and dispose
Assert.Throws<ArgumentOutOfRangeException>(() => new Semaphore(-1, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Semaphore(0, 0));
Assert.Throws<ArgumentException>(() => new Semaphore(2, 1));
var s = new Semaphore(0, 1);
Assert.False(s.WaitOne(0));
s.Dispose();
Assert.Throws<ObjectDisposedException>(() => s.Release());
Assert.Throws<ObjectDisposedException>(() => s.WaitOne(0));
s = new Semaphore(1, 1);
Assert.True(s.WaitOne(0));
// Signal and unsignal
Assert.Throws<ArgumentOutOfRangeException>(() => s.Release(0));
s = new Semaphore(1, 1);
Assert.True(s.WaitOne(0));
Assert.False(s.WaitOne(0));
Assert.False(s.WaitOne(0));
Assert.Equal(0, s.Release());
Assert.True(s.WaitOne(0));
Assert.Throws<SemaphoreFullException>(() => s.Release(2));
Assert.Equal(0, s.Release());
Assert.Throws<SemaphoreFullException>(() => s.Release());
s = new Semaphore(1, 2);
Assert.Throws<SemaphoreFullException>(() => s.Release(2));
Assert.Equal(1, s.Release(1));
Assert.True(s.WaitOne(0));
Assert.True(s.WaitOne(0));
Assert.Throws<SemaphoreFullException>(() => s.Release(3));
Assert.Equal(0, s.Release(2));
Assert.Throws<SemaphoreFullException>(() => s.Release());
// Wait
s = new Semaphore(1, 2);
Assert.True(s.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.False(s.WaitOne(0));
s.Release();
Assert.True(s.WaitOne());
Assert.False(s.WaitOne(0));
s.Release(2);
Assert.True(s.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
s.Release();
Assert.True(s.WaitOne());
s = new Semaphore(0, 2);
Assert.False(s.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
s = null;
// Multi-wait with all indexes signaled
var ss =
new Semaphore[]
{
new Semaphore(1, 1),
new Semaphore(1, 1),
new Semaphore(1, 1),
new Semaphore(1, 1)
};
Assert.Equal(0, WaitHandle.WaitAny(ss, 0));
for (int i = 0; i < ss.Length; ++i)
{
Assert.Equal(i > 0, ss[i].WaitOne(0));
ss[i].Release();
}
Assert.Equal(0, WaitHandle.WaitAny(ss, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < ss.Length; ++i)
{
Assert.Equal(i > 0, ss[i].WaitOne(0));
ss[i].Release();
}
Assert.Equal(0, WaitHandle.WaitAny(ss));
for (int i = 0; i < ss.Length; ++i)
{
Assert.Equal(i > 0, ss[i].WaitOne(0));
ss[i].Release();
}
Assert.True(WaitHandle.WaitAll(ss, 0));
for (int i = 0; i < ss.Length; ++i)
{
Assert.False(ss[i].WaitOne(0));
ss[i].Release();
}
Assert.True(WaitHandle.WaitAll(ss, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < ss.Length; ++i)
{
Assert.False(ss[i].WaitOne(0));
ss[i].Release();
}
Assert.True(WaitHandle.WaitAll(ss));
for (int i = 0; i < ss.Length; ++i)
{
Assert.False(ss[i].WaitOne(0));
}
// Multi-wait with indexes 1 and 2 signaled
ss[1].Release();
ss[2].Release();
Assert.Equal(1, WaitHandle.WaitAny(ss, 0));
for (int i = 0; i < ss.Length; ++i)
{
Assert.Equal(i == 2, ss[i].WaitOne(0));
}
ss[1].Release();
ss[2].Release();
Assert.Equal(1, WaitHandle.WaitAny(ss, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < ss.Length; ++i)
{
Assert.Equal(i == 2, ss[i].WaitOne(0));
}
ss[1].Release();
ss[2].Release();
Assert.False(WaitHandle.WaitAll(ss, 0));
Assert.False(WaitHandle.WaitAll(ss, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
for (int i = 0; i < ss.Length; ++i)
{
Assert.Equal(i == 1 || i == 2, ss[i].WaitOne(0));
}
// Multi-wait with all indexes unsignaled
Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(ss, 0));
Assert.Equal(WaitHandle.WaitTimeout, WaitHandle.WaitAny(ss, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
Assert.False(WaitHandle.WaitAll(ss, 0));
Assert.False(WaitHandle.WaitAll(ss, ThreadTestHelpers.ExpectedTimeoutMilliseconds));
for (int i = 0; i < ss.Length; ++i)
{
Assert.False(ss[i].WaitOne(0));
}
}
// There is a race condition between a timed out WaitOne and a Set call not clearing the waiters list
// in the wait subsystem (Unix only). More information can be found at
// https://github.com/dotnet/corert/issues/3616 and https://github.com/dotnet/corert/pull/3782.
[Fact]
public static void DoubleSetOnEventWithTimedOutWaiterShouldNotStayInWaitersList()
{
AutoResetEvent threadStartedEvent = new AutoResetEvent(false);
AutoResetEvent resetEvent = new AutoResetEvent(false);
Thread thread = new Thread(() => {
threadStartedEvent.Set();
Thread.Sleep(50);
resetEvent.Set();
resetEvent.Set();
});
thread.IsBackground = true;
thread.Start();
threadStartedEvent.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
resetEvent.WaitOne(50);
thread.Join(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
}
[Fact]
public static void MutexTest()
{
// Constructor and dispose
var m = new Mutex();
Assert.True(m.WaitOne(0));
m.ReleaseMutex();
m.Dispose();
Assert.Throws<ObjectDisposedException>(() => m.ReleaseMutex());
Assert.Throws<ObjectDisposedException>(() => m.WaitOne(0));
m = new Mutex(false);
Assert.True(m.WaitOne(0));
m.ReleaseMutex();
m = new Mutex(true);
Assert.True(m.WaitOne(0));
m.ReleaseMutex();
m.ReleaseMutex();
m = new Mutex(true);
Assert.True(m.WaitOne(0));
m.Dispose();
Assert.Throws<ObjectDisposedException>(() => m.ReleaseMutex());
Assert.Throws<ObjectDisposedException>(() => m.WaitOne(0));
// Acquire and release
m = new Mutex();
VerifyThrowsApplicationException(() => m.ReleaseMutex());
Assert.True(m.WaitOne(0));
m.ReleaseMutex();
VerifyThrowsApplicationException(() => m.ReleaseMutex());
Assert.True(m.WaitOne(0));
Assert.True(m.WaitOne(0));
Assert.True(m.WaitOne(0));
m.ReleaseMutex();
m.ReleaseMutex();
m.ReleaseMutex();
VerifyThrowsApplicationException(() => m.ReleaseMutex());
// Wait
Assert.True(m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.True(m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
m.ReleaseMutex();
m.ReleaseMutex();
Assert.True(m.WaitOne());
Assert.True(m.WaitOne());
m.ReleaseMutex();
m.ReleaseMutex();
m = null;
// Multi-wait with all indexes unlocked
var ms =
new Mutex[]
{
new Mutex(),
new Mutex(),
new Mutex(),
new Mutex()
};
Assert.Equal(0, WaitHandle.WaitAny(ms, 0));
ms[0].ReleaseMutex();
for (int i = 1; i < ms.Length; ++i)
{
VerifyThrowsApplicationException(() => ms[i].ReleaseMutex());
}
Assert.Equal(0, WaitHandle.WaitAny(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
ms[0].ReleaseMutex();
for (int i = 1; i < ms.Length; ++i)
{
VerifyThrowsApplicationException(() => ms[i].ReleaseMutex());
}
Assert.Equal(0, WaitHandle.WaitAny(ms));
ms[0].ReleaseMutex();
for (int i = 1; i < ms.Length; ++i)
{
VerifyThrowsApplicationException(() => ms[i].ReleaseMutex());
}
Assert.True(WaitHandle.WaitAll(ms, 0));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
Assert.True(WaitHandle.WaitAll(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
Assert.True(WaitHandle.WaitAll(ms));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
// Multi-wait with indexes 0 and 3 locked
ms[0].WaitOne(0);
ms[3].WaitOne(0);
Assert.Equal(0, WaitHandle.WaitAny(ms, 0));
ms[0].ReleaseMutex();
VerifyThrowsApplicationException(() => ms[1].ReleaseMutex());
VerifyThrowsApplicationException(() => ms[2].ReleaseMutex());
Assert.Equal(0, WaitHandle.WaitAny(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
ms[0].ReleaseMutex();
VerifyThrowsApplicationException(() => ms[1].ReleaseMutex());
VerifyThrowsApplicationException(() => ms[2].ReleaseMutex());
Assert.Equal(0, WaitHandle.WaitAny(ms));
ms[0].ReleaseMutex();
VerifyThrowsApplicationException(() => ms[1].ReleaseMutex());
VerifyThrowsApplicationException(() => ms[2].ReleaseMutex());
Assert.True(WaitHandle.WaitAll(ms, 0));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
Assert.True(WaitHandle.WaitAll(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
Assert.True(WaitHandle.WaitAll(ms));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
ms[0].ReleaseMutex();
VerifyThrowsApplicationException(() => ms[1].ReleaseMutex());
VerifyThrowsApplicationException(() => ms[2].ReleaseMutex());
ms[3].ReleaseMutex();
// Multi-wait with all indexes locked
for (int i = 0; i < ms.Length; ++i)
{
Assert.True(ms[i].WaitOne(0));
}
Assert.Equal(0, WaitHandle.WaitAny(ms, 0));
ms[0].ReleaseMutex();
Assert.Equal(0, WaitHandle.WaitAny(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
ms[0].ReleaseMutex();
Assert.Equal(0, WaitHandle.WaitAny(ms));
ms[0].ReleaseMutex();
Assert.True(WaitHandle.WaitAll(ms, 0));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
Assert.True(WaitHandle.WaitAll(ms, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
Assert.True(WaitHandle.WaitAll(ms));
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
}
for (int i = 0; i < ms.Length; ++i)
{
ms[i].ReleaseMutex();
VerifyThrowsApplicationException(() => ms[i].ReleaseMutex());
}
}
private static void VerifyThrowsApplicationException(Action action)
{
// TODO: netstandard2.0 - After switching to ns2.0 contracts, use Assert.Throws<T> instead of this function
// TODO: Enable this verification. There currently seem to be some reliability issues surrounding exceptions on Unix.
//try
//{
// action();
//}
//catch (Exception ex)
//{
// if (ex.HResult == unchecked((int)0x80131600))
// return;
// Console.WriteLine(
// "VerifyThrowsApplicationException: Assertion failure - Assert.Throws<ApplicationException>: got {1}",
// ex.GetType());
// throw new AssertionFailureException(ex);
//}
//Console.WriteLine(
// "VerifyThrowsApplicationException: Assertion failure - Assert.Throws<ApplicationException>: got no exception");
//throw new AssertionFailureException();
}
[Fact]
[OuterLoop]
public static void WaitDurationTest()
{
VerifyWaitDuration(
new ManualResetEvent(false),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds);
VerifyWaitDuration(
new ManualResetEvent(true),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: 0);
VerifyWaitDuration(
new AutoResetEvent(false),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds);
VerifyWaitDuration(
new AutoResetEvent(true),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: 0);
VerifyWaitDuration(
new Semaphore(0, 1),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds);
VerifyWaitDuration(
new Semaphore(1, 1),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: 0);
VerifyWaitDuration(
new Mutex(true),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: 0);
VerifyWaitDuration(
new Mutex(false),
waitTimeoutMilliseconds: ThreadTestHelpers.ExpectedMeasurableTimeoutMilliseconds,
expectedWaitTerminationAfterMilliseconds: 0);
}
private static void VerifyWaitDuration(
WaitHandle wh,
int waitTimeoutMilliseconds,
int expectedWaitTerminationAfterMilliseconds)
{
Assert.True(waitTimeoutMilliseconds > 0);
Assert.True(expectedWaitTerminationAfterMilliseconds >= 0);
var sw = new Stopwatch();
sw.Restart();
Assert.Equal(expectedWaitTerminationAfterMilliseconds == 0, wh.WaitOne(waitTimeoutMilliseconds));
sw.Stop();
int waitDurationDiffMilliseconds = (int)sw.ElapsedMilliseconds - expectedWaitTerminationAfterMilliseconds;
Assert.True(waitDurationDiffMilliseconds >= AcceptableEarlyWaitTerminationDiffMilliseconds);
Assert.True(waitDurationDiffMilliseconds <= AcceptableLateWaitTerminationDiffMilliseconds);
}
//[Fact] // This test takes a long time to run in release and especially in debug builds. Enable for manual testing.
public static void MutexMaximumReacquireCountTest()
{
// Create a mutex with the maximum reacquire count
var m = new Mutex();
int tenPercent = int.MaxValue / 10;
int progressPercent = 0;
Console.Write(" 0%");
for (int i = 0; i >= 0; ++i)
{
if (i >= (progressPercent + 1) * tenPercent)
{
++progressPercent;
if (progressPercent < 10)
{
Console.Write(" {0}%", progressPercent * 10);
}
}
Assert.True(m.WaitOne(0));
}
Assert.Throws<OverflowException>(
() =>
{
// Windows allows a slightly higher maximum reacquire count than this implementation
Assert.True(m.WaitOne(0));
Assert.True(m.WaitOne(0));
});
Console.WriteLine(" 100%");
// Single wait fails
Assert.Throws<OverflowException>(() => m.WaitOne(0));
Assert.Throws<OverflowException>(() => m.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Assert.Throws<OverflowException>(() => m.WaitOne());
var e0 = new AutoResetEvent(false);
var s0 = new Semaphore(0, 1);
var e1 = new AutoResetEvent(false);
var s1 = new Semaphore(0, 1);
var h = new WaitHandle[] { e0, s0, m, e1, s1 };
Action<bool, bool, bool, bool> init =
(signale0, signals0, signale1, signals1) =>
{
if (signale0)
e0.Set();
else
e0.Reset();
s0.WaitOne(0);
if (signals0)
s0.Release();
if (signale1)
e1.Set();
else
e1.Reset();
s1.WaitOne(0);
if (signals1)
s1.Release();
};
Action<bool, bool, bool, bool> verify =
(e0signaled, s0signaled, e1signaled, s1signaled) =>
{
Assert.Equal(e0signaled, e0.WaitOne(0));
Assert.Equal(s0signaled, s0.WaitOne(0));
Assert.Throws<OverflowException>(() => m.WaitOne(0));
Assert.Equal(e1signaled, e1.WaitOne(0));
Assert.Equal(s1signaled, s1.WaitOne(0));
init(e0signaled, s0signaled, e1signaled, s1signaled);
};
// WaitAny succeeds when a signaled object is before the mutex
init(true, true, true, true);
Assert.Equal(0, WaitHandle.WaitAny(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
verify(false, true, true, true);
Assert.Equal(1, WaitHandle.WaitAny(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
verify(false, false, true, true);
// WaitAny fails when all objects before the mutex are unsignaled
init(false, false, true, true);
Assert.Throws<OverflowException>(() => WaitHandle.WaitAny(h, 0));
verify(false, false, true, true);
Assert.Throws<OverflowException>(() => WaitHandle.WaitAny(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
verify(false, false, true, true);
Assert.Throws<OverflowException>(() => WaitHandle.WaitAny(h));
verify(false, false, true, true);
// WaitAll fails and does not unsignal any signaled object
init(true, true, true, true);
Assert.Throws<OverflowException>(() => WaitHandle.WaitAll(h, 0));
verify(true, true, true, true);
Assert.Throws<OverflowException>(() => WaitHandle.WaitAll(h, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
verify(true, true, true, true);
Assert.Throws<OverflowException>(() => WaitHandle.WaitAll(h));
verify(true, true, true, true);
m.Dispose();
}
}
internal static class ThreadPoolTests
{
[Fact]
public static void RunProcessorCountItemsInParallel()
{
int count = 0;
AutoResetEvent e0 = new AutoResetEvent(false);
for(int i = 0; i < Environment.ProcessorCount; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == Environment.ProcessorCount)
{
e0.Set();
}
});
}
e0.CheckedWait();
// Run the test again to make sure we can reuse the threads.
count = 0;
for(int i = 0; i < Environment.ProcessorCount; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == Environment.ProcessorCount)
{
e0.Set();
}
});
}
e0.CheckedWait();
}
[Fact]
public static void RunMoreThanMaxJobsMakesOneJobWaitForStarvationDetection()
{
ManualResetEvent e0 = new ManualResetEvent(false);
AutoResetEvent jobsQueued = new AutoResetEvent(false);
int count = 0;
AutoResetEvent e1 = new AutoResetEvent(false);
for(int i = 0; i < Environment.ProcessorCount; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == Environment.ProcessorCount)
{
jobsQueued.Set();
}
e0.CheckedWait();
});
}
jobsQueued.CheckedWait();
ThreadPool.QueueUserWorkItem( _ => e1.Set());
Thread.Sleep(500); // Sleep for the gate thread delay to wait for starvation
e1.CheckedWait();
e0.Set();
}
[Fact]
public static void ThreadPoolCanPickUpOneJobWhenThreadIsAvailable()
{
ManualResetEvent e0 = new ManualResetEvent(false);
AutoResetEvent jobsQueued = new AutoResetEvent(false);
AutoResetEvent testJobCompleted = new AutoResetEvent(false);
int count = 0;
for(int i = 0; i < Environment.ProcessorCount - 1; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == Environment.ProcessorCount - 1)
{
jobsQueued.Set();
}
e0.CheckedWait();
});
}
jobsQueued.CheckedWait();
ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set());
testJobCompleted.CheckedWait();
e0.Set();
}
[Fact]
public static void ThreadPoolCanPickUpMultipleJobsWhenThreadsAreAvailable()
{
ManualResetEvent e0 = new ManualResetEvent(false);
AutoResetEvent jobsQueued = new AutoResetEvent(false);
AutoResetEvent testJobCompleted = new AutoResetEvent(false);
int count = 0;
for(int i = 0; i < Environment.ProcessorCount - 1; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == Environment.ProcessorCount - 1)
{
jobsQueued.Set();
}
e0.CheckedWait();
});
}
jobsQueued.CheckedWait();
int testJobsCount = 0;
int maxCount = 5;
void Job(object _)
{
if(Interlocked.Increment(ref testJobsCount) != maxCount)
{
ThreadPool.QueueUserWorkItem(Job);
}
else
{
testJobCompleted.Set();
}
}
ThreadPool.QueueUserWorkItem(Job);
testJobCompleted.CheckedWait();
e0.Set();
}
private static WaitCallback CreateRecursiveJob(int jobCount, int targetJobCount, AutoResetEvent testJobCompleted)
{
return _ =>
{
if (jobCount == targetJobCount)
{
testJobCompleted.Set();
}
else
{
ThreadPool.QueueUserWorkItem(CreateRecursiveJob(jobCount + 1, targetJobCount, testJobCompleted));
}
};
}
[Fact]
[OuterLoop]
public static void RunJobsAfterThreadTimeout()
{
ManualResetEvent e0 = new ManualResetEvent(false);
AutoResetEvent jobsQueued = new AutoResetEvent(false);
AutoResetEvent testJobCompleted = new AutoResetEvent(false);
int count = 0;
for(int i = 0; i < Environment.ProcessorCount - 1; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == Environment.ProcessorCount - 1)
{
jobsQueued.Set();
}
e0.CheckedWait();
});
}
jobsQueued.CheckedWait();
ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set());
testJobCompleted.CheckedWait();
Console.Write("Sleeping to time out thread\n");
Thread.Sleep(21000);
ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set());
testJobCompleted.CheckedWait();
e0.Set();
Console.Write("Sleeping to time out all threads\n");
Thread.Sleep(21000);
ThreadPool.QueueUserWorkItem( _ => testJobCompleted.Set());
testJobCompleted.CheckedWait();
}
[Fact]
public static void WorkQueueDepletionTest()
{
ManualResetEvent e0 = new ManualResetEvent(false);
int numLocalScheduled = 1;
int numGlobalScheduled = 1;
int numToSchedule = Environment.ProcessorCount * 64;
int numCompleted = 0;
object syncRoot = new object();
void ThreadLocalJob()
{
if(Interlocked.Increment(ref numLocalScheduled) <= numToSchedule)
{
Task.Factory.StartNew(ThreadLocalJob);
}
if(Interlocked.Increment(ref numLocalScheduled) <= numToSchedule)
{
Task.Factory.StartNew(ThreadLocalJob);
}
if (Interlocked.Increment(ref numCompleted) == numToSchedule * 2)
{
e0.Set();
}
}
void GlobalJob(object _)
{
if(Interlocked.Increment(ref numGlobalScheduled) <= numToSchedule)
{
ThreadPool.QueueUserWorkItem(GlobalJob);
}
if(Interlocked.Increment(ref numGlobalScheduled) <= numToSchedule)
{
ThreadPool.QueueUserWorkItem(GlobalJob);
}
if (Interlocked.Increment(ref numCompleted) == numToSchedule * 2)
{
e0.Set();
}
}
Task.Factory.StartNew(ThreadLocalJob);
ThreadPool.QueueUserWorkItem(GlobalJob);
e0.CheckedWait();
}
[Fact]
public static void WorkerThreadStateReset()
{
var cultureInfo = new CultureInfo("pt-BR");
var expectedCultureInfo = CultureInfo.CurrentCulture;
var expectedUICultureInfo = CultureInfo.CurrentUICulture;
int count = 0;
AutoResetEvent e0 = new AutoResetEvent(false);
for(int i = 0; i < Environment.ProcessorCount; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
CultureInfo.CurrentCulture = cultureInfo;
CultureInfo.CurrentUICulture = cultureInfo;
Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
if(Interlocked.Increment(ref count) == Environment.ProcessorCount)
{
e0.Set();
}
});
}
e0.CheckedWait();
// Run the test again to make sure we can reuse the threads.
count = 0;
for(int i = 0; i < Environment.ProcessorCount; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
Assert.Equal(expectedCultureInfo, CultureInfo.CurrentCulture);
Assert.Equal(expectedUICultureInfo, CultureInfo.CurrentUICulture);
Assert.Equal(ThreadPriority.Normal, Thread.CurrentThread.Priority);
if(Interlocked.Increment(ref count) == Environment.ProcessorCount)
{
e0.Set();
}
});
}
e0.CheckedWait();
}
[Fact]
public static void SettingMinThreadsWillCreateThreadsUpToMinimum()
{
ThreadPool.GetMinThreads(out int minThreads, out int unusedMin);
ThreadPool.GetMaxThreads(out int maxThreads, out int unusedMax);
try
{
ManualResetEvent e0 = new ManualResetEvent(false);
AutoResetEvent jobsQueued = new AutoResetEvent(false);
int count = 0;
ThreadPool.SetMaxThreads(minThreads, unusedMax);
for(int i = 0; i < minThreads + 1; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
if(Interlocked.Increment(ref count) == minThreads + 1)
{
jobsQueued.Set();
}
e0.CheckedWait();
});
}
Assert.False(jobsQueued.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
Assert.True(ThreadPool.SetMaxThreads(minThreads + 1, unusedMax));
Assert.True(ThreadPool.SetMinThreads(minThreads + 1, unusedMin));
jobsQueued.CheckedWait();
e0.Set();
}
finally
{
ThreadPool.SetMinThreads(minThreads, unusedMin);
ThreadPool.SetMaxThreads(maxThreads, unusedMax);
}
}
}
internal static class WaitThreadTests
{
private const int WaitThreadTimeoutTimeMs = 20000;
[Fact]
public static void SignalingRegisteredHandleCallsCalback()
{
var e0 = new AutoResetEvent(false);
var e1 = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(e0, (_, timedOut) =>
{
if(!timedOut)
{
e1.Set();
}
}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
e0.Set();
e1.CheckedWait();
}
[Fact]
public static void TimingOutRegisteredHandleCallsCallback()
{
var e0 = new AutoResetEvent(false);
var e1 = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(e0, (_, timedOut) =>
{
if(timedOut)
{
e1.Set();
}
}, null, ThreadTestHelpers.ExpectedTimeoutMilliseconds, true);
e1.CheckedWait();
}
[Fact]
public static void UnregisteringBeforeSignalingDoesNotCallCallback()
{
var e0 = new AutoResetEvent(false);
var e1 = new AutoResetEvent(false);
var registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) =>
{
e1.Set();
}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
registeredWaitHandle.Unregister(null);
Assert.False(e1.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
}
[Fact]
public static void RepeatingWaitFiresUntilUnregistered()
{
var e0 = new AutoResetEvent(false);
var e1 = new AutoResetEvent(false);
var registered = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) =>
{
e1.Set();
}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, false);
for (int i = 0; i < 4; ++i)
{
e0.Set();
e1.CheckedWait();
}
registered.Unregister(null);
e0.Set();
Assert.False(e1.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
}
[Fact]
public static void UnregisterEventSignaledWhenUnregistered()
{
var e0 = new AutoResetEvent(false);
var e1 = new AutoResetEvent(false);
var registered = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
registered.Unregister(e1);
e1.CheckedWait();
}
[Fact]
public static void CanRegisterMoreThan64Waits()
{
RegisteredWaitHandle[] handles = new RegisteredWaitHandle[65];
for(int i = 0; i < 65; ++i) {
handles[i] = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (_, __) => {}, null, -1, true);
}
for(int i = 0; i < 65; ++i) {
handles[i].Unregister(null);
}
}
[Fact]
public static void StateIsPasssedThroughToCallback()
{
object state = new object();
AutoResetEvent e0 = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(true), (callbackState, _) =>
{
if(state == callbackState)
{
e0.Set();
}
}, state, 0, true);
e0.CheckedWait();
}
[Fact]
[OuterLoop]
public static void WaitWithLongerTimeoutThanWaitThreadCanStillTimeout()
{
AutoResetEvent e0 = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (_, __) => e0.Set(), null, WaitThreadTimeoutTimeMs + 1000, true);
Thread.Sleep(WaitThreadTimeoutTimeMs);
e0.CheckedWait();
}
[Fact]
public static void UnregisterCallbackIsNotCalledAfterCallbackFinishesIfAnotherCallbackOnSameWaitRunning()
{
AutoResetEvent e0 = new AutoResetEvent(false);
AutoResetEvent e1 = new AutoResetEvent(false);
AutoResetEvent e2 = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) =>
{
e2.WaitOne(ThreadTestHelpers.UnexpectedTimeoutMilliseconds);
}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, false);
e0.Set();
Thread.Sleep(50);
e0.Set();
Thread.Sleep(50);
handle.Unregister(e1);
Assert.False(e1.WaitOne(ThreadTestHelpers.ExpectedTimeoutMilliseconds));
e2.Set();
}
[Fact]
public static void CallingUnregisterOnAutomaticallyUnregisteredHandleReturnsTrue()
{
AutoResetEvent e0 = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
e0.Set();
Thread.Sleep(ThreadTestHelpers.ExpectedTimeoutMilliseconds);
Assert.True(handle.Unregister(null));
}
[Fact]
public static void EventSetAfterUnregisterNotObservedOnWaitThread()
{
AutoResetEvent e0 = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
handle.Unregister(null);
e0.Set();
e0.CheckedWait();
}
[Fact]
public static void BlockingUnregister()
{
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
handle.Unregister(new InvalidWaitHandle());
}
[Fact]
public static void CanDisposeEventAfterUnblockingUnregister()
{
using(var e0 = new AutoResetEvent(false))
{
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
handle.Unregister(null);
}
}
[Fact]
public static void UnregisterEventSignaledWhenUnregisteredEvenIfAutoUnregistered()
{
var e0 = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) => {}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
e0.Set();
Thread.Sleep(50); // Ensure the callback has happened
var e1 = new AutoResetEvent(false);
handle.Unregister(e1);
e1.CheckedWait();
}
[Fact]
public static void BlockingUnregisterBlocksEvenIfCallbackExecuting()
{
bool callbackComplete = false;
var e0 = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(e0, (_, __) =>
{
Thread.Sleep(300);
callbackComplete = true;
}, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, true);
e0.Set();
Thread.Sleep(100); // Give the wait thread time to process removals.
handle.Unregister(new InvalidWaitHandle());
Assert.True(callbackComplete);
}
}
internal static class ThreadTestHelpers
{
public const int ExpectedTimeoutMilliseconds = 50;
public const int ExpectedMeasurableTimeoutMilliseconds = 500;
public const int UnexpectedTimeoutMilliseconds = 1000 * 30;
public static void CheckedWait(this WaitHandle wh)
{
Assert.True(wh.WaitOne(UnexpectedTimeoutMilliseconds));
}
}
internal sealed class InvalidWaitHandle : WaitHandle
{
}
internal sealed class Stopwatch
{
private DateTime _startTimeTicks;
private DateTime _endTimeTicks;
public void Restart() => _startTimeTicks = DateTime.UtcNow;
public void Stop() => _endTimeTicks = DateTime.UtcNow;
public long ElapsedMilliseconds => (long)(_endTimeTicks - _startTimeTicks).TotalMilliseconds;
}
internal static class Assert
{
public static void False(bool condition)
{
if (!condition)
return;
Console.WriteLine("Assertion failure - Assert.False");
throw new AssertionFailureException();
}
public static void True(bool condition)
{
if (condition)
return;
Console.WriteLine("Assertion failure - Assert.True");
throw new AssertionFailureException();
}
public static void Same<T>(T expected, T actual) where T : class
{
if (expected == actual)
return;
Console.WriteLine("Assertion failure - Assert.Same({0}, {1})", expected, actual);
throw new AssertionFailureException();
}
public static void Equal<T>(T expected, T actual)
{
if (EqualityComparer<T>.Default.Equals(expected, actual))
return;
Console.WriteLine("Assertion failure - Assert.Equal({0}, {1})", expected, actual);
throw new AssertionFailureException();
}
public static void NotEqual<T>(T notExpected, T actual)
{
if (!EqualityComparer<T>.Default.Equals(notExpected, actual))
return;
Console.WriteLine("Assertion failure - Assert.NotEqual({0}, {1})", notExpected, actual);
throw new AssertionFailureException();
}
public static void Throws<T>(Action action) where T : Exception
{
// TODO: Enable Assert.Throws<T> tests. There currently seem to be some reliability issues surrounding exceptions on Unix.
//try
//{
// action();
//}
//catch (T ex)
//{
// if (ex.GetType() == typeof(T))
// return;
// Console.WriteLine("Assertion failure - Assert.Throws<{0}>: got {1}", typeof(T), ex.GetType());
// throw new AssertionFailureException(ex);
//}
//catch (Exception ex)
//{
// Console.WriteLine("Assertion failure - Assert.Throws<{0}>: got {1}", typeof(T), ex.GetType());
// throw new AssertionFailureException(ex);
//}
//Console.WriteLine("Assertion failure - Assert.Throws<{0}>: got no exception", typeof(T));
//throw new AssertionFailureException();
}
public static void Null(object value)
{
if (value == null)
return;
Console.WriteLine("Assertion failure - Assert.Null");
throw new AssertionFailureException();
}
public static void NotNull(object value)
{
if (value != null)
return;
Console.WriteLine("Assertion failure - Assert.NotNull");
throw new AssertionFailureException();
}
}
internal class AssertionFailureException : Exception
{
public AssertionFailureException()
{
}
public AssertionFailureException(string message) : base(message)
{
}
public AssertionFailureException(Exception innerException) : base(null, innerException)
{
}
}
internal class FactAttribute : Attribute
{
}
internal class OuterLoopAttribute : Attribute
{
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using BitCoinSharp.IO;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Math;
namespace BitCoinSharp
{
/// <summary>
/// A collection of various utility methods that are helpful for working with the BitCoin protocol.
/// To enable debug logging from the library, run with -Dbitcoinj.logging=true on your command line.
/// </summary>
public static class Utils
{
// TODO: Replace this nanocoins business with something better.
/// <summary>
/// How many "nanocoins" there are in a BitCoin.
/// </summary>
/// <remarks>
/// A nanocoin is the smallest unit that can be transferred using BitCoin.
/// The term nanocoin is very misleading, though, because there are only 100 million
/// of them in a coin (whereas one would expect 1 billion.
/// </remarks>
public const ulong Coin = 100000000;
/// <summary>
/// How many "nanocoins" there are in 0.01 BitCoins.
/// </summary>
/// <remarks>
/// A nanocoin is the smallest unit that can be transferred using BitCoin.
/// The term nanocoin is very misleading, though, because there are only 100 million
/// of them in a coin (whereas one would expect 1 billion).
/// </remarks>
public const ulong Cent = 1000000;
/// <summary>
/// Convert an amount expressed in the way humans are used to into nanocoins.
/// </summary>
public static ulong ToNanoCoins(uint coins, uint cents)
{
Debug.Assert(cents < 100);
var bi = coins*Coin;
bi += cents*Cent;
return bi;
}
/// <summary>
/// Convert an amount expressed in the way humans are used to into nanocoins.
/// </summary>
/// <remarks>
/// This takes string in a format understood by <see cref="System.Double.Parse(string)"/>,
/// for example "0", "1", "0.10", "1.23E3", "1234.5E-5".
/// </remarks>
/// <exception cref="ArithmeticException">If you try to specify fractional nanocoins.</exception>
public static ulong ToNanoCoins(string coins)
{
var value = decimal.Parse(coins, NumberStyles.Float)*Coin;
if (value != Math.Round(value))
{
throw new ArithmeticException();
}
return checked((ulong) value);
}
public static void Uint32ToByteArrayBe(uint val, byte[] @out, int offset)
{
@out[offset + 0] = (byte) (val >> 24);
@out[offset + 1] = (byte) (val >> 16);
@out[offset + 2] = (byte) (val >> 8);
@out[offset + 3] = (byte) (val >> 0);
}
public static void Uint32ToByteArrayLe(uint val, byte[] @out, int offset)
{
@out[offset + 0] = (byte) (val >> 0);
@out[offset + 1] = (byte) (val >> 8);
@out[offset + 2] = (byte) (val >> 16);
@out[offset + 3] = (byte) (val >> 24);
}
/// <exception cref="IOException"/>
public static void Uint32ToByteStreamLe(uint val, Stream stream)
{
stream.Write((byte) (val >> 0));
stream.Write((byte) (val >> 8));
stream.Write((byte) (val >> 16));
stream.Write((byte) (val >> 24));
}
/// <exception cref="IOException"/>
public static void Uint64ToByteStreamLe(ulong val, Stream stream)
{
var bytes = BitConverter.GetBytes(val);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
stream.Write(bytes);
}
/// <summary>
/// See <see cref="DoubleDigest(byte[], int, int)"/>.
/// </summary>
public static byte[] DoubleDigest(byte[] input)
{
return DoubleDigest(input, 0, input.Length);
}
/// <summary>
/// Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. This is
/// standard procedure in BitCoin. The resulting hash is in big endian form.
/// </summary>
public static byte[] DoubleDigest(byte[] input, int offset, int length)
{
var algorithm = new SHA256Managed();
var first = algorithm.ComputeHash(input, offset, length);
return algorithm.ComputeHash(first);
}
/// <summary>
/// Calculates SHA256(SHA256(byte range 1 + byte range 2)).
/// </summary>
public static byte[] DoubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2)
{
var algorithm = new SHA256Managed();
var buffer = new byte[length1 + length2];
Array.Copy(input1, offset1, buffer, 0, length1);
Array.Copy(input2, offset2, buffer, length1, length2);
var first = algorithm.ComputeHash(buffer, 0, buffer.Length);
return algorithm.ComputeHash(first);
}
/// <summary>
/// Returns the given byte array hex encoded.
/// </summary>
public static string BytesToHexString(byte[] bytes)
{
var buf = new StringBuilder(bytes.Length*2);
foreach (var b in bytes)
{
var s = b.ToString("x");
if (s.Length < 2)
buf.Append('0');
buf.Append(s);
}
return buf.ToString();
}
/// <summary>
/// Returns a copy of the given byte array in reverse order.
/// </summary>
public static byte[] ReverseBytes(byte[] bytes)
{
// We could use the XOR trick here but it's easier to understand if we don't. If we find this is really a
// performance issue the matter can be revisited.
var buf = new byte[bytes.Length];
for (var i = 0; i < bytes.Length; i++)
buf[i] = bytes[bytes.Length - 1 - i];
return buf;
}
public static uint ReadUint32(byte[] bytes, int offset)
{
return (((uint) bytes[offset + 0]) << 0) |
(((uint) bytes[offset + 1]) << 8) |
(((uint) bytes[offset + 2]) << 16) |
(((uint) bytes[offset + 3]) << 24);
}
public static uint ReadUint32Be(byte[] bytes, int offset)
{
return (((uint) bytes[offset + 0]) << 24) |
(((uint) bytes[offset + 1]) << 16) |
(((uint) bytes[offset + 2]) << 8) |
(((uint) bytes[offset + 3]) << 0);
}
public static ushort ReadUint16Be(byte[] bytes, int offset)
{
return (ushort) ((bytes[offset] << 8) | bytes[offset + 1]);
}
/// <summary>
/// Calculates RIPEMD160(SHA256(input)). This is used in Address calculations.
/// </summary>
public static byte[] Sha256Hash160(byte[] input)
{
var sha256 = new SHA256Managed().ComputeHash(input);
var digest = new RipeMD160Digest();
digest.BlockUpdate(sha256, 0, sha256.Length);
var @out = new byte[20];
digest.DoFinal(@out, 0);
return @out;
}
/// <summary>
/// Returns the given value in nanocoins as a 0.12 type string.
/// </summary>
public static string BitcoinValueToFriendlyString(long value)
{
var negative = value < 0;
if (negative)
value = -value;
var coins = value/(long) Coin;
var cents = value%(long) Coin;
return string.Format("{0}{1}.{2:00}", negative ? "-" : "", coins, cents/(long) Cent);
}
/// <summary>
/// Returns the given value in nanocoins as a 0.12 type string.
/// </summary>
public static string BitcoinValueToFriendlyString(ulong value)
{
var coins = value/Coin;
var cents = value%Coin;
return string.Format("{0}.{1:00}", coins, cents/Cent);
}
/// <summary>
/// MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of
/// a 4 byte big endian length field, followed by the stated number of bytes representing
/// the number in big endian format.
/// </summary>
private static BigInteger DecodeMpi(byte[] mpi)
{
var length = ReadUint32Be(mpi, 0);
var buf = new byte[length];
Array.Copy(mpi, 4, buf, 0, (int) length);
return new BigInteger(1, buf);
}
// The representation of nBits uses another home-brew encoding, as a way to represent a large
// hash value in only 32 bits.
internal static BigInteger DecodeCompactBits(long compact)
{
var size = (byte) (compact >> 24);
var bytes = new byte[4 + size];
bytes[3] = size;
if (size >= 1) bytes[4] = (byte) (compact >> 16);
if (size >= 2) bytes[5] = (byte) (compact >> 8);
if (size >= 3) bytes[6] = (byte) (compact >> 0);
return DecodeMpi(bytes);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ExchangeServer {
public partial class ExchangeActiveSyncSettings {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// Image1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image Image1;
/// <summary>
/// locTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTitle;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// chkAllowNonProvisionable control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAllowNonProvisionable;
/// <summary>
/// lblRefreshInterval control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblRefreshInterval;
/// <summary>
/// hoursRefreshInterval control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.HoursBox hoursRefreshInterval;
/// <summary>
/// secApplication control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secApplication;
/// <summary>
/// ApplicationPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ApplicationPanel;
/// <summary>
/// chkAllowAttachments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAllowAttachments;
/// <summary>
/// locMaxAttachmentSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMaxAttachmentSize;
/// <summary>
/// sizeMaxAttachmentSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox sizeMaxAttachmentSize;
/// <summary>
/// secWSS control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secWSS;
/// <summary>
/// WSSPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel WSSPanel;
/// <summary>
/// chkWindowsFileShares control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkWindowsFileShares;
/// <summary>
/// chkWindowsSharePoint control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkWindowsSharePoint;
/// <summary>
/// secPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPassword;
/// <summary>
/// PasswordPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PasswordPanel;
/// <summary>
/// PasswordUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel PasswordUpdatePanel;
/// <summary>
/// chkRequirePasword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkRequirePasword;
/// <summary>
/// PasswordSettingsRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow PasswordSettingsRow;
/// <summary>
/// chkRequireAlphaNumeric control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkRequireAlphaNumeric;
/// <summary>
/// chkEnablePasswordRecovery control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnablePasswordRecovery;
/// <summary>
/// chkRequireEncryption control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkRequireEncryption;
/// <summary>
/// chkAllowSimplePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkAllowSimplePassword;
/// <summary>
/// locNumberAttempts control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locNumberAttempts;
/// <summary>
/// sizeNumberAttempts control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox sizeNumberAttempts;
/// <summary>
/// locMinimumPasswordLength control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMinimumPasswordLength;
/// <summary>
/// sizeMinimumPasswordLength control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox sizeMinimumPasswordLength;
/// <summary>
/// locTimeReenter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTimeReenter;
/// <summary>
/// sizeTimeReenter control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox sizeTimeReenter;
/// <summary>
/// locMinutes control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMinutes;
/// <summary>
/// locPasswordExpiration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPasswordExpiration;
/// <summary>
/// sizePasswordExpiration control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox sizePasswordExpiration;
/// <summary>
/// locDays control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDays;
/// <summary>
/// locPasswordHistory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPasswordHistory;
/// <summary>
/// sizePasswordHistory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ExchangeServer.UserControls.SizeBox sizePasswordHistory;
/// <summary>
/// btnSave control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSave;
/// <summary>
/// ValidationSummary1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
}
}
| |
// ------------------------------------------------------------------------------------------------
// <copyright file="VirtualNetworkLinkScenarioTests.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ------------------------------------------------------------------------------------------------
namespace PrivateDns.Tests.ScenarioTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using FluentAssertions;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Microsoft.Azure.Management.PrivateDns;
using Microsoft.Azure.Management.PrivateDns.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Rest.Azure;
using PrivateDns.Tests.Extensions;
using PrivateDns.Tests.Helpers;
using Xunit;
using Xunit.Abstractions;
public class VirtualNetworkLinkScenarioTests : BaseScenarioTests
{
public VirtualNetworkLinkScenarioTests(ITestOutputHelper output)
: base(output)
{
this.NetworkManagementClient = ClientFactory.GetNetworkClient(this.TestContext, this.ResourceHandler);
}
private NetworkManagementClient NetworkManagementClient { get; set; }
[Fact]
public void PutLink_LinkNotExistsWithoutRegistration_ExpectLinkCreated()
{
this.PutLink_LinkNotExists_ExpectLinkCreated(registrationEnabled: false);
}
[Fact]
public void PutLink_LinkNotExistsWithRegistration_ExpectLinkCreated()
{
this.PutLink_LinkNotExists_ExpectLinkCreated(registrationEnabled: true);
}
[Fact]
public void PutLink_LinkNotExistsIfNoneMatchSuccess_ExpectLinkCreated()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var virtualNetworkId = this.CreateVirtualNetwork(resourceGroupName).Id;
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
var createdVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: virtualNetworkLinkName,
ifNoneMatch: "*",
parameters: TestDataGenerator.GenerateVirtualNetworkLink(location: Constants.PrivateDnsZonesVirtualNetworkLinksLocation, virtualNetworkId: virtualNetworkId, registrationEnabled: false));
createdVirtualNetworkLink.Should().NotBeNull();
createdVirtualNetworkLink.ProvisioningState.Should().Be(Constants.ProvisioningStateSucceeded);
}
[Fact]
public void PutLink_LinkExistsIfMatchSuccess_ExpectLinkUpdated()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName);
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
ifMatch: createdVirtualNetworkLink.Etag,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(location: createdVirtualNetworkLink.Location, virtualNetworkId: createdVirtualNetworkLink.VirtualNetwork.Id, registrationEnabled: createdVirtualNetworkLink.RegistrationEnabled));
updatedVirtualNetworkLink.Should().NotBeNull();
updatedVirtualNetworkLink.ProvisioningState.Should().Be(Constants.ProvisioningStateSucceeded);
updatedVirtualNetworkLink.Etag.Should().NotBeNullOrEmpty().And.NotBe(createdVirtualNetworkLink.Etag);
}
[Fact]
public void PutLink_LinkExistsIfMatchFailure_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName);
Action updatedVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
ifMatch: Guid.NewGuid().ToString(),
parameters: TestDataGenerator.GenerateVirtualNetworkLink(location: createdVirtualNetworkLink.Location, virtualNetworkId: createdVirtualNetworkLink.VirtualNetwork.Id, registrationEnabled: createdVirtualNetworkLink.RegistrationEnabled));
updatedVirtualNetworkLinkAction.Should().Throw<CloudException>().Which.Response.ExtractAsyncErrorCode().Should().Be(HttpStatusCode.PreconditionFailed.ToString());
}
[Fact]
public void PatchLink_ZoneNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = TestDataGenerator.GeneratePrivateZoneName();
var virtualNetworkId = TestDataGenerator.GenerateVirtualNetworkArmId(this.SubscriptionId);
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
Action updatedVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: virtualNetworkLinkName,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(location: Constants.PrivateDnsZonesVirtualNetworkLinksLocation, virtualNetworkId: virtualNetworkId, registrationEnabled: false));
updatedVirtualNetworkLinkAction.Should().Throw<CloudException>().Which.Response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void PatchLink_LinkNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var virtualNetworkId = TestDataGenerator.GenerateVirtualNetworkArmId(this.SubscriptionId);
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
Action updateVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: virtualNetworkLinkName,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(location: Constants.PrivateDnsZonesVirtualNetworkLinksLocation, virtualNetworkId: virtualNetworkId, registrationEnabled: false));
updateVirtualNetworkLinkAction.Should().Throw<CloudException>().Which.Response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void PatchLink_LinkExistsEmptyRequest_ExpectNoError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName);
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink());
updatedVirtualNetworkLink.Should().NotBeNull();
}
[Fact]
public void PatchLink_EnableRegistration_ExpectRegistrationEnabled()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName, registrationEnabled: false);
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(registrationEnabled: true));
updatedVirtualNetworkLink.RegistrationEnabled.Should().BeTrue();
}
[Fact]
public void PatchLink_DisableRegistration_ExpectRegistrationDisabled()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName, registrationEnabled: true);
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(registrationEnabled: false));
updatedVirtualNetworkLink.RegistrationEnabled.Should().BeFalse();
}
[Fact]
public void PatchLink_LinkExistsAddTags_ExpectTagsAdded()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName, tags: null);
var virtualNetworkLinkTags = TestDataGenerator.GenerateTags();
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(tags: virtualNetworkLinkTags));
updatedVirtualNetworkLink.Should().NotBeNull();
updatedVirtualNetworkLink.Tags.Should().NotBeNull().And.BeEquivalentTo(virtualNetworkLinkTags);
}
[Fact]
public void PatchLink_LinkExistsChangeTags_ExpectTagsChanged()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName, tags: TestDataGenerator.GenerateTags());
var updatedVirtualNetworkLinkTags = TestDataGenerator.GenerateTags(startFrom: createdVirtualNetworkLink.Tags.Count);
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(tags: updatedVirtualNetworkLinkTags));
updatedVirtualNetworkLink.Should().NotBeNull();
updatedVirtualNetworkLink.Tags.Should().NotBeNull().And.BeEquivalentTo(updatedVirtualNetworkLinkTags);
}
[Fact]
public void PatchLink_LinkExistsRemoveTags_ExpectTagsRemoved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName, tags: TestDataGenerator.GenerateTags());
var updatedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(tags: new Dictionary<string, string>()));
updatedVirtualNetworkLink.Should().NotBeNull();
updatedVirtualNetworkLink.Tags.Should().BeEmpty();
}
[Fact]
public void PatchLink_LinkExistsChangeVirtualNetwork_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLink = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName, tags: TestDataGenerator.GenerateTags());
var updatedVirtualNetworkId = TestDataGenerator.GenerateVirtualNetworkArmId(this.SubscriptionId);
Action updateVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Update(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: createdVirtualNetworkLink.Name,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(virtualNetworkId: updatedVirtualNetworkId));
updateVirtualNetworkLinkAction.Should().Throw<CloudException>().Which.Response.ExtractAsyncErrorCode().Should().Be(HttpStatusCode.BadRequest.ToString());
}
[Fact]
public void GetLink_ZoneNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var nonExistentPrivateZoneName = TestDataGenerator.GeneratePrivateZoneName();
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
Action retrieveVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Get(resourceGroupName, nonExistentPrivateZoneName, virtualNetworkLinkName);
retrieveVirtualNetworkLinkAction.Should().Throw<CloudException>().Which.Response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void GetLink_LinkNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var nonExistentVirtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
Action retrieveVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Get(resourceGroupName, privateZoneName, nonExistentVirtualNetworkLinkName);
retrieveVirtualNetworkLinkAction.Should().Throw<CloudException>().Which.Response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public void GetLink_LinkExists_ExpectLinkRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var virtualNetworkLinkName = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName).Name;
var retrievedVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.Get(resourceGroupName, privateZoneName, virtualNetworkLinkName);
retrievedVirtualNetworkLink.Should().NotBeNull();
retrievedVirtualNetworkLink.Id.Should().Be(TestDataGenerator.GenerateVirtualNetworkLinkArmId(this.SubscriptionId, resourceGroupName, privateZoneName, virtualNetworkLinkName));
retrievedVirtualNetworkLink.Name.Should().Be(virtualNetworkLinkName);
retrievedVirtualNetworkLink.Type.Should().Be(Constants.PrivateDnsZonesVirtualNetworkLinksResourceType);
retrievedVirtualNetworkLink.Location.Should().Be(Constants.PrivateDnsZonesVirtualNetworkLinksLocation);
}
[Fact]
public void ListLinks_NoLinksPresent_ExpectNoLinksRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var listResult = this.PrivateDnsManagementClient.VirtualNetworkLinks.List(resourceGroupName, privateZoneName);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().BeNull();
var listVirtualNetworkLinks = listResult.ToArray();
listVirtualNetworkLinks.Count().Should().Be(0);
}
[Fact]
public void ListLinks_MultipleLinksPresent_ExpectMultipleLinksRetrieved()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLinks = this.CreateVirtualNetworkLinks(resourceGroupName, privateZoneName);
var listResult = this.PrivateDnsManagementClient.VirtualNetworkLinks.List(resourceGroupName, privateZoneName);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().BeNull();
var listVirtualNetworkLinks = listResult.ToArray();
listVirtualNetworkLinks.Count().Should().Be(createdVirtualNetworkLinks.Count());
listVirtualNetworkLinks.All(listedVirtualNetworkLink => ValidateListedVirtualNetworkLinkIsExpected(listedVirtualNetworkLink, createdVirtualNetworkLinks));
}
[Fact]
public void ListLinks_WithTopParameter_ExpectSpecifiedLinksRetrieved()
{
const int numVirtualNetworkLinks = 2;
const int topValue = numVirtualNetworkLinks - 1;
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLinks = this.CreateVirtualNetworkLinks(resourceGroupName, privateZoneName, numVirtualNetworkLinks: numVirtualNetworkLinks);
var expectedVirtualNetworkLinks = createdVirtualNetworkLinks.OrderBy(x => x.Name).Take(topValue);
var listResult = this.PrivateDnsManagementClient.VirtualNetworkLinks.List(resourceGroupName, privateZoneName, top: topValue);
listResult.Should().NotBeNull();
listResult.NextPageLink.Should().NotBeNullOrEmpty();
var listVirtualNetworkLinks = listResult.ToArray();
listVirtualNetworkLinks.Count().Should().Be(topValue);
listVirtualNetworkLinks.All(listedVirtualNetworkLink => ValidateListedVirtualNetworkLinkIsExpected(listedVirtualNetworkLink, expectedVirtualNetworkLinks));
}
[Fact]
public void ListLinks_ListNextPage_ExpectNextLinksRetrieved()
{
const int numVirtualNetworkLinks = 2;
const int topValue = numVirtualNetworkLinks - 1;
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var createdVirtualNetworkLinks = this.CreateVirtualNetworkLinks(resourceGroupName, privateZoneName, numVirtualNetworkLinks: numVirtualNetworkLinks);
var expectedNextVirtualNetworkLinks = createdVirtualNetworkLinks.OrderBy(x => x.Name).Skip(topValue);
var initialListResult = this.PrivateDnsManagementClient.VirtualNetworkLinks.List(resourceGroupName, privateZoneName, top: topValue);
var nextLink = initialListResult.NextPageLink;
var nextListResult = this.PrivateDnsManagementClient.VirtualNetworkLinks.ListNext(nextLink);
nextListResult.Should().NotBeNull();
nextListResult.NextPageLink.Should().BeNull();
var nextListedVirtualNetworkLinks = nextListResult.ToArray();
nextListedVirtualNetworkLinks.Count().Should().Be(topValue);
nextListedVirtualNetworkLinks.All(listedVirtualNetworkLink => ValidateListedVirtualNetworkLinkIsExpected(listedVirtualNetworkLink, expectedNextVirtualNetworkLinks));
}
[Fact]
public void DeleteLink_ZoneNotExists_ExpectError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var nonExistentPrivateZoneName = TestDataGenerator.GeneratePrivateZoneName();
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
Action deleteVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Delete(resourceGroupName, nonExistentPrivateZoneName, virtualNetworkLinkName);
deleteVirtualNetworkLinkAction.Should().NotThrow();
}
[Fact]
public void DeleteLink_LinkNotExists_ExpectNoError()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var nonExistentVirtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
Action deleteVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Delete(resourceGroupName, privateZoneName, nonExistentVirtualNetworkLinkName);
deleteVirtualNetworkLinkAction.Should().NotThrow();
}
[Fact]
public void DeleteLink_LinkExists_ExpectLinkDeleted()
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var virtualNetworkLinkName = this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName).Name;
Action deleteVirtualNetworkLinkAction = () => this.PrivateDnsManagementClient.VirtualNetworkLinks.Delete(resourceGroupName, privateZoneName, virtualNetworkLinkName);
deleteVirtualNetworkLinkAction.Should().NotThrow();
}
private void PutLink_LinkNotExists_ExpectLinkCreated(bool registrationEnabled)
{
var resourceGroupName = this.CreateResourceGroup().Name;
var privateZoneName = this.CreatePrivateZone(resourceGroupName).Name;
var virtualNetworkId = this.CreateVirtualNetwork(resourceGroupName).Id;
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
var virtualNetworkLinkParams = TestDataGenerator.GenerateVirtualNetworkLink(
location: Constants.PrivateDnsZonesVirtualNetworkLinksLocation,
virtualNetworkId: virtualNetworkId,
registrationEnabled: registrationEnabled);
var createdVirtualNetworkLink = this.PrivateDnsManagementClient.VirtualNetworkLinks.CreateOrUpdate(resourceGroupName, privateZoneName, virtualNetworkLinkName, virtualNetworkLinkParams);
createdVirtualNetworkLink.Should().NotBeNull();
createdVirtualNetworkLink.Id.Should().Be(TestDataGenerator.GenerateVirtualNetworkLinkArmId(this.SubscriptionId, resourceGroupName, privateZoneName, virtualNetworkLinkName));
createdVirtualNetworkLink.Name.Should().Be(virtualNetworkLinkName);
createdVirtualNetworkLink.Location.Should().Be(Constants.PrivateDnsZonesVirtualNetworkLinksLocation);
createdVirtualNetworkLink.Type.Should().Be(Constants.PrivateDnsZonesVirtualNetworkLinksResourceType);
createdVirtualNetworkLink.Etag.Should().NotBeNullOrEmpty();
createdVirtualNetworkLink.VirtualNetwork.Should().NotBeNull();
createdVirtualNetworkLink.VirtualNetwork.Id.Should().Be(virtualNetworkId);
createdVirtualNetworkLink.RegistrationEnabled.Should().Be(registrationEnabled);
createdVirtualNetworkLink.ProvisioningState.Should().Be(Constants.ProvisioningStateSucceeded);
createdVirtualNetworkLink.VirtualNetworkLinkState.Should().Be(registrationEnabled ? Constants.VirtualNetworkLinkStateInProgress : Constants.VirtualNetworkLinkStateCompleted);
createdVirtualNetworkLink.Tags.Should().BeNull();
}
private VirtualNetwork CreateVirtualNetwork(string resourceGroupName, string virtualNetworkName = null)
{
virtualNetworkName = virtualNetworkName ?? TestDataGenerator.GenerateVirtualNetworkName();
var createdVirtualNetwork = this.NetworkManagementClient.CreateVirtualNetwork(resourceGroupName: resourceGroupName, virtualNetworkName: virtualNetworkName);
createdVirtualNetwork.Should().NotBeNull();
return createdVirtualNetwork;
}
private VirtualNetworkLink CreateVirtualNetworkLink(
string resourceGroupName,
string privateZoneName,
bool registrationEnabled = false,
IDictionary<string, string> tags = null)
{
var virtualNetworkId = this.CreateVirtualNetwork(resourceGroupName).Id;
var virtualNetworkLinkName = TestDataGenerator.GenerateVirtualNetworkLinkName();
return this.PrivateDnsManagementClient.VirtualNetworkLinks.CreateOrUpdate(
resourceGroupName: resourceGroupName,
privateZoneName: privateZoneName,
virtualNetworkLinkName: virtualNetworkLinkName,
parameters: TestDataGenerator.GenerateVirtualNetworkLink(
location: Constants.PrivateDnsZonesVirtualNetworkLinksLocation,
virtualNetworkId: virtualNetworkId,
registrationEnabled: registrationEnabled,
tags: tags));
}
private ICollection<VirtualNetworkLink> CreateVirtualNetworkLinks(string resourceGroupName, string privateZoneName, int numVirtualNetworkLinks = 2)
{
var createdVirtualNetworkLinks = new List<VirtualNetworkLink>();
for (var i = 0; i < numVirtualNetworkLinks; i++)
{
createdVirtualNetworkLinks.Add(this.CreateVirtualNetworkLink(resourceGroupName, privateZoneName));
}
return createdVirtualNetworkLinks;
}
private static bool ValidateListedVirtualNetworkLinkIsExpected(VirtualNetworkLink listedVirtualNetworkLink, IEnumerable<VirtualNetworkLink> expectedVirtualNetworkLinks)
{
return expectedVirtualNetworkLinks.Any(expectedVirtualNetworkLink => string.Equals(expectedVirtualNetworkLink.Id, listedVirtualNetworkLink.Id, StringComparison.OrdinalIgnoreCase));
}
}
}
| |
// SessionsViewModel.cs
//
using System;
using System.Collections.Generic;
using Slick;
using System.Runtime.CompilerServices;
using Xrm.Sdk;
using Client.TimeSheet.Model;
using SparkleXrm.GridEditor;
using TimeSheet.Client.ViewModel;
namespace Client.TimeSheet.ViewModel
{
public class SessionsViewModel : DataViewBase
{
#region Constructor
public SessionsViewModel()
{
}
#endregion
#region Fields
private Dictionary<int, List<dev1_session>> weeks = new Dictionary<int, List<dev1_session>>();
private DateTime _selectedDate;
private List<dev1_session> data = new List<dev1_session>();
#endregion
#region Public Fields
public DateTime WeekStart;
public DateTime WeekEnd;
public DateTime SelectedDay;
public Guid SelectedActivityID;
public EntityReference SelectedActivity;
#endregion
#region Methods
public List<dev1_session> GetCurrentWeek()
{
return weeks[WeekStart.GetTime()];
}
public void SetCurrentWeek(DateTime date)
{
_selectedDate = date;
WeekStart = DateTimeEx.FirstDayOfWeek(date);
WeekEnd= DateTimeEx.LastDayOfWeek(date);
Refresh();
}
private int? GetSelectedDayIndex()
{
if (this.SelectedDay == null)
return null;
int daysDiff = (this.SelectedDay-this.WeekStart)/(24*60*60*1000);
return daysDiff+1;
}
/// <summary>
/// When an activity row is selected in the
/// </summary>
/// <param name="entityReference"></param>
public void SetCurrentActivity(EntityReference entityReference, int day)
{
bool hasChanged = (entityReference!=null && entityReference.Id!=null? entityReference.Id.Value : null) != (this.SelectedActivity!=null && this.SelectedActivity.Id!=null? this.SelectedActivity.Id.Value : null);
hasChanged = hasChanged || (day != GetSelectedDayIndex());
if (!hasChanged)
return;
if (day > 0)
this.SelectedDay = DateTimeEx.DateAdd(DateInterval.Days, day - 1, this.WeekStart);
else
this.SelectedDay = null;
this.SelectedActivity = entityReference;
if (entityReference != null && entityReference.Id != null)
this.SelectedActivityID = entityReference.Id;
else
this.SelectedActivityID = null;
RefreshActivityView();
}
private void AddSession(List<dev1_session> sessions, dev1_session session)
{
sessions.Add(session);
// Set the account field derived from the regarding object (depending on type)
if (session.opportunity_customerid != null)
session.Account = session.opportunity_customerid;
else if (session.contract_customerid != null)
session.Account = session.contract_customerid;
else if (session.incident_customerid != null)
session.Account = session.incident_customerid;
else if (session.activitypointer_regardingobjectid != null && session.activitypointer_regardingobjectid.LogicalName == "account")
session.Account = session.activitypointer_regardingobjectid;
// Calculate duration/end date
if (session.dev1_EndTime == null && session.dev1_Duration!=null)
OnDurationChanged(session);
else if (session.dev1_Duration == null)
OnStartEndDateChanged(session);
// Is the session read only?
if (session.StatusCode != null && session.StatusCode.Value.Value != (int)dev1_session_StatusCode.Draft)
session.EntityState = EntityStates.ReadOnly;
// Subscribe to the Property Changed event so we can re-calculate the duration or end date
session.PropertyChanged += new Xrm.ComponentModel.PropertyChangedEventHandler(OnSessionPropertyChanged);
}
private void OnSessionPropertyChanged(object sender, Xrm.ComponentModel.PropertyChangedEventArgs e)
{
if ((e.PropertyName == "dev1_starttime") || (e.PropertyName == "dev1_endtime"))
{
OnStartEndDateChanged(sender);
}
else if (e.PropertyName == "dev1_duration")
{
OnDurationChanged(sender);
}
// TODO: This should really provide the row that is changing
Refresh();
}
public override bool OnBeforeEdit(object item)
{
Entity session = (Entity)item;
if (item!=null)
return (session.EntityState != EntityStates.ReadOnly);
else
return true;
}
private static void OnDurationChanged(object sender)
{
dev1_session session = (dev1_session)sender;
DateTime startTime = session.dev1_StartTime;
if (startTime != null)
{
int? duration = session.dev1_Duration;
int? startTimeMilliSeconds = startTime.GetTime();
startTimeMilliSeconds = startTimeMilliSeconds + (duration * 1000 * 60);
DateTime newEndDate = new DateTime((int)startTimeMilliSeconds);
session.dev1_EndTime = newEndDate;
}
}
private static void OnStartEndDateChanged(object sender)
{
// Calculate the duration
dev1_session session = (dev1_session)sender;
// Ensure that the end date is the same as the start date
if (session.dev1_StartTime != null && session.dev1_EndTime != null)
{
session.dev1_EndTime.SetDate(session.dev1_StartTime.GetUTCDate());
session.dev1_EndTime.SetMonth(session.dev1_StartTime.GetUTCMonth());
session.dev1_EndTime.SetFullYear(session.dev1_StartTime.GetUTCFullYear());
}
session.dev1_Duration = SessionVM.CalculateDuration(session.dev1_StartTime, session.dev1_EndTime);
}
/// <summary>
/// Only show the view of selected activity
/// </summary>
private void RefreshActivityView()
{
// filter sessions by activity and seleced day
data = new List<dev1_session>();
foreach (dev1_session session in GetCurrentWeek())
{
if (
(
(SelectedActivityID == null)
||
(session.dev1_ActivityId == SelectedActivityID.ToString())
)
&&
(
(SelectedDay == null)
||
(session.dev1_StartTime.GetDay() == SelectedDay.GetDay())
)
) // TODO: filter day
{
data.Add(session);
}
}
// Notify
DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs();
args.From = 0;
args.To = data.Count - 1;
this.OnDataLoaded.Notify(args, null, null);
this.OnRowsChanged.Notify(null, null, this);
}
/// <summary>
/// Get all the new and inserted sessions
/// </summary>
/// <returns></returns>
public List<dev1_session> GetEditedSessions()
{
List<dev1_session> edited = new List<dev1_session>();
foreach (dev1_session session in weeks[WeekStart.GetTime()])
{
if (session.dev1_sessionId == null || session.EntityState == EntityStates.Changed || session.EntityState == EntityStates.Created)
{
edited.Add(session);
}
}
return edited;
}
#endregion
#region Overridden Methods
public override PagingInfo GetPagingInfo()
{
return null;
}
public override int GetLength()
{
if (data != null)
return data.Count;
else
return 0;
}
public override void RemoveItem(object id)
{
// Only allow removing from current week selected
weeks[WeekStart.GetTime()].Remove((dev1_session)id);
}
public override object GetItem(int index)
{
return data[index];
}
public override void SetPagingOptions(PagingInfo p)
{
}
public override void Refresh()
{
if (weeks[WeekStart.GetTime()] == null)
{
this.OnDataLoading.Notify(null, null, null);
// We need to load the data from the server
OrganizationServiceProxy.BeginRetrieveMultiple(String.Format(Queries.SessionsByWeekStartDate, DateTimeEx.ToXrmString(WeekStart), DateTimeEx.ToXrmString(WeekEnd)), delegate(object result)
{
try
{
EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(dev1_session));
// Set data
List<dev1_session> sessions = new List<dev1_session>();
weeks[WeekStart.GetTime()] = sessions;
foreach (Entity e in results.Entities)
{
AddSession(sessions, (dev1_session)e);
}
RefreshActivityView();
}
catch (Exception ex)
{
// Show error
Script.Alert("There was an error loading the Timesheet sessions\n" + ex.Message);
}
});
}
else
{
RefreshActivityView();
}
// Only show the selected
}
public override void AddItem(object item)
{
// TODO: Set current week from the datetime on the new session
if (this.SelectedActivity != null)
{
List<dev1_session> sessions = GetCurrentWeek();
dev1_session itemAdding = (dev1_session)item;
dev1_session newItem = new dev1_session();
newItem.dev1_Description = itemAdding.dev1_Description;
newItem.dev1_StartTime = itemAdding.dev1_StartTime;
newItem.dev1_Duration = itemAdding.dev1_Duration;
newItem.Account = itemAdding.Account;
newItem.activitypointer_regardingobjectid = itemAdding.activitypointer_regardingobjectid == null ? this.SelectedActivity : itemAdding.activitypointer_regardingobjectid;
newItem.activitypointer_subject = itemAdding.activitypointer_regardingobjectid == null ? this.SelectedActivity.Name : itemAdding.activitypointer_subject;
newItem.dev1_ActivityId = this.SelectedActivity.Id.ToString();
newItem.dev1_ActivityTypeName = this.SelectedActivity.LogicalName;
// Set the activity reference
switch (this.SelectedActivity.LogicalName)
{
case "phonecall":
newItem.dev1_PhoneCallId = this.SelectedActivity;
break;
case "task":
newItem.dev1_TaskId = this.SelectedActivity;
break;
case "letter":
newItem.dev1_LetterId = this.SelectedActivity;
break;
case "email":
newItem.dev1_EmailId = this.SelectedActivity;
break;
}
newItem.EntityState = EntityStates.Created;
// If no date set, set to the currently selected date
if (newItem.dev1_StartTime == null)
{
newItem.dev1_StartTime = SelectedDay == null ? WeekStart : SelectedDay;
}
// Add to the sessions view cache
AddSession(sessions, newItem);
// Add to the data view as well
data.Add(newItem);
// refresh
DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs();
args.From = data.Count - 1;
args.To = data.Count - 1;
this.OnDataLoaded.Notify(args, null, null);
this.OnRowsChanged.Notify(null, null, null);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
// Define MATRIXFRAMES if you want to use matrices for keyframes
// instead of SRT transforms. Doing so will cause collapsing when
// interpolating, and will cause the file size to explode.
namespace KiloWatt.Animation.Animation
{
// Keyframe represents one particular bone's pose at one point in time.
// It includes position, orientation and scale.
public class Keyframe
{
#if !MATRIXFRAMES
public Keyframe()
{
ori_ = Quaternion.Identity;
scale_ = Vector3.One;
}
public Keyframe(Vector3 pos, Quaternion ori)
: this(pos, ori, Vector3.One)
{
}
public Keyframe(Vector3 pos, Quaternion ori, Vector3 scale)
{
pos_ = pos;
ori_ = ori;
scale_ = scale;
}
// Offset from parent, in parent space
public Vector3 Pos { get { return pos_; } set { pos_ = value; } }
Vector3 pos_;
// Orientation relative to parent
public Quaternion Ori { get { return ori_; } set { ori_ = value; } }
Quaternion ori_;
// Scale relative to parent
public Vector3 Scale { get { return scale_; } set { scale_ = value; } }
Vector3 scale_;
#else
public Keyframe()
{
transform_ = Matrix.Identity;
}
Matrix transform_;
public Matrix Transform { get { return transform_; } set { transform_ = value; } }
#endif
// A simple unit test makes sure some keyframe functions work right.
public static bool Tested = Keyframe.Test();
static bool Test()
{
#if DEBUG && !MATRIXFRAMES
Keyframe kf = new Keyframe();
Matrix mx = Matrix.CreateScale(0.15f, 0.20f, 0.25f) *
Matrix.CreateRotationY((float)(Math.PI/6)) *
Matrix.CreateRotationX(0.1f) *
Matrix.CreateRotationZ(-0.1f) *
Matrix.CreateTranslation(2, 0, 1);
Keyframe.CreateFromMatrix(ref mx, kf);
Matrix two;
kf.ToMatrix(out two);
Matrix three = Matrix.Invert(mx) * two;
// verify that forward and back is transparent
for (int i = 0; i != 16; ++i)
{
float f = MatrixElement(ref three, i);
if ((i % 5) == 0)
System.Diagnostics.Debug.Assert(Math.Abs(f - 1) < 1e-4);
else
System.Diagnostics.Debug.Assert(Math.Abs(f) < 1e-4);
}
#endif
return true;
}
#if !MATRIXFRAMES
// load from reading
internal void Load(Vector3 pos, Quaternion ori, Vector3 scale)
{
pos_ = pos;
ori_ = ori;
scale_ = scale;
}
#endif
/// <summary>
/// Evaluate the difference between two keyframes as a floating point number.
/// </summary>
/// <param name="o">The keyframe to compare to.</param>
/// <returns>A measurement of how different two keyframes are. 0.01 is intended to be
/// largely imperceptible; 1.0 is a big difference (but it could be even bigger). A
/// value below 0 is never returned, and 0 is returned for identity.</returns>
public float DifferenceFrom(Keyframe o)
{
#if !MATRIXFRAMES
float dp = (pos_ - o.pos_).Length();
float ds = (scale_ - o.scale_).Length();
Matrix m1 = Matrix.CreateFromQuaternion(ori_);
Matrix m2 = Matrix.CreateFromQuaternion(o.ori_);
float dr = (float)Math.Pow(((m1.Right - m2.Right).Length()
+ (m1.Up - m2.Up).Length() + (m1.Backward - m2.Backward).Length()), 4) * 100000;
return (dp + ds + dr);
#else
Matrix diff = Matrix.Invert(transform_) * o.transform_;
float diff = 0;
for (int i = 0; i < 16; ++i)
{
diff = diff + Math.Abs(MatrixElement(ref transform_, i) - MatrixElement(ref o.transform_, i));
}
#endif
}
/// <summary>
/// Convert to matrix, in order scale, rotation, translation
/// </summary>
/// <returns>A matrix representing the keyframe transform.</returns>
public Matrix ToMatrix()
{
#if !MATRIXFRAMES
Matrix ret;
ToMatrix(out ret);
return ret;
#else
return transform_;
#endif
}
#if !MATRIXFRAMES
// Convert to matrix, not taking scale into account
public Matrix ToMatrixNoScale()
{
Matrix ret;
ToMatrixNoScale(out ret);
return ret;
}
#endif
// Convert to matrix, in order scale, rotation, translation
public void ToMatrix(out Matrix m)
{
#if !MATRIXFRAMES
m = Matrix.CreateFromQuaternion(ori_);
m.M11 *= scale_.X;
m.M12 *= scale_.X;
m.M13 *= scale_.X;
m.M21 *= scale_.Y;
m.M22 *= scale_.Y;
m.M23 *= scale_.Y;
m.M31 *= scale_.Z;
m.M32 *= scale_.Z;
m.M33 *= scale_.Z;
m.Translation = pos_;
#else
m = transform_;
#endif
}
#if !MATRIXFRAMES
// Convert to matrix, in order rotation, translation
public void ToMatrixNoScale(out Matrix m)
{
m = Matrix.CreateFromQuaternion(ori_);
m.Translation = pos_;
}
#endif
/// <summary>
/// Interpolate between two keyframes into a provided storage keyframe.
/// Interpolation of quaternions uses Lerp and normalization. Interpolation
/// is always done the short way around.
/// </summary>
/// <param name="left">The value to use at t == 0.</param>
/// <param name="right">The value to use at t == 1.</param>
/// <param name="t">The "time" factor between 0 and 1.</param>
/// <param name="result">The destination for the interpolation.</param>
/// <returns>result (for convenience).</returns>
public static Keyframe Interpolate(Keyframe left, Keyframe right, float t, Keyframe result)
{
#if DEBUG
if (left == null)
throw new ArgumentNullException("left");
if (right == null)
throw new ArgumentNullException("right");
if (result == null)
throw new ArgumentNullException("result");
#endif
#if !MATRIXFRAMES
result.pos_ = left.pos_ * (1 - t) + right.pos_ * t;
result.scale_ = left.scale_ * (1 - t) + right.scale_ * t;
Quaternion b = right.ori_;
if (Quaternion.Dot(left.ori_, b) < 0)
b = -b;
// I'm doing lerp, rather than slerp. The idea is that keyframes will be dense enough
// that the difference in angular velocity is very small, and lerp is a lot cheaper
// than slerp.
result.ori_ = Quaternion.Normalize(left.ori_ * (1 - t) + b * t);
#else
result.transform_ = left.transform_ * (1 - t) + right.transform_ * t;
#endif
return result;
}
/// <summary>
/// Copy the values of a first keyframe into myself.
/// </summary>
/// <param name="o">The other keyframe to copy from.</param>
/// <return>this</return>
public Keyframe CopyFrom(Keyframe o)
{
#if !MATRIXFRAMES
pos_ = o.pos_;
scale_ = o.scale_;
ori_ = o.ori_;
#else
transform_ = o.transform_;
#endif
return this;
}
// A Keyframe that does no scale, rotation or translation
public static Keyframe Identity { get { return identity_; } }
static Keyframe identity_ = new Keyframe();
/// <summary>
/// Given a base keyframe, and a "delta" keyframe, construct a keyframe that
/// represents the first transformation followed by a weighted amount of the
/// second keyframe.
/// </summary>
/// <param name="first">The base keyframe. Cannot be the same object as "result."</param>
/// <param name="second">The delta keyframe. Can be the same object as "result."</param>
/// <param name="weight">How much of the delta keyframe to apply (typically 0 .. 1)</param>
/// <param name="result">The composed keyframe data will be stored here.</param>
/// <returns>result (for convenience)</returns>
public static Keyframe Compose(Keyframe first, Keyframe second, float weight, Keyframe result)
{
#if DEBUG
// "first" and "result" can't be the same objects, although
// "second" and "result" can be.
System.Diagnostics.Debug.Assert(first != result);
if (first == null)
throw new ArgumentNullException("left");
if (second == null)
throw new ArgumentNullException("right");
if (result == null)
throw new ArgumentNullException("result");
#endif
#if !MATRIXFRAMES
Interpolate(Identity, second, weight, result);
Vector3 pos;
Vector3.Transform(ref result.pos_, ref first.ori_, out pos);
result.pos_ = first.pos_ + pos;
result.scale_ = first.scale_ * second.scale_;
// Yes, XNA does quaternions in a different order from matrices. Blech.
result.ori_ = second.ori_ * first.ori_;
#else
result.transform_ = first.transform_ * (Matrix.Identity * (1 - weight) + second.transform_ * weight);
#endif
return result;
}
// Given a matrix, decompose that matrix into a Keyframe.
// This works for matrices that don't contain shear or off-axis scale.
public static Keyframe CreateFromMatrix(Matrix mat)
{
return CreateFromMatrix(ref mat);
}
// Given a matrix, decompose that matrix into a Keyframe.
// This works for matrices that don't contain shear or off-axis scale.
public static Keyframe CreateFromMatrix(ref Matrix mat)
{
Keyframe k = new Keyframe();
return CreateFromMatrix(ref mat, k);
}
/// <summary>
/// Decompose the given matrix into a scale/rotation/translation
/// keyframe. The method used is not well behaved when the scale
/// along one axis is very close to 0, so don't scale down by more
/// than about 1/10,000.
/// This works for matrices that don't contain shear or off-axis scale.
/// </summary>
/// <param name="xform">The transform to decompose.</param>
/// <param name="ret">The keyframe to decompose into.</param>
/// <returns>ret (for convenience)</returns>
public static Keyframe CreateFromMatrix(ref Matrix xform, Keyframe ret)
{
#if DEBUG
if (ret == null)
throw new ArgumentNullException("ret");
#endif
#if !MATRIXFRAMES
// decompose the matrix into scale, rotation and translaction
ret.Scale = new Vector3(
(new Vector3(xform.M11, xform.M12, xform.M13)).Length(),
(new Vector3(xform.M21, xform.M22, xform.M23)).Length(),
(new Vector3(xform.M31, xform.M32, xform.M33)).Length());
ret.Pos = xform.Translation;
// I can't extract rotation if one of the axes is zero scale.
// That's unfortunate, as someone might want to animation an object
// becoming pancaked and spinning. Just don't make it THAT much
// of a pancake then.
Matrix mat = Matrix.Identity;
if (Math.Abs(ret.Scale.X) > 1e-6 && Math.Abs(ret.Scale.Y) > 1e-6
&& Math.Abs(ret.Scale.Z) > 1e-6)
{
Vector3 right = Vector3.Normalize(xform.Right);
Vector3 up = Vector3.Normalize(xform.Up - right * Vector3.Dot(xform.Up, right));
Vector3 backward = Vector3.Cross(right, up);
if (Vector3.Dot(xform.Backward, backward) < 0) {
// matrix is mirrored
ret.Scale = ret.Scale * new Vector3(1, 1, -1);
}
mat.Right = right;
mat.Up = up;
mat.Backward = backward;
ret.Ori = Quaternion.CreateFromRotationMatrix(mat);
}
ret.ToMatrix(out mat);
for (int i = 0; i != 16; ++i)
{
// Make sure that the matrix that comes out of the keyframe is a good decomposition
// of the original matrix.
if(Math.Abs(MatrixElement(ref mat, i) - MatrixElement(ref xform, i)) > 0.02f)
{
Console.WriteLine("Matrix could not be properly decomposed into TRS keyframe.");
}
}
#else
ret.transform_ = xform;
#endif
return ret;
}
// Given a matrix and an index, return the n-th value in that
// matrix, assuming row-major ordering of a matrix assuming
// row vertices on the left (so translation lives in 12, 13, 14).
public static float MatrixElement(ref Matrix mat, int ix)
{
switch (ix)
{
case 0: return mat.M11;
case 1: return mat.M12;
case 2: return mat.M13;
case 3: return mat.M14;
case 4: return mat.M21;
case 5: return mat.M22;
case 6: return mat.M23;
case 7: return mat.M24;
case 8: return mat.M31;
case 9: return mat.M32;
case 10: return mat.M33;
case 11: return mat.M34;
case 12: return mat.M41;
case 13: return mat.M42;
case 14: return mat.M43;
case 15: return mat.M44;
default:
throw new System.ArgumentException(String.Format("Index must be 0-15. Is {0}.", ix), "ix");
}
}
}
// read from disk
public class KeyframeReader : ContentTypeReader<Keyframe>
{
public KeyframeReader()
{
}
protected override Keyframe Read(ContentReader input, Keyframe existingInstance)
{
if (existingInstance == null)
existingInstance = new Keyframe();
#if !MATRIXFRAMES
Vector3 pos = input.ReadVector3();
Quaternion ori = input.ReadQuaternion();
Vector3 scale = input.ReadVector3();
existingInstance.Load(pos, ori, scale);
#else
existingInstance.Transform = input.ReadMatrix();
#endif
return existingInstance;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Buffers.Text
{
public static partial class Utf16Formatter
{
#region Constants
private const char Seperator = ',';
// Invariant formatting uses groups of 3 for each number group seperated by commas.
// ex. 1,234,567,890
private const int GroupSize = 3;
#endregion Constants
private static bool TryFormatDecimalInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int charsNeeded = digitCount + (int)((value >> 63) & 1);
Span<char> span = buffer.NonPortableCast<byte, char>();
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref span.DangerousGetPinnableReference();
int idx = 0;
if (value < 0)
{
Unsafe.Add(ref utf16Bytes, idx++) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (value == long.MinValue)
{
if (!TryFormatDecimalUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten))
return false;
bytesWritten += sizeof(char); // Add the minus sign
return true;
}
value = -value;
}
if (precision != ParsedFormat.NoPrecision)
{
int leadingZeros = (int)precision - digitCount;
while (leadingZeros-- > 0)
Unsafe.Add(ref utf16Bytes, idx++) = '0';
}
idx += FormattingHelpers.WriteDigits(value, digitCount, ref utf16Bytes, idx);
bytesWritten = idx * sizeof(char);
return true;
}
private static bool TryFormatDecimalUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten);
// Remove a single digit from the number. This will get it below long.MaxValue
// Then we call the faster long version and follow-up with writing the last
// digit. This ends up being faster by a factor of 2 than to just do the entire
// operation using the unsigned versions.
value = FormattingHelpers.DivMod(value, 10, out ulong lastDigit);
if (precision != ParsedFormat.NoPrecision && precision > 0)
precision -= 1;
if (!TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten))
return false;
Span<char> span = buffer.Slice(bytesWritten).NonPortableCast<byte, char>();
if (span.Length < sizeof(char))
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref span.DangerousGetPinnableReference();
FormattingHelpers.WriteDigits(lastDigit, 1, ref utf16Bytes, 0);
bytesWritten += sizeof(char);
return true;
}
private static bool TryFormatNumericInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int groupSeperators = (int)FormattingHelpers.DivMod(digitCount, GroupSize, out long firstGroup);
if (firstGroup == 0)
{
firstGroup = 3;
groupSeperators--;
}
int trailingZeros = (precision == ParsedFormat.NoPrecision) ? 2 : precision;
int charsNeeded = (int)((value >> 63) & 1) + digitCount + groupSeperators;
int idx = charsNeeded;
if (trailingZeros > 0)
charsNeeded += trailingZeros + 1; // +1 for period.
Span<char> span = buffer.NonPortableCast<byte, char>();
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref span.DangerousGetPinnableReference();
long v = value;
if (v < 0)
{
Unsafe.Add(ref utf16Bytes, 0) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (v == long.MinValue)
{
if (!TryFormatNumericUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten))
return false;
bytesWritten += sizeof(char); // Add the minus sign
return true;
}
v = -v;
}
// Write out the trailing zeros
if (trailingZeros > 0)
{
Unsafe.Add(ref utf16Bytes, idx) = Period;
FormattingHelpers.WriteDigits(0, trailingZeros, ref utf16Bytes, idx + 1);
}
// Starting from the back, write each group of digits except the first group
while (digitCount > 3)
{
idx -= 3;
v = FormattingHelpers.DivMod(v, 1000, out long groupValue);
FormattingHelpers.WriteDigits(groupValue, 3, ref utf16Bytes, idx);
Unsafe.Add(ref utf16Bytes, --idx) = Seperator;
digitCount -= 3;
}
// Write the first group of digits.
FormattingHelpers.WriteDigits(v, (int)firstGroup, ref utf16Bytes, idx - (int)firstGroup);
bytesWritten = charsNeeded * sizeof(char);
return true;
}
private static bool TryFormatNumericUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatNumericInt64((long)value, precision, buffer, out bytesWritten);
// The ulong path is much slower than the long path here, so we are doing the last group
// inside this method plus the zero padding but routing to the long version for the rest.
value = FormattingHelpers.DivMod(value, 1000, out ulong lastGroup);
if (!TryFormatNumericInt64((long)value, 0, buffer, out bytesWritten))
return false;
if (precision == ParsedFormat.NoPrecision)
precision = 2;
// Since this method routes entirely to the long version if the number is smaller than
// long.MaxValue, we are guaranteed to need to write 3 more digits here before the set
// of trailing zeros.
int extraChars = 4; // 3 digits + group seperator
if (precision > 0)
extraChars += precision + 1; // +1 for period.
Span<char> span = buffer.Slice(bytesWritten).NonPortableCast<byte, char>();
if (span.Length < extraChars)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref span.DangerousGetPinnableReference();
var idx = 0;
// Write the last group
Unsafe.Add(ref utf16Bytes, idx++) = Seperator;
idx += FormattingHelpers.WriteDigits(lastGroup, 3, ref utf16Bytes, idx);
// Write out the trailing zeros
if (precision > 0)
{
Unsafe.Add(ref utf16Bytes, idx++) = Period;
idx += FormattingHelpers.WriteDigits(0, precision, ref utf16Bytes, idx);
}
bytesWritten += extraChars * sizeof(char);
return true;
}
private static bool TryFormatHexUInt64(ulong value, byte precision, bool useLower, Span<byte> buffer, out int bytesWritten)
{
const string HexTableLower = "0123456789abcdef";
const string HexTableUpper = "0123456789ABCDEF";
var digits = 1;
var v = value;
if (v > 0xFFFFFFFF)
{
digits += 8;
v >>= 0x20;
}
if (v > 0xFFFF)
{
digits += 4;
v >>= 0x10;
}
if (v > 0xFF)
{
digits += 2;
v >>= 0x8;
}
if (v > 0xF) digits++;
int paddingCount = (precision == ParsedFormat.NoPrecision) ? 0 : precision - digits;
if (paddingCount < 0) paddingCount = 0;
int charsNeeded = digits + paddingCount;
Span<char> span = buffer.NonPortableCast<byte, char>();
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
string hexTable = useLower ? HexTableLower : HexTableUpper;
ref char utf16Bytes = ref span.DangerousGetPinnableReference();
int idx = charsNeeded;
for (v = value; digits-- > 0; v >>= 4)
Unsafe.Add(ref utf16Bytes, --idx) = hexTable[(int)(v & 0xF)];
while (paddingCount-- > 0)
Unsafe.Add(ref utf16Bytes, --idx) = '0';
bytesWritten = charsNeeded * sizeof(char);
return true;
}
}
}
| |
/*
Copyright 2012 Michael Edwards
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using NUnit.Framework;
using Glass.Mapper.Sc.DataMappers;
using Sitecore.Data;
using Sitecore.Data.Managers;
using Sitecore.Globalization;
using Sitecore.SecurityModel;
namespace Glass.Mapper.Sc.Integration.DataMappers
{
[TestFixture]
public class SitecoreInfoMapperFixture
{
private Database _db;
[SetUp]
public void Setup()
{
_db = Sitecore.Configuration.Factory.GetDatabase("master");
}
#region Method - MapToProperty
[Test]
[Sequential]
public void MapToProperty_SitecoreInfoType_GetsExpectedValueFromSitecore(
[Values(
SitecoreInfoType.ContentPath,
SitecoreInfoType.DisplayName,
SitecoreInfoType.FullPath,
SitecoreInfoType.Key,
SitecoreInfoType.MediaUrl,
SitecoreInfoType.Name,
SitecoreInfoType.Path,
SitecoreInfoType.TemplateName,
SitecoreInfoType.Url,
SitecoreInfoType.Version
)] SitecoreInfoType type,
[Values(
"/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem", //content path
"DataMappersEmptyItem DisplayName", //DisplayName
"/sitecore/content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem", //FullPath
"datamappersemptyitem", //Key
"/~/media/031501A9C7F24596BD659276DA3A627A.ashx", //MediaUrl
"DataMappersEmptyItem", //Name
"/sitecore/content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem", //Path
"DataMappersEmptyItem", //TemplateName
"/en/sitecore/content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem.aspx", //Url
1 //version
)] object expected
)
{
//Assign
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null,config));
Sitecore.Context.Site = null;
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
[TestCase(SitecoreInfoMediaUrlOptions.Default, "/~/media/031501A9C7F24596BD659276DA3A627A.ashx")]
[TestCase(SitecoreInfoMediaUrlOptions.RemoveExtension, "/~/media/031501A9C7F24596BD659276DA3A627A")]
[TestCase(SitecoreInfoMediaUrlOptions.LowercaseUrls, "/~/media/031501a9c7f24596bd659276da3a627a.ashx?as=0&dmc=0&thn=0")]
public void MapToProperty_MediaUrlWithFlag_ReturnsModifiedUrl(
SitecoreInfoMediaUrlOptions option,
string expected
)
{
//Assign
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = SitecoreInfoType.MediaUrl;
config.MediaUrlOptions = option;
mapper.Setup(new DataMapperResolverArgs(null, config));
Sitecore.Context.Site = null;
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
[ExpectedException(typeof (MapperException))]
public void MapToProperty_SitecoreInfoTypeNotSet_ThrowsException()
{
//Assign
SitecoreInfoType type = SitecoreInfoType.NotSet;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null,config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
//No asserts expect exception
}
[Test]
public void MapToProperty_SitecoreInfoTypeLanguage_ReturnsEnStringType()
{
//Assign
var type = SitecoreInfoType.Language;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
config.PropertyInfo = new FakePropertyInfo(typeof(string), "StringField", typeof(Stub));
mapper.Setup(new DataMapperResolverArgs(null, config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
var expected = item.Language.Name;
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_SitecoreInfoTypeItemuri_ReturnsFullItemUri()
{
//Assign
var type = SitecoreInfoType.ItemUri;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
config.PropertyInfo = new FakePropertyInfo(typeof(string), "StringField", typeof(Stub));
mapper.Setup(new DataMapperResolverArgs(null, config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
var expected = item.Language.Name;
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext) as ItemUri;
//Assert
Assert.AreEqual(item.ID, value.ItemID);
Assert.AreEqual(item.Language, value.Language);
Assert.AreEqual(item.Database.Name, value.DatabaseName);
Assert.AreEqual(item.Version, value.Version);
}
[Test]
public void MapToProperty_SitecoreInfoTypeLanguage_ReturnsEnLanguageType()
{
//Assign
var type = SitecoreInfoType.Language;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null,config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
var expected = item.Language;
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_SitecoreInfoTypeTemplateId_ReturnsTemplateIdAsGuid()
{
//Assign
var type = SitecoreInfoType.TemplateId;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null,config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
var expected = item.TemplateID.Guid;
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_SitecoreInfoTypeTemplateId_ReturnsTemplateIdAsID()
{
//Assign
var type = SitecoreInfoType.TemplateId;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
config.PropertyInfo = typeof (Stub).GetProperty("TemplateId");
mapper.Setup(new DataMapperResolverArgs(null,config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
var expected = item.TemplateID;
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
var value = mapper.MapToProperty(dataContext);
//Assert
Assert.AreEqual(expected, value);
}
[Test]
public void MapToProperty_SitecoreInfoTypeBaseTemplateIds_ReturnsBaseTemplateIds()
{
//Assign
var type = SitecoreInfoType.BaseTemplateIds;
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
config.PropertyInfo = typeof(Stub).GetProperty("BaseTemplateIds");
mapper.Setup(new DataMapperResolverArgs(null, config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
//Act
IEnumerable<ID> results;
using (new SecurityDisabler())
{
results = mapper.MapToProperty(dataContext) as IEnumerable<ID>;
}
//Assert
Assert.Greater( results.Count(), 10);
Assert.IsTrue(results.All(x=>x!= item.TemplateID));
}
#endregion
#region Method - MapToCms
[Test]
public void MapToCms_SavingDisplayName_UpdatesTheDisplayNameField()
{
//Assign
var type = SitecoreInfoType.DisplayName;
var expected = "new display name";
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null,config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
dataContext.PropertyValue = expected;
string actual = string.Empty;
//Act
using (new SecurityDisabler())
{
item.Editing.BeginEdit();
mapper.MapToCms(dataContext);
actual = item[Global.Fields.DisplayName];
item.Editing.CancelEdit();
}
//Assert
Assert.AreEqual(expected, actual);
}
[Test]
public void MapToCms_SavingName_UpdatesTheItemName()
{
//Assign
var type = SitecoreInfoType.Name;
var expected = "new name";
var mapper = new SitecoreInfoMapper();
var config = new SitecoreInfoConfiguration();
config.Type = type;
mapper.Setup(new DataMapperResolverArgs(null,config));
var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
var dataContext = new SitecoreDataMappingContext(null, item, null);
dataContext.PropertyValue = expected;
string actual = string.Empty;
//Act
using (new SecurityDisabler())
{
item.Editing.BeginEdit();
mapper.MapToCms(dataContext);
actual = item.Name;
item.Editing.CancelEdit();
}
//Assert
Assert.AreEqual(expected, actual);
}
#endregion
#region Stubs
public class Stub
{
public ID TemplateId { get; set; }
public IEnumerable<ID> BaseTemplateIds { get; set; }
public string StringField { get; set; }
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RabbitResourceHolder.cs" company="The original author or authors.">
// Copyright 2002-2012 the original author or 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#region Using Directives
using System;
using System.Collections.Generic;
using Common.Logging;
using RabbitMQ.Client;
using Spring.Messaging.Amqp.Rabbit.Support;
using Spring.Util;
#endregion
namespace Spring.Messaging.Amqp.Rabbit.Connection
{
/// <summary>
/// A rabbit resource holder.
/// </summary>
/// <author>Mark Pollack</author>
/// <author>Joe Fitzgerald (.NET)</author>
public class RabbitResourceHolder : RabbitResourceHolderSupport
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILog Logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// The frozen flag.
/// </summary>
private bool frozen = false;
/// <summary>
/// The connections.
/// </summary>
private readonly LinkedList<IConnection> connections = new LinkedList<IConnection>();
/// <summary>
/// The channels.
/// </summary>
private readonly LinkedList<IModel> channels = new LinkedList<IModel>();
/// <summary>
/// The channels per connection.
/// </summary>
private readonly IDictionary<IConnection, LinkedList<IModel>> channelsPerConnection = new Dictionary<IConnection, LinkedList<IModel>>();
/// <summary>
/// The delivery tags.
/// </summary>
private readonly IDictionary<IModel, LinkedList<long>> deliveryTags = new Dictionary<IModel, LinkedList<long>>();
/// <summary>
/// The transactional flag.
/// </summary>
private bool transactional;
/// <summary>
/// Release after completion.
/// </summary>
private readonly bool releaseAfterCompletion = true;
/// <summary>
/// Initializes a new instance of the <see cref="RabbitResourceHolder"/> class.
/// </summary>
public RabbitResourceHolder() { }
/// <summary>Initializes a new instance of the <see cref="RabbitResourceHolder"/> class.</summary>
/// <param name="channel">The channel.</param>
/// <param name="releaseAfterCompletion">The release After Completion.</param>
public RabbitResourceHolder(IModel channel, bool releaseAfterCompletion) : this()
{
this.AddChannel(channel);
this.releaseAfterCompletion = releaseAfterCompletion;
}
/// <summary>
/// Gets a value indicating whether Frozen.
/// </summary>
public bool Frozen { get { return this.frozen; } }
/// <summary>Gets a value indicating whether release after completion.</summary>
public bool ReleaseAfterCompletion { get { return this.releaseAfterCompletion; } }
/// <summary>
/// Gets a value indicating whether IsChannelTransactional.
/// </summary>
public bool IsChannelTransactional { get { return this.transactional; } }
/// <summary>Add a connection.</summary>
/// <param name="connection">The connection.</param>
public void AddConnection(IConnection connection)
{
AssertUtils.IsTrue(!this.frozen, "Cannot add Connection because RabbitResourceHolder is frozen");
AssertUtils.ArgumentNotNull(connection, "Connection must not be null");
if (!this.connections.Contains(connection))
{
this.connections.AddOrUpdate(connection);
}
}
/// <summary>Add a channel.</summary>
/// <param name="channel">The channel.</param>
public void AddChannel(IModel channel) { this.AddChannel(channel, null); }
/// <summary>Add a channel.</summary>
/// <param name="channel">The channel.</param>
/// <param name="connection">The connection.</param>
public void AddChannel(IModel channel, IConnection connection)
{
AssertUtils.IsTrue(!this.frozen, "Cannot add Channel because RabbitResourceHolder is frozen");
AssertUtils.ArgumentNotNull(channel, "Channel must not be null");
if (!this.channels.Contains(channel))
{
this.channels.AddOrUpdate(channel);
if (connection != null)
{
// .NET: Moved Extra Code Into Extension Method AddListValue
this.channelsPerConnection.AddListValue(connection, channel);
}
}
}
/// <summary>Determine if the channel is in the channels.</summary>
/// <param name="channel">The channel.</param>
/// <returns>True if the channel is in channels; otherwise false.</returns>
public bool ContainsChannel(IModel channel) { return this.channels.Contains(channel); }
/// <summary>
/// Gets Connection.
/// </summary>
public IConnection Connection { get { return (this.connections != null && this.connections.Count > 0) ? this.connections.First.Value : null; } }
/// <summary>
/// Gets a connection.
/// </summary>
/// <typeparam name="T">
/// T, where T is IConnection
/// </typeparam>
/// <returns>
/// The connection.
/// </returns>
public IConnection GetConnection<T>() where T : IConnection
{
var type = typeof(T);
return (IConnection)CollectionUtils.FindValueOfType(this.connections, type);
}
/// <summary>The get connection.</summary>
/// <param name="connectionType">The connection type.</param>
/// <typeparam name="T">Type T</typeparam>
/// <returns>The Spring.Messaging.Amqp.Rabbit.Connection.IConnection.</returns>
public IConnection GetConnection<T>(Type connectionType) where T : IConnection { return (T)CollectionUtils.FindValueOfType(this.connections, connectionType); }
/// <summary>
/// Gets Channel.
/// </summary>
public IModel Channel { get { return (this.channels != null && this.channels.Count > 0) ? this.channels.First.Value : null; } }
/// <summary>
/// Commit all delivery tags.
/// </summary>
public void CommitAll()
{
try
{
foreach (var channel in this.channels)
{
if (this.deliveryTags.ContainsKey(channel))
{
foreach (var deliveryTag in this.deliveryTags[channel])
{
channel.BasicAck((ulong)deliveryTag, false);
}
}
channel.TxCommit();
}
}
catch (Exception e)
{
throw new AmqpException("Failed to commit RabbitMQ transaction", e);
}
}
/// <summary>
/// Close all channels and connections.
/// </summary>
public void CloseAll()
{
foreach (var channel in this.channels)
{
try
{
if (channel != ConnectionFactoryUtils.GetConsumerChannel())
{
channel.Close();
}
else
{
Logger.Debug(m => m("Skipping close of consumer channel: {0}", channel.ToString()));
}
}
catch (Exception ex)
{
Logger.Debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
}
foreach (var connection in this.connections)
{
RabbitUtils.CloseConnection(connection);
}
this.connections.Clear();
this.channels.Clear();
this.channelsPerConnection.Clear();
}
/// <summary>Add a delivery tag to the channel.</summary>
/// <param name="channel">The channel.</param>
/// <param name="deliveryTag">The delivery tag.</param>
public void AddDeliveryTag(IModel channel, long deliveryTag) { this.deliveryTags.AddListValue(channel, deliveryTag); }
/// <summary>
/// Rollback all.
/// </summary>
public void RollbackAll()
{
foreach (var channel in this.channels)
{
Logger.Debug(m => m("Rollingback messages to channel: {0}", channel));
RabbitUtils.RollbackIfNecessary(channel);
if (this.deliveryTags.ContainsKey(channel))
{
foreach (var deliveryTag in this.deliveryTags[channel])
{
try
{
channel.BasicReject((ulong)deliveryTag, true);
}
catch (Exception ex)
{
throw new AmqpException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.CommitIfNecessary(channel);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Json;
using System;
namespace ReactNative.Animated
{
class SpringAnimationDriver : AnimationDriver
{
/// <summary>
/// Maximum amount of time to simulate per physics iteration in seconds (4 frames at 60 FPS).
/// </summary>
private const double MaxDeltaTimeSec = 0.064;
/// <summary>
/// Fixed timestep to use in the physics solver in seconds.
/// </summary>
private const double SolverTimestepSec = 0.001;
private long _lastTime;
private bool _springStarted;
// configuration
private double _springStiffness;
private double _springDamping;
private double _springMass;
private double _initialVelocity;
private bool _overshootClampingEnabled;
// all physics simulation objects are reused in each processing pass
private PhysicsState _currentState = new PhysicsState();
private double _startValue;
private double _endValue;
// thresholds for determining when the spring is at rest
private double _restSpeedThreshold;
private double _displacementFromRestThreshold;
private double _timeAccumulator = 0;
// for controlling loop
private int _iterations;
private int _currentLoop = 0;
private double _originalValue;
public SpringAnimationDriver(int id, ValueAnimatedNode animatedValue, ICallback endCallback, JObject config)
: base(id, animatedValue, endCallback)
{
_springStiffness = config.Value<double>("stiffness");
_springDamping = config.Value<double>("damping");
_springMass = config.Value<double>("mass");
_initialVelocity = config.Value<double>("initialVelocity");
_currentState.Velocity = _initialVelocity;
_endValue = config.Value<double>("toValue");
_restSpeedThreshold = config.Value<double>("restSpeedThreshold");
_displacementFromRestThreshold = config.Value<double>("restDisplacementThreshold");
_overshootClampingEnabled = config.Value<bool>("overshootClamping");
_iterations = config.ContainsKey("iterations") ? config.Value<int>("iterations") : 1;
HasFinished = _iterations == 0;
}
public override void RunAnimationStep(TimeSpan renderingTime)
{
var frameTimeMillis = renderingTime.Ticks / 10000;
if (!_springStarted)
{
if (_currentLoop == 0)
{
_originalValue = AnimatedValue.RawValue;
_currentLoop = 1;
}
_startValue = _currentState.Position = AnimatedValue.RawValue;
_lastTime = frameTimeMillis;
_timeAccumulator = 0.0;
_springStarted = true;
}
Advance((frameTimeMillis - _lastTime) / 1000.0);
_lastTime = frameTimeMillis;
AnimatedValue.RawValue = _currentState.Position;
if (IsAtRest())
{
if (_iterations == -1 || _currentLoop < _iterations)
{
// looping animation, return to start
_springStarted = false;
AnimatedValue.RawValue = _originalValue;
_currentLoop++;
}
else
{
// animation has completed
HasFinished = IsAtRest();
}
}
}
/// <summary>
/// Gets the displacement from rest for a given physics state.
/// </summary>
/// <param name="state">The state to measure from.</param>
/// <returns>The distance displaced by.</returns>
private double GetDisplacementDistanceForState(PhysicsState state)
{
return Math.Abs(_endValue - state.Position);
}
/// <summary>
/// Check if current state is at rest.
/// </summary>
/// <returns>
/// <code>true</code> if the spring is at rest, otherwise <code>false</code>.
/// </returns>
private bool IsAtRest()
{
return Math.Abs(_currentState.Velocity) <= _restSpeedThreshold &&
(GetDisplacementDistanceForState(_currentState) <= _displacementFromRestThreshold ||
_springStiffness == 0);
}
/// <summary>
/// Check if the spring is overshooting beyond its target.
/// </summary>
/// <returns>
/// <code>true</code> if the spring is overshooting its target,
/// otherwise <code>false</code>.
/// </returns>
private bool IsOvershooting()
{
return _springStiffness > 0 &&
((_startValue < _endValue && _currentState.Position > _endValue) ||
(_startValue > _endValue && _currentState.Position < _endValue));
}
private void Advance(double realDeltaTime)
{
if (IsAtRest())
{
return;
}
// clamp the amount of realDeltaTime to avoid stuttering in the UI.
// We should be able to catch up in a subsequent advance if necessary.
var adjustedDeltaTime = realDeltaTime;
if (realDeltaTime > MaxDeltaTimeSec)
{
adjustedDeltaTime = MaxDeltaTimeSec;
}
_timeAccumulator += adjustedDeltaTime;
var c = _springDamping;
var m = _springMass;
var k = _springStiffness;
var v0 = -_initialVelocity;
var zeta = c / (2 * Math.Sqrt(k * m));
var omega0 = Math.Sqrt(k / m);
var omega1 = omega0 * Math.Sqrt(1.0 - (zeta * zeta));
var x0 = _endValue - _startValue;
double velocity;
double position;
var t = _timeAccumulator;
if (zeta < 1)
{
// Under damped
double envelope = Math.Exp(-zeta * omega0 * t);
position =
_endValue -
envelope *
((v0 + zeta * omega0 * x0) / omega1 * Math.Sin(omega1 * t) +
x0 * Math.Cos(omega1 * t));
// This looks crazy -- it's actually just the derivative of the
// oscillation function
velocity =
zeta *
omega0 *
envelope *
(Math.Sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 +
x0 * Math.Cos(omega1 * t)) -
envelope *
(Math.Cos(omega1 * t) * (v0 + zeta * omega0 * x0) -
omega1 * x0 * Math.Sin(omega1 * t));
}
else
{
// Critically damped spring
double envelope = Math.Exp(-omega0 * t);
position = _endValue - envelope * (x0 + (v0 + omega0 * x0) * t);
velocity =
envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0));
}
_currentState.Position = position;
_currentState.Velocity = velocity;
// End the spring immediately if it is overshooting and overshoot clamping is enabled.
// Also make sure that if the spring was considered within a resting threshold that it's now
// snapped to its end value.
if (IsAtRest() || (_overshootClampingEnabled && IsOvershooting()))
{
// Don't call setCurrentValue because that forces a call to onSpringUpdate
if (_springStiffness > 0)
{
_startValue = _endValue;
_currentState.Position = _endValue;
}
else
{
_endValue = _currentState.Position;
_startValue = _endValue;
}
_currentState.Velocity = 0;
}
}
struct PhysicsState
{
public double Position;
public double Velocity;
}
}
}
| |
using System;
using System.Collections.Generic;
using De.Osthus.Ambeth.Collections;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using De.Osthus.Ambeth.Xml.PostProcess;
using De.Osthus.Ambeth.Appendable;
namespace De.Osthus.Ambeth.Xml
{
public class DefaultXmlWriter : IWriter, IPostProcessWriter
{
protected readonly IAppendable appendable;
protected readonly ICyclicXmlController xmlController;
protected readonly IDictionary<Object, int> mutableToIdMap = new IdentityDictionary<Object, int>();
protected readonly IDictionary<Object, int> immutableToIdMap = new Dictionary<Object, int>();
protected int nextIdMapIndex = 1;
protected readonly IISet<Object> substitutedEntities = new IdentityHashSet<Object>();
protected readonly IDictionary<Type, ITypeInfoItem[]> typeToMemberMap = new Dictionary<Type, ITypeInfoItem[]>();
protected bool isInAttributeState = false;
protected int beautifierLevel;
protected bool beautifierIgnoreLineBreak = true;
protected int elementContentLevel = -1;
protected String beautifierLinebreak;
protected bool beautifierActive;
public IDictionary<Object, int> MutableToIdMap
{
get
{
return mutableToIdMap;
}
}
public IDictionary<Object, int> ImmutableToIdMap
{
get
{
return immutableToIdMap;
}
}
public IISet<Object> SubstitutedEntities
{
get
{
return substitutedEntities;
}
}
public DefaultXmlWriter(IAppendable appendable, ICyclicXmlController xmlController)
{
this.appendable = appendable;
this.xmlController = xmlController;
}
public void SetBeautifierActive(bool beautifierActive)
{
this.beautifierActive = beautifierActive;
}
public bool IsBeautifierActive()
{
return beautifierActive;
}
public String GetBeautifierLinebreak()
{
return beautifierLinebreak;
}
public void SetBeautifierLinebreak(String beautifierLinebreak)
{
this.beautifierLinebreak = beautifierLinebreak;
}
protected void WriteBeautifierTabs(int amount)
{
if (beautifierIgnoreLineBreak)
{
beautifierIgnoreLineBreak = false;
}
else
{
Write(beautifierLinebreak);
}
while (amount-- > 0)
{
Write('\t');
}
}
public void WriteEscapedXml(String unescapedString)
{
for (int a = 0, size = unescapedString.Length; a < size; a++)
{
char oneChar = unescapedString[a];
switch (oneChar)
{
case '&':
appendable.Append("&");
break;
case '\"':
appendable.Append(""");
break;
case '\'':
appendable.Append("'");
break;
case '<':
appendable.Append("<");
break;
case '>':
appendable.Append(">");
break;
default:
appendable.Append(oneChar);
break;
}
}
}
public void WriteAttribute(String attributeName, Object attributeValue)
{
if (attributeValue == null)
{
return;
}
WriteAttribute(attributeName, attributeValue.ToString());
}
public void WriteAttribute(String attributeName, String attributeValue)
{
if (attributeValue == null || attributeValue.Length == 0)
{
return;
}
CheckIfInAttributeState();
appendable.Append(' ').Append(attributeName).Append("=\"");
WriteEscapedXml(attributeValue);
appendable.Append('\"');
}
public void WriteEndElement()
{
CheckIfInAttributeState();
appendable.Append("/>");
isInAttributeState = false;
if (beautifierActive)
{
beautifierLevel--;
}
}
public void WriteCloseElement(String elementName)
{
if (isInAttributeState)
{
WriteEndElement();
isInAttributeState = false;
}
else
{
if (beautifierActive)
{
if (elementContentLevel == beautifierLevel)
{
WriteBeautifierTabs(beautifierLevel - 1);
}
beautifierLevel--;
elementContentLevel = beautifierLevel;
}
appendable.Append("</").Append(elementName).Append('>');
}
}
public void Write(String s)
{
appendable.Append(s);
}
public void Write(char s)
{
appendable.Append(s);
}
public void WriteOpenElement(String elementName)
{
EndTagIfInAttributeState();
if (beautifierActive)
{
WriteBeautifierTabs(beautifierLevel);
appendable.Append('<').Append(elementName).Append('>');
elementContentLevel = beautifierLevel;
beautifierLevel++;
}
else
{
appendable.Append('<').Append(elementName).Append('>');
}
}
public void WriteStartElement(String elementName)
{
EndTagIfInAttributeState();
if (beautifierActive)
{
WriteBeautifierTabs(beautifierLevel);
appendable.Append('<').Append(elementName);
elementContentLevel = beautifierLevel;
beautifierLevel++;
}
else
{
appendable.Append('<').Append(elementName);
}
isInAttributeState = true;
}
public void WriteStartElementEnd()
{
if (!isInAttributeState)
{
return;
}
CheckIfInAttributeState();
appendable.Append('>');
isInAttributeState = false;
}
public void WriteObject(Object obj)
{
xmlController.WriteObject(obj, this);
}
public void WriteEmptyElement(String elementName)
{
EndTagIfInAttributeState();
if (beautifierActive)
{
elementContentLevel = beautifierLevel - 1;
WriteBeautifierTabs(beautifierLevel);
}
appendable.Append('<').Append(elementName).Append("/>");
}
public int AcquireIdForObject(Object obj)
{
bool isImmutableType = ImmutableTypeSet.IsImmutableType(obj.GetType());
IDictionary<Object, int> objectToIdMap = isImmutableType ? immutableToIdMap : mutableToIdMap;
if (objectToIdMap.ContainsKey(obj))
{
throw new Exception("There is already a id mapped given object (" + obj + ")");
}
int id = nextIdMapIndex++;
objectToIdMap.Add(obj, id);
return id;
}
public int GetIdOfObject(Object obj)
{
bool isImmutableType = ImmutableTypeSet.IsImmutableType(obj.GetType());
IDictionary<Object, int> objectToIdMap = isImmutableType ? immutableToIdMap : mutableToIdMap;
return DictionaryExtension.ValueOrDefault(objectToIdMap, obj);
}
public void PutMembersOfType(Type type, ITypeInfoItem[] members)
{
typeToMemberMap.Add(type, members);
}
public ITypeInfoItem[] GetMembersOfType(Type type)
{
return DictionaryExtension.ValueOrDefault(typeToMemberMap, type);
}
public bool IsInAttributeState()
{
return isInAttributeState;
}
protected void CheckIfInAttributeState()
{
if (!IsInAttributeState())
{
throw new Exception("There is currently no pending open tag to attribute");
}
}
protected void EndTagIfInAttributeState()
{
if (IsInAttributeState())
{
WriteStartElementEnd();
}
}
public void AddSubstitutedEntity(Object entity)
{
substitutedEntities.Add(entity);
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
{
private partial class State
{
public SemanticDocument Document { get; }
public TExpressionSyntax Expression { get; private set; }
public bool InAttributeContext { get; private set; }
public bool InBlockContext { get; private set; }
public bool InConstructorInitializerContext { get; private set; }
public bool InFieldContext { get; private set; }
public bool InParameterContext { get; private set; }
public bool InQueryContext { get; private set; }
public bool InExpressionBodiedMemberContext { get; private set; }
public bool InAutoPropertyInitializerContext { get; private set; }
public bool IsConstant { get; private set; }
private SemanticMap _semanticMap;
private readonly TService _service;
public State(TService service, SemanticDocument document)
{
_service = service;
this.Document = document;
}
public static State Generate(
TService service,
SemanticDocument document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
var state = new State(service, document);
if (!state.TryInitialize(textSpan, cancellationToken))
{
return null;
}
return state;
}
private bool TryInitialize(
TextSpan textSpan,
CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return false;
}
var tree = this.Document.SyntaxTree;
var syntaxFacts = this.Document.Project.LanguageServices.GetService<ISyntaxFactsService>();
this.Expression = this.GetExpressionUnderSpan(tree, textSpan, cancellationToken);
if (this.Expression == null)
{
return false;
}
var containingType = this.Expression.AncestorsAndSelf()
.Select(n => this.Document.SemanticModel.GetDeclaredSymbol(n, cancellationToken))
.OfType<INamedTypeSymbol>()
.FirstOrDefault();
containingType = containingType ?? this.Document.SemanticModel.Compilation.ScriptClass;
if (containingType == null || containingType.TypeKind == TypeKind.Interface)
{
return false;
}
if (!CanIntroduceVariable(cancellationToken))
{
return false;
}
this.IsConstant = this.Document.SemanticModel.GetConstantValue(this.Expression, cancellationToken).HasValue;
// Note: the ordering of these clauses are important. They go, generally, from
// innermost to outermost order.
if (IsInQueryContext(cancellationToken))
{
if (CanGenerateInto<TQueryExpressionSyntax>(cancellationToken))
{
this.InQueryContext = true;
return true;
}
return false;
}
if (IsInConstructorInitializerContext(cancellationToken))
{
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
this.InConstructorInitializerContext = true;
return true;
}
return false;
}
var enclosingBlocks = _service.GetContainingExecutableBlocks(this.Expression);
if (enclosingBlocks.Any())
{
// If we're inside a block, then don't even try the other options (like field,
// constructor initializer, etc.). This is desirable behavior. If we're in a
// block in a field, then we're in a lambda, and we want to offer to generate
// a local, and not a field.
if (IsInBlockContext(cancellationToken))
{
this.InBlockContext = true;
return true;
}
return false;
}
/* NOTE: All checks from this point forward are intentionally ordered to be AFTER the check for Block Context. */
// If we are inside a block within an Expression bodied member we should generate inside the block,
// instead of rewriting a concise expression bodied member to its equivalent that has a body with a block.
if (_service.IsInExpressionBodiedMember(this.Expression))
{
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
this.InExpressionBodiedMemberContext = true;
return true;
}
return false;
}
if (_service.IsInAutoPropertyInitializer(this.Expression))
{
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
this.InAutoPropertyInitializerContext = true;
return true;
}
return false;
}
if (CanGenerateInto<TTypeDeclarationSyntax>(cancellationToken))
{
if (IsInParameterContext(cancellationToken))
{
this.InParameterContext = true;
return true;
}
else if (IsInFieldContext(cancellationToken))
{
this.InFieldContext = true;
return true;
}
else if (IsInAttributeContext(cancellationToken))
{
this.InAttributeContext = true;
return true;
}
}
return false;
}
public SemanticMap GetSemanticMap(CancellationToken cancellationToken)
{
_semanticMap = _semanticMap ?? this.Document.SemanticModel.GetSemanticMap(this.Expression, cancellationToken);
return _semanticMap;
}
private TExpressionSyntax GetExpressionUnderSpan(SyntaxTree tree, TextSpan textSpan, CancellationToken cancellationToken)
{
var root = tree.GetRoot(cancellationToken);
var startToken = root.FindToken(textSpan.Start);
var stopToken = root.FindToken(textSpan.End);
if (textSpan.End <= stopToken.SpanStart)
{
stopToken = stopToken.GetPreviousToken(includeSkipped: true);
}
if (startToken.RawKind == 0 || stopToken.RawKind == 0)
{
return null;
}
var containingExpressions1 = startToken.GetAncestors<TExpressionSyntax>().ToList();
var containingExpressions2 = stopToken.GetAncestors<TExpressionSyntax>().ToList();
var commonExpression = containingExpressions1.FirstOrDefault(containingExpressions2.Contains);
if (commonExpression == null)
{
return null;
}
if (!(textSpan.Start >= commonExpression.FullSpan.Start &&
textSpan.Start <= commonExpression.SpanStart))
{
return null;
}
if (!(textSpan.End >= commonExpression.Span.End &&
textSpan.End <= commonExpression.FullSpan.End))
{
return null;
}
return commonExpression;
}
private bool CanIntroduceVariable(
CancellationToken cancellationToken)
{
if (!_service.CanIntroduceVariableFor(this.Expression))
{
return false;
}
if (this.Expression is TTypeSyntax)
{
return false;
}
// Even though we're creating a variable, we still ask if we can be replaced with an
// RValue and not an LValue. This is because introduction of a local adds a *new* LValue
// location, and we want to ensure that any writes will still happen to the *original*
// LValue location. i.e. if you have: "a[1] = b" then you don't want to change that to
// "var c = a[1]; c = b", as that write is no longer happening into the right LValue.
//
// In essence, this says "i can be replaced with an expression as long as I'm not being
// written to".
var semanticFacts = this.Document.Project.LanguageServices.GetService<ISemanticFactsService>();
return semanticFacts.CanReplaceWithRValue(this.Document.SemanticModel, this.Expression, cancellationToken);
}
private bool CanGenerateInto<TSyntax>(CancellationToken cancellationToken)
where TSyntax : SyntaxNode
{
if (this.Document.SemanticModel.Compilation.ScriptClass != null)
{
return true;
}
var syntax = this.Expression.GetAncestor<TSyntax>();
return syntax != null && !syntax.OverlapsHiddenPosition(cancellationToken);
}
private bool IsInTypeDeclarationOrValidCompilationUnit()
{
if (this.Expression.GetAncestorOrThis<TTypeDeclarationSyntax>() != null)
{
return true;
}
// If we're interactive/script, we can generate into the compilation unit.
if (this.Document.Document.SourceCodeKind != SourceCodeKind.Regular)
{
return true;
}
return false;
}
}
}
}
| |
/*
* Copyright 2011-2012 Stefan Thoolen (http://www.netmftoolbox.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Net.Sockets;
using System.Text;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
namespace FloodSensor
{
/// <summary>
/// Generic, useful tools
/// </summary>
public static class Tools
{
/// <summary>
/// Returns the name of the hardware provider
/// </summary>
public static string HardwareProvider
{ get {
if (Tools._HardwareProvider == "")
{
string[] HP = Microsoft.SPOT.Hardware.HardwareProvider.HwProvider.ToString().Split(new char[] { '.' });
Tools._HardwareProvider = HP[HP.Length - 2];
}
return Tools._HardwareProvider;
} }
/// <summary>Contains the name of the hardware provider</summary>
private static string _HardwareProvider = "";
/// <summary>Escapes all non-visible characters</summary>
/// <param name="Input">Input text</param>
/// <returns>Output text</returns>
public static string Escape(string Input)
{
if (Input == null) return "";
char[] Buffer = Input.ToCharArray();
string RetValue = "";
for (int i = 0; i < Buffer.Length; ++i)
{
if (Buffer[i] == 13)
RetValue += "\\r";
else if (Buffer[i] == 10)
RetValue += "\\n";
else if (Buffer[i] == 92)
RetValue += "\\\\";
else if (Buffer[i] < 32 || Buffer[i] > 126)
RetValue += "\\" + Tools.Dec2Hex((int)Buffer[i], 2);
else
RetValue += Buffer[i];
}
return RetValue;
}
/// <summary>
/// Converts a Hex string to a number
/// </summary>
/// <param name="HexNumber">The Hex string (ex.: "0F")</param>
/// <returns>The decimal value</returns>
public static uint Hex2Dec(string HexNumber)
{
// Always in upper case
HexNumber = HexNumber.ToUpper();
// Contains all Hex posibilities
string ConversionTable = "0123456789ABCDEF";
// Will contain the return value
uint RetVal = 0;
// Will increase
uint Multiplier = 1;
for (int Index = HexNumber.Length - 1; Index >= 0; --Index)
{
RetVal += (uint)(Multiplier * (ConversionTable.IndexOf(HexNumber[Index])));
Multiplier = (uint)(Multiplier * ConversionTable.Length);
}
return RetVal;
}
/// <summary>
/// Converts a byte array to a char array
/// </summary>
/// <param name="Input">The byte array</param>
/// <returns>The char array</returns>
public static char[] Bytes2Chars(byte[] Input)
{
char[] Output = new char[Input.Length];
for (int Counter = 0; Counter < Input.Length; ++Counter)
{
Output[Counter] = (char)Input[Counter];
}
return Output;
}
/// <summary>
/// Converts a char array to a byte array
/// </summary>
/// <param name="Input">The char array</param>
/// <returns>The byte array</returns>
public static byte[] Chars2Bytes(char[] Input)
{
byte[] Output = new byte[Input.Length];
for (int Counter = 0; Counter < Input.Length; ++Counter)
{
Output[Counter] = (byte)Input[Counter];
}
return Output;
}
/// <summary>
/// Changes a number into a string and add zeros in front of it, if required
/// </summary>
/// <param name="Number">The input number</param>
/// <param name="Digits">The amount of digits it should be</param>
/// <param name="Character">The character to repeat in front (default: 0)</param>
/// <returns>A string with the right amount of digits</returns>
public static string ZeroFill(string Number, int Digits, char Character = '0')
{
bool Negative = false;
if (Number.Substring(0, 1) == "-")
{
Negative = true;
Number = Number.Substring(1);
}
for (int Counter = Number.Length; Counter < Digits; ++Counter)
{
Number = Character + Number;
}
if (Negative) Number = "-" + Number;
{
return Number;
}
}
/// <summary>
/// Changes a number into a string and add zeros in front of it, if required
/// </summary>
/// <param name="Number">The input number</param>
/// <param name="MinLength">The amount of digits it should be</param>
/// <param name="Character">The character to repeat in front (default: 0)</param>
/// <returns>A string with the right amount of digits</returns>
public static string ZeroFill(int Number, int MinLength, char Character = '0')
{
return ZeroFill(Number.ToString(), MinLength, Character);
// In 4.2 it should be possible to replace this with the following line,
// but due to a bug (http://netmf.codeplex.com/workitem/1322) it isn't.
// return Number.toString("d" + MinLength.toString());
}
/// <summary>
/// URL-encode according to RFC 3986
/// </summary>
/// <param name="Input">The URL to be encoded.</param>
/// <returns>Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits.</returns>
public static string RawUrlEncode(string Input)
{
string RetValue = "";
for (int Counter = 0; Counter < Input.Length; ++Counter)
{
byte CharCode = (byte)(Input.ToCharArray()[Counter]);
if (
CharCode == 0x2d // -
|| CharCode == 0x5f // _
|| CharCode == 0x2e // .
|| CharCode == 0x7e // ~
|| (CharCode > 0x2f && CharCode < 0x3a) // 0-9
|| (CharCode > 0x40 && CharCode < 0x5b) // A-Z
|| (CharCode > 0x60 && CharCode < 0x7b) // a-z
)
{
RetValue += Input.Substring(Counter, 1);
}
else
{
// Calculates the hex value in some way
RetValue += "%" + Dec2Hex(CharCode, 2);
}
}
return RetValue;
}
/// <summary>
/// URL-decode according to RFC 3986
/// </summary>
/// <param name="Input">The URL to be decoded.</param>
/// <returns>Returns a string in which original characters</returns>
public static string RawUrlDecode(string Input)
{
string RetValue = "";
for (int Counter = 0; Counter < Input.Length; ++Counter)
{
string Char = Input.Substring(Counter, 1);
if (Char == "%")
{
// Encoded character
string HexValue = Input.Substring(++Counter, 2);
++Counter;
RetValue += (char)Hex2Dec(HexValue);
}
else
{
// Normal character
RetValue += Char;
}
}
return RetValue;
}
/// <summary>
/// Encodes a string according to the BASE64 standard
/// </summary>
/// <param name="Input">The input string</param>
/// <returns>The output string</returns>
public static string Base64Encode(string Input)
{
// Pairs of 3 8-bit bytes will become pairs of 4 6-bit bytes
// That's the whole trick of base64 encoding :-)
int Blocks = Input.Length / 3; // The amount of original pairs
if (Blocks * 3 < Input.Length) ++Blocks; // Fixes rounding issues; always round up
int Bytes = Blocks * 4; // The length of the base64 output
// These characters will be used to represent the 6-bit bytes in ASCII
char[] Base64_Characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".ToCharArray();
// Converts the input string to characters and creates the output array
char[] InputChars = Input.ToCharArray();
char[] OutputChars = new char[Bytes];
// Converts the blocks of bytes
for (int Block = 0; Block < Blocks; ++Block)
{
// Fetches the input pairs
byte Input0 = (byte)(InputChars.Length > Block * 3 ? InputChars[Block * 3] : 0);
byte Input1 = (byte)(InputChars.Length > Block * 3 + 1 ? InputChars[Block * 3 + 1] : 0);
byte Input2 = (byte)(InputChars.Length > Block * 3 + 2 ? InputChars[Block * 3 + 2] : 0);
// Generates the output pairs
byte Output0 = (byte)(Input0 >> 2); // The first 6 bits of the 1st byte
byte Output1 = (byte)(((Input0 & 0x3) << 4) + (Input1 >> 4)); // The last 2 bits of the 1st byte followed by the first 4 bits of the 2nd byte
byte Output2 = (byte)(((Input1 & 0xf) << 2) + (Input2 >> 6)); // The last 4 bits of the 2nd byte followed by the first 2 bits of the 3rd byte
byte Output3 = (byte)(Input2 & 0x3f); // The last 6 bits of the 3rd byte
// This prevents 0-bytes at the end
if (InputChars.Length < Block * 3 + 2) Output2 = 64;
if (InputChars.Length < Block * 3 + 3) Output3 = 64;
// Converts the output pairs to base64 characters
OutputChars[Block * 4] = Base64_Characters[Output0];
OutputChars[Block * 4 + 1] = Base64_Characters[Output1];
OutputChars[Block * 4 + 2] = Base64_Characters[Output2];
OutputChars[Block * 4 + 3] = Base64_Characters[Output3];
}
return new string(OutputChars);
}
/// <summary>
/// Converts a number to a Hex string
/// </summary>
/// <param name="Input">The number</param>
/// <param name="MinLength">The minimum length of the return string (filled with 0s)</param>
/// <returns>The Hex string</returns>
public static string Dec2Hex(int Input, int MinLength = 0)
{
#if MF_FRAMEWORK_VERSION_V4_2
// Since NETMF 4.2 int.toString() exists, so we can do this:
return Input.ToString("x" + MinLength.ToString());
#else
// Contains all Hex posibilities
string ConversionTable = "0123456789ABCDEF";
// Starts the conversion
string RetValue = "";
int Current = 0;
int Next = Input;
do
{
if (Next >= ConversionTable.Length)
{
// The current digit
Current = (Next / ConversionTable.Length);
if (Current * ConversionTable.Length > Next) --Current;
// What's left
Next = Next - (Current * ConversionTable.Length);
}
else
{
// The last digit
Current = Next;
// Nothing left
Next = -1;
}
RetValue += ConversionTable[Current];
} while (Next != -1);
return Tools.ZeroFill(RetValue, MinLength);
#endif
}
/// <summary>
/// Converts a 16-bit array to an 8 bit array
/// </summary>
/// <param name="Data">The 16-bit array</param>
/// <returns>The 8-bit array</returns>
public static byte[] UShortsToBytes(ushort[] Data)
{
byte[] RetVal = new byte[Data.Length * 2];
int BytePos = 0;
for (int ShortPos = 0; ShortPos < Data.Length; ++ShortPos)
{
RetVal[BytePos++] = (byte)(Data[ShortPos] >> 8);
RetVal[BytePos++] = (byte)(Data[ShortPos] & 0x00ff);
}
return RetVal;
}
/// <summary>
/// Converts an 8-bit array to a 16 bit array
/// </summary>
/// <param name="Data">The 8-bit array</param>
/// <returns>The 16-bit array</returns>
public static ushort[] BytesToUShorts(byte[] Data)
{
ushort[] RetVal = new ushort[Data.Length / 2];
int BytePos = 0;
for (int ShortPos = 0; ShortPos < RetVal.Length; ++ShortPos)
{
RetVal[ShortPos] = (ushort)((Data[BytePos++] << 8) + Data[BytePos++]);
}
return RetVal;
}
/// <summary>Calculates an XOR Checksum</summary>
/// <param name="Data">Input data</param>
/// <returns>XOR Checksum</returns>
public static byte XorChecksum(string Data)
{
return Tools.XorChecksum(Tools.Chars2Bytes(Data.ToCharArray()));
}
/// <summary>Calculates an XOR Checksum</summary>
/// <param name="Data">Input data</param>
/// <returns>XOR Checksum</returns>
public static byte XorChecksum(byte[] Data)
{
byte Checksum = 0;
for (int Pos = 0; Pos < Data.Length; ++Pos)
{
Checksum ^= Data[Pos];
}
return Checksum;
}
/// <summary>
/// Displays a number with a metric prefix
/// </summary>
/// <param name="Number">The number</param>
/// <param name="BinaryMultiple">If true, will use 1024 as multiplier instead of 1000</param>
/// <returns>The number with a metric prefix</returns>
/// <remarks>See also: http://en.wikipedia.org/wiki/Metric_prefix </remarks>
public static string MetricPrefix(float Number, bool BinaryMultiple = false)
{
float Multiplier = BinaryMultiple ? 1024 : 1000;
if (Number > (Multiplier * Multiplier * Multiplier * Multiplier))
return Tools.Round(Number / Multiplier / Multiplier / Multiplier / Multiplier) + "T";
if (Number > (Multiplier * Multiplier * Multiplier))
return Tools.Round(Number / Multiplier / Multiplier / Multiplier) + "G";
if (Number > (Multiplier * Multiplier))
return Tools.Round(Number / Multiplier / Multiplier) + "M";
if (Number > Multiplier)
return Tools.Round(Number / Multiplier) + "k";
else
return Tools.Round(Number).ToString();
}
/// <summary>
/// Rounds a value to a certain amount of digits
/// </summary>
/// <param name="Input">The input number</param>
/// <param name="Digits">Amount of digits after the .</param>
/// <returns>The rounded value (as float or double gave precision errors, hence the String type)</returns>
public static string Round(float Input, int Digits = 2)
{
int Multiplier = 1;
for (int i = 0; i < Digits; ++i) Multiplier *= 10;
string Rounded = ((int)(Input * Multiplier)).ToString();
return (Rounded.Substring(0, Rounded.Length - 2) + "." + Rounded.Substring(Rounded.Length - 2)).TrimEnd(new char[] { '0', '.' });
}
/// <summary>
/// Converts an integer color code to RGB
/// </summary>
/// <param name="Color">The integer color (0x000000 to 0xffffff)</param>
/// <returns>A new byte[] { Red, Green, Blue }</returns>
public static int[] ColorToRgb(int Color)
{
byte Red = (byte)((Color & 0xff0000) >> 16);
byte Green = (byte)((Color & 0xff00) >> 8);
byte Blue = (byte)(Color & 0xff);
return new int[] { Red, Green, Blue };
}
public static string BytesToHexString(byte[] messageBytes)
{
var sb = new StringBuilder();
foreach (byte b in messageBytes)
{
sb.Append(b.ToString("X2"));
}
string hexString = sb.ToString();
return hexString;
}
public static byte[] ByteReverser(byte[] array)
{
var outgoingBytes = new byte[array.Length];
int outgoingIndex = 0;
for (int origArrayIndex = array.Length-1; origArrayIndex >= 0; origArrayIndex--)
{
outgoingBytes[outgoingIndex] = array[origArrayIndex];
outgoingIndex++;
}
//Debug.Print("ByteReverser incoming bytes: " + BytesToHexString(array));
//Debug.Print("ByteReverser outgoing bytes: " + BytesToHexString(outgoingBytes));
return outgoingBytes;
}
/// <summary>
/// Extracts a sub-range of an array, and returns it in reverse order
/// </summary>
/// <param name="byteArray"></param>
/// <param name="arrayIndex"></param>
/// <param name="byteCount"></param>
/// <returns></returns>
private static byte[] ExtractAndReverse(byte[] byteArray, int arrayIndex, int byteCount)
{
var originalBytes = Utility.ExtractRangeFromArray(byteArray, arrayIndex, byteCount);
var reversedBytes = ByteReverser(originalBytes);
return reversedBytes;
}
public static Int16 ParseReversedInt16(byte[] byteArray, int arrayIndex)
{
var reversedBytes = ExtractAndReverse(byteArray, arrayIndex, 2);
return BitConverter.ToInt16(reversedBytes, 0);
}
public static Int32 ParseReversedInt32(byte[] byteArray, int arrayIndex)
{
var reversedBytes = ExtractAndReverse(byteArray, arrayIndex, 4);
return BitConverter.ToInt32(reversedBytes, 0);
}
public static UInt32 ParseReversedUInt32(byte[] byteArray, int arrayIndex)
{
var reversedBytes = ExtractAndReverse(byteArray, arrayIndex, 4);
return BitConverter.ToUInt32(reversedBytes, 0);
}
public static Int16 ReadShort(NetworkStream networkStream)
{
const int shortLength = 2;
var int16Bytes = new byte[shortLength];
networkStream.Read(int16Bytes, 0, shortLength);
// Change byte order of incoming bytes
int16Bytes = ByteReverser(int16Bytes);
return BitConverter.ToInt16(int16Bytes, 0);
}
public static Int32 ReadInt(NetworkStream networkStream)
{
const int intLength = 4;
var int32Bytes = new byte[intLength];
networkStream.Read(int32Bytes, 0, intLength);
// Change byte order of incoming bytes
int32Bytes = ByteReverser(int32Bytes);
return BitConverter.ToInt32(int32Bytes, 0);
}
public static UInt32 ReadUInt(NetworkStream networkStream)
{
const int uintLength = 4;
var uint32Bytes = new byte[uintLength];
networkStream.Read(uint32Bytes, 0, uintLength);
// Change byte order of incoming bytes
uint32Bytes = ByteReverser(uint32Bytes);
return BitConverter.ToUInt32(uint32Bytes, 0);
}
/// <summary>
/// From this fine Stack Overflow post:
/// http://stackoverflow.com/questions/321370/convert-hex-string-to-byte-array
///
/// Because as the author points out, "also works on .NET Micro Framework where (in SDK4.3) byte.Parse(string) only permits integer formats."
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static byte[] StringToByteArrayFastest(string hex)
{
if (hex.Length % 2 == 1)
{
throw new Exception("The binary key cannot have an odd number of digits");
}
var arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
public static int GetHexVal(char hex)
{
int val = (int)hex;
//For uppercase A-F letters:
return val - (val < 58 ? 48 : 55);
//For lowercase a-f letters:
//return val - (val < 58 ? 48 : 87);
//Or the two combined, but a bit slower:
//return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Talent.V4.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCompanyServiceClientTest
{
[xunit::FactAttribute]
public void CreateCompanyRequestObject()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.CreateCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.CreateCompany(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCompanyRequestObjectAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.CreateCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.CreateCompanyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.CreateCompanyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateCompany()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.CreateCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.CreateCompany(request.Parent, request.Company);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCompanyAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.CreateCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.CreateCompanyAsync(request.Parent, request.Company, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.CreateCompanyAsync(request.Parent, request.Company, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateCompanyResourceNames()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.CreateCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.CreateCompany(request.ParentAsTenantName, request.Company);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateCompanyResourceNamesAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
CreateCompanyRequest request = new CreateCompanyRequest
{
ParentAsTenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"),
Company = new Company(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.CreateCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.CreateCompanyAsync(request.ParentAsTenantName, request.Company, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.CreateCompanyAsync(request.ParentAsTenantName, request.Company, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCompanyRequestObject()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.GetCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.GetCompany(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCompanyRequestObjectAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.GetCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.GetCompanyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.GetCompanyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCompany()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.GetCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.GetCompany(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCompanyAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.GetCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.GetCompanyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.GetCompanyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetCompanyResourceNames()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.GetCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.GetCompany(request.CompanyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetCompanyResourceNamesAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.GetCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.GetCompanyAsync(request.CompanyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.GetCompanyAsync(request.CompanyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateCompanyRequestObject()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
UpdateCompanyRequest request = new UpdateCompanyRequest
{
Company = new Company(),
UpdateMask = new wkt::FieldMask(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.UpdateCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.UpdateCompany(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateCompanyRequestObjectAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
UpdateCompanyRequest request = new UpdateCompanyRequest
{
Company = new Company(),
UpdateMask = new wkt::FieldMask(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.UpdateCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.UpdateCompanyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.UpdateCompanyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateCompany()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
UpdateCompanyRequest request = new UpdateCompanyRequest
{
Company = new Company(),
UpdateMask = new wkt::FieldMask(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.UpdateCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company response = client.UpdateCompany(request.Company, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateCompanyAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
UpdateCompanyRequest request = new UpdateCompanyRequest
{
Company = new Company(),
UpdateMask = new wkt::FieldMask(),
};
Company expectedResponse = new Company
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
DisplayName = "display_name137f65c2",
ExternalId = "external_id9442680e",
Size = CompanySize.Mini,
HeadquartersAddress = "headquarters_address64cd7eb7",
HiringAgency = true,
EeoText = "eeo_text70a1a576",
WebsiteUri = "website_urid0c5dfce",
CareerSiteUri = "career_site_uri62d45b74",
ImageUri = "image_urieba3b1bc",
KeywordSearchableJobCustomAttributes =
{
"keyword_searchable_job_custom_attributese72ec77c",
},
DerivedInfo = new Company.Types.DerivedInfo(),
Suspended = true,
};
mockGrpcClient.Setup(x => x.UpdateCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Company>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
Company responseCallSettings = await client.UpdateCompanyAsync(request.Company, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Company responseCancellationToken = await client.UpdateCompanyAsync(request.Company, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteCompanyRequestObject()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteCompany(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteCompanyRequestObjectAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteCompanyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteCompanyAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteCompany()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteCompany(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteCompanyAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteCompanyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteCompanyAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteCompanyResourceNames()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCompany(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteCompany(request.CompanyName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteCompanyResourceNamesAsync()
{
moq::Mock<CompanyService.CompanyServiceClient> mockGrpcClient = new moq::Mock<CompanyService.CompanyServiceClient>(moq::MockBehavior.Strict);
DeleteCompanyRequest request = new DeleteCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteCompanyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CompanyServiceClient client = new CompanyServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteCompanyAsync(request.CompanyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteCompanyAsync(request.CompanyName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
{
private enum Operation
{
Add,
Set,
Remove,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedDictionary<int, bool>();
var actual = ImmutableSortedDictionary<int, bool>.Empty;
int seed = (int)DateTime.Now.Ticks;
Console.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int key;
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
bool value = random.Next() % 2 == 0;
Console.WriteLine("Adding \"{0}\"={1} to the set.", key, value);
expected.Add(key, value);
actual = actual.Add(key, value);
break;
case Operation.Set:
bool overwrite = expected.Count > 0 && random.Next() % 2 == 0;
if (overwrite)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
}
else
{
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
}
value = random.Next() % 2 == 0;
Console.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite);
expected[key] = value;
actual = actual.SetItem(key, value);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
Console.WriteLine("Removing element \"{0}\" from the set.", key);
Assert.True(expected.Remove(key));
actual = actual.Remove(key);
}
break;
}
Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void ToUnorderedTest()
{
var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n))));
var unsortedMap = sortedMap.ToImmutableDictionary();
Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap);
Assert.Equal(sortedMap.Count, unsortedMap.Count);
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList());
}
[Fact]
public void SortChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void InitialBulkAddUniqueTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("c", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(2, actual.Count);
}
[Fact]
public void InitialBulkAddWithExactDuplicatesTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "b"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(1, actual.Count);
}
[Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void InitialBulkAddWithKeyCollisionTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
Assert.Throws<ArgumentException>(() => map.AddRange(uniqueEntries));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
var dictionary = ImmutableSortedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void ToImmutableSortedDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void WithComparers()
{
var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(Comparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
var cultureComparer = StringComparer.CurrentCulture;
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(cultureComparer, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(() => map.WithComparers(StringComparer.OrdinalIgnoreCase));
// Force all values to be considered equal.
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(EverythingEqual<string>.Default, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersEmptyCollection()
{
var map = ImmutableSortedDictionary.Create<string, string>();
Assert.Same(Comparer<string>.Default, map.KeyComparer);
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance()
{
var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k);
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
File.AppendAllText(Environment.ExpandEnvironmentVariables(@"%TEMP%\timing.txt"), string.Join(Environment.NewLine, timing));
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance_Empty()
{
var dictionary = ImmutableSortedDictionary<int, int>.Empty;
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
File.AppendAllText(Environment.ExpandEnvironmentVariables(@"%TEMP%\timing_empty.txt"), string.Join(Environment.NewLine, timing));
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSortedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer;
}
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// 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 System;
using System.Globalization;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.Azure.Commands.Common.Authentication;
namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet
{
/// <summary>
/// Update settings for an existing Microsoft Azure SQL Database in the given server context.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureSqlDatabase", SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.High)]
public class RemoveAzureSqlDatabase : AzureSMCmdlet
{
#region Parameter sets
/// <summary>
/// The name of the parameter set for removing a database by name with a connection context
/// </summary>
internal const string ByNameWithConnectionContext =
"ByNameWithConnectionContext";
/// <summary>
/// The name of the parameter set for removing a database by name using azure subscription
/// </summary>
internal const string ByNameWithServerName =
"ByNameWithServerName";
/// <summary>
/// The name of the parameter set for removing a database by input
/// object with a connection context
/// </summary>
internal const string ByObjectWithConnectionContext =
"ByObjectWithConnectionContext";
/// <summary>
/// The name of the parameter set for removing a database by input
/// object using azure subscription
/// </summary>
internal const string ByObjectWithServerName =
"ByObjectWithServerName";
#endregion
#region Parameters
/// <summary>
/// Gets or sets the server connection context.
/// </summary>
[Alias("Context")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByNameWithConnectionContext,
HelpMessage = "The connection context to the specified server.")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByObjectWithConnectionContext,
HelpMessage = "The connection context to the specified server.")]
[ValidateNotNull]
public IServerDataServiceContext ConnectionContext { get; set; }
/// <summary>
/// Gets or sets the name of the server to connect to
/// </summary>
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByNameWithServerName,
HelpMessage = "The name of the server to connect to")]
[Parameter(Mandatory = true, Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ByObjectWithServerName,
HelpMessage = "The name of the server to connect to")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
[Alias("InputObject")]
[Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true,
ParameterSetName = ByObjectWithConnectionContext,
HelpMessage = "The database object you want to remove")]
[Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true,
ParameterSetName = ByObjectWithServerName,
HelpMessage = "The database object you want to remove")]
[ValidateNotNull]
public Services.Server.Database Database { get; set; }
/// <summary>
/// Gets or sets the database name.
/// </summary>
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByNameWithConnectionContext,
HelpMessage = "The name of the database to remove")]
[Parameter(Mandatory = true, Position = 1,
ParameterSetName = ByNameWithServerName,
HelpMessage = "The name of the database to remove")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the switch to not confirm on the removal of the database.
/// </summary>
[Parameter(HelpMessage = "Do not confirm on the removal of the database")]
public SwitchParameter Force { get; set; }
#endregion
/// <summary>
/// Process the command.
/// </summary>
public override void ExecuteCmdlet()
{
// Obtain the database name from the given parameters.
string databaseName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
{
databaseName = this.Database.Name;
}
else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
{
databaseName = this.DatabaseName;
}
// Determine the name of the server we are connecting to
string serverName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("ServerName"))
{
serverName = this.ServerName;
}
else
{
serverName = this.ConnectionContext.ServerName;
}
string actionDescription = string.Format(
CultureInfo.InvariantCulture,
Resources.RemoveAzureSqlDatabaseDescription,
serverName,
databaseName);
string actionWarning = string.Format(
CultureInfo.InvariantCulture,
Resources.RemoveAzureSqlDatabaseWarning,
serverName,
databaseName);
this.WriteVerbose(actionDescription);
// Do nothing if force is not specified and user cancelled the operation
if (!this.Force.IsPresent &&
!this.ShouldProcess(
actionDescription,
actionWarning,
Resources.ShouldProcessCaption))
{
return;
}
switch (this.ParameterSetName)
{
case ByNameWithConnectionContext:
case ByObjectWithConnectionContext:
this.ProcessWithConnectionContext(databaseName);
break;
case ByNameWithServerName:
case ByObjectWithServerName:
this.ProcessWithServerName(databaseName);
break;
}
}
/// <summary>
/// Process the request using a temporary connection context.
/// </summary>
/// <param name="databaseName">The name of the database to remove</param>
private void ProcessWithServerName(string databaseName)
{
Func<string> GetClientRequestId = () => string.Empty;
try
{
// Get the current subscription data.
AzureSubscription subscription = Profile.Context.Subscription;
// Create a temporary context
ServerDataServiceCertAuth context =
ServerDataServiceCertAuth.Create(this.ServerName, Profile, subscription);
GetClientRequestId = () => context.ClientRequestId;
// Remove the database with the specified name
context.RemoveDatabase(databaseName);
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
GetClientRequestId(),
ex);
}
}
/// <summary>
/// Process the request with the connection context
/// </summary>
/// <param name="databaseName">The name of the database to remove</param>
private void ProcessWithConnectionContext(string databaseName)
{
try
{
// Remove the database with the specified name
this.ConnectionContext.RemoveDatabase(databaseName);
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
this.ConnectionContext.ClientRequestId,
ex);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E07Level1111Child (editable child object).<br/>
/// This is a generated base class of <see cref="E07Level1111Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E06Level111"/> collection.
/// </remarks>
[Serializable]
public partial class E07Level1111Child : BusinessBase<E07Level1111Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int cLarentID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_Child_Name, "Level_1_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E07Level1111Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E07Level1111Child"/> object.</returns>
internal static E07Level1111Child NewE07Level1111Child()
{
return DataPortal.CreateChild<E07Level1111Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="E07Level1111Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E07Level1111Child"/> object.</returns>
internal static E07Level1111Child GetE07Level1111Child(SafeDataReader dr)
{
E07Level1111Child obj = new E07Level1111Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E07Level1111Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private E07Level1111Child()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E07Level1111Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E07Level1111Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_Child_Name"));
cLarentID1 = dr.GetInt32("CLarentID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E07Level1111Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE07Level1111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E07Level1111Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE07Level1111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="E07Level1111Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E06Level111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteE07Level1111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using GraphQL.DataLoader;
using GraphQL.Utilities.Federation;
using Xunit;
namespace GraphQL.Tests.Utilities
{
public class FederatedSchemaBuilderTests : FederatedSchemaBuilderTestBase
{
public class User
{
public string Id { get; set; }
public string Username { get; set; }
}
[Fact]
public void returns_sdl()
{
var definitions = @"
extend type Query {
me: User
}
type User @key(fields: ""id"") {
id: ID! @external
username: String!
}
";
var query = "{ _service { sdl } }";
var sdl = @"extend type Query {
me: User
}
type User @key(fields: ""id"") {
id: ID! @external
username: String!
}
";
var expected = @"{ ""_service"": { ""sdl"" : """ + JsonEncodedText.Encode(sdl) + @""" } }";
AssertQuery(_ =>
{
_.Definitions = definitions;
_.Query = query;
_.ExpectedResult = expected;
});
}
[Fact]
public void entity_query()
{
var definitions = @"
extend type Query {
me: User
}
type User @key(fields: ""id"") {
id: ID!
username: String!
}
";
Builder.Types.For("User").ResolveReferenceAsync(ctx => Task.FromResult(new User { Id = "123", Username = "Quinn" }));
var query = @"
query ($_representations: [_Any!]!) {
_entities(representations: $_representations) {
... on User {
id
username
}
}
}";
var variables = @"{ ""_representations"": [{ ""__typename"": ""User"", ""id"": ""123"" }] }";
var expected = @"{ ""_entities"": [{ ""__typename"": ""User"", ""id"" : ""123"", ""username"": ""Quinn"" }] }";
AssertQuery(_ =>
{
_.Definitions = definitions;
_.Query = query;
_.Variables = variables;
_.ExpectedResult = expected;
});
}
[Theory]
[InlineData("...on User { id }", false)]
[InlineData("__typename ...on User { id }", false)]
[InlineData("...on User { __typename id }", false)]
[InlineData("...on User { ...TypeAndId }", true)]
public void result_includes_typename(string selectionSet, bool includeFragment)
{
var definitions = @"
extend type Query {
me: User
}
type User @key(fields: ""id"") {
id: ID!
username: String!
}
";
Builder.Types.For("User").ResolveReferenceAsync(ctx => Task.FromResult(new User { Id = "123", Username = "Quinn" }));
var query = @$"
query ($_representations: [_Any!]!) {{
_entities(representations: $_representations) {{
{selectionSet}
}}
}}";
if (includeFragment)
{
query += @"
fragment TypeAndId on User {
__typename
id
}
";
}
var variables = @"{ ""_representations"": [{ ""__typename"": ""User"", ""id"": ""123"" }] }";
var expected = @"{ ""_entities"": [{ ""__typename"": ""User"", ""id"" : ""123""}] }";
AssertQuery(_ =>
{
_.Definitions = definitions;
_.Query = query;
_.Variables = variables;
_.ExpectedResult = expected;
});
}
[Fact]
public void input_types_and_types_without_key_directive_are_not_added_to_entities_union()
{
var definitions = @"
input UserInput {
limit: Int!
offset: Int
}
type Comment {
id: ID!
}
type User @key(fields: ""id"") {
id: ID! @external
}
";
var query = "{ __schema { types { name kind possibleTypes { name } } } }";
var executionResult = Executer.ExecuteAsync(_ =>
{
_.Schema = Builder.Build(definitions);
_.Query = query;
}).GetAwaiter().GetResult();
var data = executionResult.Data.ToDict();
var schema = data["__schema"].ToDict();
var types = (IEnumerable<object>)schema["types"];
var entityType = types.Single(t => (string)t.ToDict()["name"] == "_Entity").ToDict();
var possibleTypes = (IEnumerable<object>)entityType["possibleTypes"];
var possibleType = possibleTypes.First().ToDict();
var name = (string)possibleType["name"];
Assert.Equal("User", name);
}
[Fact]
public void resolve_reference_is_not_trying_to_await_for_each_field_individialy_and_plays_well_with_dataloader_issue_1565()
{
var definitions = @"
extend type Query {
user(id: ID!): User
}
type User @key(fields: ""id"") {
id: ID!
username: String!
}
";
var users = new List<User> {
new User { Id = "1", Username = "One" },
new User { Id = "2", Username = "Two" },
};
var accessor = new DataLoaderContextAccessor
{
Context = new DataLoaderContext()
};
var listener = new DataLoaderDocumentListener(accessor);
Builder.Types.For("User").ResolveReferenceAsync(ctx =>
{
var id = ctx.Arguments["id"].ToString();
// return Task.FromResult(users.FirstOrDefault(user => user.Id == id));
var loader = accessor.Context.GetOrAddBatchLoader<string, User>("GetAccountByIdAsync", ids =>
{
var results = users.Where(user => ids.Contains(user.Id));
return Task.FromResult((IDictionary<string, User>)results.ToDictionary(c => c.Id));
});
return Task.FromResult(loader.LoadAsync(id));
});
var query = @"
{
_entities(representations: [{__typename: ""User"", id: ""1"" }, {__typename: ""User"", id: ""2"" }]) {
... on User {
id
username
}
}
}";
var expected = @"{ ""_entities"": [{ ""__typename"": ""User"", ""id"" : ""1"", ""username"": ""One"" }, { ""__typename"": ""User"", ""id"" : ""2"", ""username"": ""Two"" }] }";
AssertQuery(_ =>
{
_.Definitions = definitions;
_.Query = query;
_.ExpectedResult = expected;
_.Listeners.Add(listener);
});
}
}
}
| |
//*********************************************************
//
// 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.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using BackgroundTask;
namespace SDKTemplate
{
public partial class MainPage : Page
{
public const string FEATURE_NAME = "BackgroundTask";
List<Scenario> scenarios = new List<Scenario>
{
new Scenario() { Title="Background Task", ClassType=typeof(BackgroundTask.SampleBackgroundTask)},
new Scenario() { Title="Background Task with Condition", ClassType=typeof(BackgroundTask.SampleBackgroundTaskWithCondition)},
new Scenario() { Title="Servicing Complete Task", ClassType=typeof(BackgroundTask.ServicingCompleteTask)},
new Scenario() { Title="Background Task with Time Trigger", ClassType=typeof(BackgroundTask.TimeTriggeredTask) },
new Scenario() { Title="Background Task with Application Trigger", ClassType=typeof(BackgroundTask.ApplicationTriggerTask) }
};
}
public class Scenario
{
public string Title { get; set; }
public Type ClassType { get; set; }
}
}
namespace BackgroundTask
{
class BackgroundTaskSample
{
public const string SampleBackgroundTaskEntryPoint = "Tasks.SampleBackgroundTask";
public const string SampleBackgroundTaskName = "SampleBackgroundTask";
public static string SampleBackgroundTaskProgress = "";
public static bool SampleBackgroundTaskRegistered = false;
public const string SampleBackgroundTaskWithConditionName = "SampleBackgroundTaskWithCondition";
public static string SampleBackgroundTaskWithConditionProgress = "";
public static bool SampleBackgroundTaskWithConditionRegistered = false;
public const string ServicingCompleteTaskEntryPoint = "Tasks.ServicingComplete";
public const string ServicingCompleteTaskName = "ServicingCompleteTask";
public static string ServicingCompleteTaskProgress = "";
public static bool ServicingCompleteTaskRegistered = false;
public const string TimeTriggeredTaskName = "TimeTriggeredTask";
public static string TimeTriggeredTaskProgress = "";
public static bool TimeTriggeredTaskRegistered = false;
public const string ApplicationTriggerTaskName = "ApplicationTriggerTask";
public static string ApplicationTriggerTaskProgress = "";
public static string ApplicationTriggerTaskResult = "";
public static bool ApplicationTriggerTaskRegistered = false;
/// <summary>
/// Register a background task with the specified taskEntryPoint, name, trigger,
/// and condition (optional).
/// </summary>
/// <param name="taskEntryPoint">Task entry point for the background task.</param>
/// <param name="name">A name for the background task.</param>
/// <param name="trigger">The trigger for the background task.</param>
/// <param name="condition">An optional conditional event that must be true for the task to fire.</param>
public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition)
{
if (TaskRequiresBackgroundAccess(name))
{
await BackgroundExecutionManager.RequestAccessAsync();
}
var builder = new BackgroundTaskBuilder();
builder.Name = name;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
if (condition != null)
{
builder.AddCondition(condition);
//
// If the condition changes while the background task is executing then it will
// be canceled.
//
builder.CancelOnConditionLoss = true;
}
BackgroundTaskRegistration task = builder.Register();
UpdateBackgroundTaskStatus(name, true);
//
// Remove previous completion status from local settings.
//
var settings = ApplicationData.Current.LocalSettings;
settings.Values.Remove(name);
return task;
}
/// <summary>
/// Unregister background tasks with specified name.
/// </summary>
/// <param name="name">Name of the background task to unregister.</param>
public static void UnregisterBackgroundTasks(String name)
{
//
// Loop through all background tasks and unregister any with SampleBackgroundTaskName or
// SampleBackgroundTaskWithConditionName.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == name)
{
cur.Value.Unregister(true);
}
}
UpdateBackgroundTaskStatus(name, false);
}
/// <summary>
/// Store the registration status of a background task with a given name.
/// </summary>
/// <param name="name">Name of background task to store registration status for.</param>
/// <param name="registered">TRUE if registered, FALSE if unregistered.</param>
public static void UpdateBackgroundTaskStatus(String name, bool registered)
{
switch (name)
{
case SampleBackgroundTaskName:
SampleBackgroundTaskRegistered = registered;
break;
case SampleBackgroundTaskWithConditionName:
SampleBackgroundTaskWithConditionRegistered = registered;
break;
case ServicingCompleteTaskName:
ServicingCompleteTaskRegistered = registered;
break;
case TimeTriggeredTaskName:
TimeTriggeredTaskRegistered = registered;
break;
case ApplicationTriggerTaskName:
ApplicationTriggerTaskRegistered = registered;
break;
}
}
/// <summary>
/// Get the registration / completion status of the background task with
/// given name.
/// </summary>
/// <param name="name">Name of background task to retreive registration status.</param>
public static String GetBackgroundTaskStatus(String name)
{
var registered = false;
switch (name)
{
case SampleBackgroundTaskName:
registered = SampleBackgroundTaskRegistered;
break;
case SampleBackgroundTaskWithConditionName:
registered = SampleBackgroundTaskWithConditionRegistered;
break;
case ServicingCompleteTaskName:
registered = ServicingCompleteTaskRegistered;
break;
case TimeTriggeredTaskName:
registered = TimeTriggeredTaskRegistered;
break;
case ApplicationTriggerTaskName:
registered = ApplicationTriggerTaskRegistered;
break;
}
var status = registered ? "Registered" : "Unregistered";
var settings = ApplicationData.Current.LocalSettings;
if (settings.Values.ContainsKey(name))
{
status += " - " + settings.Values[name].ToString();
}
return status;
}
/// <summary>
/// Determine if task with given name requires background access.
/// </summary>
/// <param name="name">Name of background task to query background access requirement.</param>
public static bool TaskRequiresBackgroundAccess(String name)
{
if ((name == TimeTriggeredTaskName) ||
(name == ApplicationTriggerTaskName))
{
return true;
}
else
{
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using NUnit.Framework;
using Projac.Sql.Tests.Framework;
namespace Projac.Sql.Tests
{
namespace SqlProjectionTests
{
[TestFixture]
public class AnyInstanceTests
{
class Any : SqlProjection
{
}
private SqlProjection _sut;
[SetUp]
public void SetUp()
{
_sut = new Any();
}
[Test]
public void IsEnumerableOfSqlProjectionHandler()
{
Assert.That(_sut, Is.AssignableTo<IEnumerable<SqlProjectionHandler>>());
}
}
[TestFixture]
public class InstanceWithoutHandlersTests
{
class WithoutHandlers : SqlProjection
{
}
private SqlProjection _sut;
[SetUp]
public void SetUp()
{
_sut = new WithoutHandlers();
}
[Test]
public void GetEnumeratorReturnsExpectedInstance()
{
Assert.That(_sut, Is.Empty);
}
[Test]
public void HandlersReturnsExpectedResult()
{
Assert.That(_sut.Handlers, Is.Empty);
}
[Test]
public void ImplicitConversionToSqlProjectionHandlerArray()
{
SqlProjectionHandler[] result = _sut;
Assert.That(result, Is.Empty);
}
[Test]
public void ExplicitConversionToSqlProjectionHandlerArray()
{
var result = (SqlProjectionHandler[])_sut;
Assert.That(result, Is.Empty);
}
}
[TestFixture]
public class InstanceWithHandlersTests
{
class WithHandlers : SqlProjection
{
private readonly SqlNonQueryCommand _command;
private readonly SqlNonQueryCommand[] _commandArray;
private readonly IEnumerable<SqlNonQueryCommand> _commandEnumeration;
private readonly SqlNonQueryCommand[] _result;
public WithHandlers()
{
_command = CommandFactory();
_commandArray = new[]
{
CommandFactory(), CommandFactory()
};
_commandEnumeration = Enumerable.Repeat(CommandFactory(), 1);
var commands = new List<SqlNonQueryCommand>();
commands.Add(_command);
commands.AddRange(_commandArray);
commands.AddRange(_commandEnumeration);
_result = commands.ToArray();
When<object>(m => _command);
When<object>(m => _commandArray);
When<object>(m => _commandEnumeration);
}
public SqlNonQueryCommand[] Result
{
get { return _result; }
}
private static SqlNonQueryCommand CommandFactory()
{
return new SqlNonQueryCommandStub("", new DbParameter[0], CommandType.Text);
}
}
private WithHandlers _sut;
[SetUp]
public void SetUp()
{
_sut = new WithHandlers();
}
[Test]
public void GetEnumeratorReturnsExpectedInstance()
{
IEnumerable<SqlProjectionHandler> result = _sut;
Assert.That(result.SelectMany(_ => _.Handler(null)),
Is.EqualTo(_sut.Result));
}
[Test]
public void HandlersReturnsExpectedResult()
{
var result = _sut.Handlers;
Assert.That(result.SelectMany(_ => _.Handler(null)),
Is.EqualTo(_sut.Result));
}
[Test]
public void ImplicitConversionToSqlProjectionHandlerArray()
{
SqlProjectionHandler[] result = _sut;
Assert.That(result.SelectMany(_ => _.Handler(null)),
Is.EqualTo(_sut.Result));
}
[Test]
public void ExplicitConversionToSqlProjectionHandlerArray()
{
var result = (SqlProjectionHandler[])_sut;
Assert.That(result.SelectMany(_ => _.Handler(null)),
Is.EqualTo(_sut.Result));
}
}
[TestFixture]
public class SqlNonQueryCommandReturningHandlerTests
{
[Test]
public void WhenHandlerCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(
() => new RegisterNullHandler());
}
[Test]
public void WhenHasExpectedResult()
{
var command = CommandFactory();
var handler = HandlerFactory(command);
var sut = new RegisterHandlers(handler);
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EquivalentTo(new[] {command}));
}
[Test]
public void SuccessiveWhenHasExpectedResult()
{
var commands = new List<SqlNonQueryCommand>();
var handlers = new List<Func<object, SqlNonQueryCommand>>();
for (var index = 0; index < Random.Next(2, 100); index++)
{
commands.Add(CommandFactory());
handlers.Add(HandlerFactory(commands[commands.Count - 1]));
}
var sut = new RegisterHandlers(handlers.ToArray());
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EquivalentTo(commands));
}
[Test]
public void SuccessiveWhenRetainsOrder()
{
var commands = new List<SqlNonQueryCommand>();
var handlers = new List<Func<object, SqlNonQueryCommand>>();
for (var index = 0; index < Random.Next(2, 100); index++)
{
commands.Add(CommandFactory());
handlers.Add(HandlerFactory(commands[commands.Count - 1]));
}
commands.Reverse();
handlers.Reverse();
var sut = new RegisterHandlers(handlers.ToArray());
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EquivalentTo(commands));
}
private static readonly Random Random = new Random();
private static Func<object, SqlNonQueryCommand> HandlerFactory(SqlNonQueryCommand command)
{
return o => command;
}
private static SqlNonQueryCommand CommandFactory()
{
return new SqlNonQueryCommandStub("", new DbParameter[0], CommandType.Text);
}
private class RegisterNullHandler : SqlProjection
{
public RegisterNullHandler()
{
When((Func<object, SqlNonQueryCommand>) null);
}
}
private class RegisterHandlers : SqlProjection
{
public RegisterHandlers(params Func<object, SqlNonQueryCommand>[] handlers)
{
foreach (var handler in handlers)
When(handler);
}
}
}
[TestFixture]
public class SqlNonQueryCommandArrayReturningHandlerTests
{
[Test]
public void WhenHandlerCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(
() => new RegisterNullHandler());
}
[Test]
public void WhenHasExpectedResult()
{
var command1 = CommandFactory();
var command2 = CommandFactory();
var handler = HandlerFactory(command1, command2);
var sut = new RegisterHandlers(handler);
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EquivalentTo(new[] {command1, command2}));
}
[Test]
public void SuccessiveWhenHasExpectedResult()
{
var commands = new List<SqlNonQueryCommand>();
var handlers = new List<Func<object, SqlNonQueryCommand[]>>();
for (var index = 0; index < Random.Next(2, 100); index++)
{
var handlerCommands = RandomCommandSet();
commands.AddRange(handlerCommands);
handlers.Add(HandlerFactory(handlerCommands.ToArray()));
}
var sut = new RegisterHandlers(handlers.ToArray());
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EqualTo(commands));
}
[Test]
public void SuccessiveWhenRetainsOrder()
{
var commands = new List<SqlNonQueryCommand>();
var handlers = new List<Func<object, SqlNonQueryCommand[]>>();
for (var index = 0; index < Random.Next(2, 100); index++)
{
var handlerCommands = RandomCommandSet();
commands.InsertRange(0, handlerCommands);
handlers.Add(HandlerFactory(handlerCommands.ToArray()));
}
handlers.Reverse();
var sut = new RegisterHandlers(handlers.ToArray());
Assert.That(sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EqualTo(commands));
}
private static readonly Random Random = new Random();
private static List<SqlNonQueryCommand> RandomCommandSet()
{
var handlerCommands = new List<SqlNonQueryCommand>();
for (var commandCount = 0; commandCount < Random.Next(2, 10); commandCount++)
{
handlerCommands.Add(CommandFactory());
}
return handlerCommands;
}
private class RegisterNullHandler : SqlProjection
{
public RegisterNullHandler()
{
When((Func<object, SqlNonQueryCommand[]>) null);
}
}
private class RegisterHandlers : SqlProjection
{
public RegisterHandlers(params Func<object, SqlNonQueryCommand[]>[] handlers)
{
foreach (var handler in handlers)
When(handler);
}
}
private static Func<object, SqlNonQueryCommand[]> HandlerFactory(params SqlNonQueryCommand[] commands)
{
return o => commands;
}
private static SqlNonQueryCommand CommandFactory()
{
return new SqlNonQueryCommandStub("", new DbParameter[0], CommandType.Text);
}
}
[TestFixture]
public class SqlNonQueryCommandEnumerationReturningHandlerTests
{
[Test]
public void WhenHandlerCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(
() => new RegisterNullHandler());
}
[Test]
public void WhenHasExpectedResult()
{
var command1 = CommandFactory();
var command2 = CommandFactory();
var handler = HandlerFactory(command1, command2);
var sut = new RegisterHandlers(handler);
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EquivalentTo(new[] {command1, command2}));
}
[Test]
public void SuccessiveWhenHasExpectedResult()
{
var commands = new List<SqlNonQueryCommand>();
var handlers = new List<Func<object, IEnumerable<SqlNonQueryCommand>>>();
for (var index = 0; index < Random.Next(2, 100); index++)
{
var handlerCommands = RandomCommandSet();
commands.AddRange(handlerCommands);
handlers.Add(HandlerFactory(handlerCommands.ToArray()));
}
var sut = new RegisterHandlers(handlers.ToArray());
Assert.That(
sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EqualTo(commands));
}
[Test]
public void SuccessiveWhenRetainsOrder()
{
var commands = new List<SqlNonQueryCommand>();
var handlers = new List<Func<object, IEnumerable<SqlNonQueryCommand>>>();
for (var index = 0; index < Random.Next(2, 100); index++)
{
var handlerCommands = RandomCommandSet();
commands.InsertRange(0, handlerCommands);
handlers.Add(HandlerFactory(handlerCommands.ToArray()));
}
handlers.Reverse();
var sut = new RegisterHandlers(handlers.ToArray());
Assert.That(sut.Handlers.SelectMany(_ => _.Handler(null)),
Is.EqualTo(commands));
}
private static readonly Random Random = new Random();
private static List<SqlNonQueryCommand> RandomCommandSet()
{
var handlerCommands = new List<SqlNonQueryCommand>();
for (var commandCount = 0; commandCount < Random.Next(2, 10); commandCount++)
{
handlerCommands.Add(CommandFactory());
}
return handlerCommands;
}
private class RegisterNullHandler : SqlProjection
{
public RegisterNullHandler()
{
When((Func<object, IEnumerable<SqlNonQueryCommand>>) null);
}
}
private class RegisterHandlers : SqlProjection
{
public RegisterHandlers(params Func<object, IEnumerable<SqlNonQueryCommand>>[] handlers)
{
foreach (var handler in handlers)
When(handler);
}
}
private static Func<object, SqlNonQueryCommand[]> HandlerFactory(params SqlNonQueryCommand[] commands)
{
return o => commands;
}
private static SqlNonQueryCommand CommandFactory()
{
return new SqlNonQueryCommandStub("", new DbParameter[0], CommandType.Text);
}
}
}
}
| |
/*
* 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.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace OpenSim.Region.CoreModules.World.Serialiser
{
public class SerialiserModule : ISharedRegionModule, IRegionSerialiserModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private Commander m_commander = new Commander("export");
private List<Scene> m_regions = new List<Scene>();
private string m_savedir = "exports";
private List<IFileSerialiser> m_serialisers = new List<IFileSerialiser>();
#region ISharedRegionModule Members
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["Serialiser"];
if (config != null)
{
m_savedir = config.GetString("save_dir", m_savedir);
}
m_log.InfoFormat("[Serialiser] Enabled, using save dir \"{0}\"", m_savedir);
}
public void PostInitialise()
{
lock (m_serialisers)
{
m_serialisers.Add(new SerialiseTerrain());
m_serialisers.Add(new SerialiseObjects());
}
// LoadCommanderCommands();
}
public void AddRegion(Scene scene)
{
// scene.RegisterModuleCommander(m_commander);
// scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
scene.RegisterModuleInterface<IRegionSerialiserModule>(this);
lock (m_regions)
{
m_regions.Add(scene);
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
lock (m_regions)
{
m_regions.Remove(scene);
}
}
public void Close()
{
m_regions.Clear();
}
public string Name
{
get { return "ExportSerialisationModule"; }
}
#endregion
#region IRegionSerialiser Members
public void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
SceneXmlLoader.LoadPrimsFromXml(scene, fileName, newIDS, loadOffset);
}
public void SavePrimsToXml(Scene scene, string fileName)
{
SceneXmlLoader.SavePrimsToXml(scene, fileName);
}
public void LoadPrimsFromXml2(Scene scene, string fileName)
{
SceneXmlLoader.LoadPrimsFromXml2(scene, fileName);
}
public void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
SceneXmlLoader.LoadPrimsFromXml2(scene, reader, startScripts);
}
public void SavePrimsToXml2(Scene scene, string fileName)
{
SceneXmlLoader.SavePrimsToXml2(scene, fileName);
}
public void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
SceneXmlLoader.SavePrimsToXml2(scene, stream, min, max);
}
public void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
SceneXmlLoader.SaveNamedPrimsToXml2(scene, primName, fileName);
}
public SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneXmlLoader.DeserializeGroupFromXml2(xmlString);
}
public string SerializeGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
return SceneXmlLoader.SaveGroupToXml2(grp, options);
}
public void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
SceneXmlLoader.SavePrimListToXml2(entityList, fileName);
}
public void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
SceneXmlLoader.SavePrimListToXml2(entityList, stream, min, max);
}
public List<string> SerialiseRegion(Scene scene, string saveDir)
{
List<string> results = new List<string>();
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
lock (m_serialisers)
{
foreach (IFileSerialiser serialiser in m_serialisers)
{
results.Add(serialiser.WriteToFile(scene, saveDir));
}
}
TextWriter regionInfoWriter = new StreamWriter(Path.Combine(saveDir, "README.TXT"));
regionInfoWriter.WriteLine("Region Name: " + scene.RegionInfo.RegionName);
regionInfoWriter.WriteLine("Region ID: " + scene.RegionInfo.RegionID.ToString());
regionInfoWriter.WriteLine("Backup Time: UTC " + DateTime.UtcNow.ToString());
regionInfoWriter.WriteLine("Serialise Version: 0.1");
regionInfoWriter.Close();
TextWriter manifestWriter = new StreamWriter(Path.Combine(saveDir, "region.manifest"));
foreach (string line in results)
{
manifestWriter.WriteLine(line);
}
manifestWriter.Close();
return results;
}
#endregion
// private void EventManager_OnPluginConsole(string[] args)
// {
// if (args[0] == "export")
// {
// string[] tmpArgs = new string[args.Length - 2];
// int i = 0;
// for (i = 2; i < args.Length; i++)
// tmpArgs[i - 2] = args[i];
//
// m_commander.ProcessConsoleCommand(args[1], tmpArgs);
// }
// }
private void InterfaceSaveRegion(Object[] args)
{
foreach (Scene region in m_regions)
{
if (region.RegionInfo.RegionName == (string) args[0])
{
// List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
SerialiseRegion(region, Path.Combine(m_savedir, region.RegionInfo.RegionID.ToString()));
}
}
}
private void InterfaceSaveAllRegions(Object[] args)
{
foreach (Scene region in m_regions)
{
// List<string> results = SerialiseRegion(region, m_savedir + region.RegionInfo.RegionID.ToString() + "/");
SerialiseRegion(region, Path.Combine(m_savedir, region.RegionInfo.RegionID.ToString()));
}
}
// private void LoadCommanderCommands()
// {
// Command serialiseSceneCommand = new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveRegion, "Saves the named region into the exports directory.");
// serialiseSceneCommand.AddArgument("region-name", "The name of the region you wish to export", "String");
//
// Command serialiseAllScenesCommand = new Command("save-all",CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveAllRegions, "Saves all regions into the exports directory.");
//
// m_commander.RegisterCommand("save", serialiseSceneCommand);
// m_commander.RegisterCommand("save-all", serialiseAllScenesCommand);
// }
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;
using ServiceStack.Common;
using ServiceStack.MiniProfiler.UI;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.WebHost.Endpoints.Support;
using HttpRequestWrapper = ServiceStack.WebHost.Endpoints.Extensions.HttpRequestWrapper;
namespace ServiceStack.WebHost.Endpoints
{
public class ServiceStackHttpHandlerFactory
: IHttpHandlerFactory
{
static readonly List<string> WebHostRootFileNames = new List<string>();
static private readonly string WebHostPhysicalPath = null;
static private readonly string DefaultRootFileName = null;
static private string ApplicationBaseUrl = null;
static private readonly IHttpHandler DefaultHttpHandler = null;
static private readonly RedirectHttpHandler NonRootModeDefaultHttpHandler = null;
static private readonly IHttpHandler ForbiddenHttpHandler = null;
static private readonly IHttpHandler NotFoundHttpHandler = null;
static private readonly IHttpHandler StaticFileHandler = new StaticFileHandler();
private static readonly bool IsIntegratedPipeline = false;
private static readonly bool ServeDefaultHandler = false;
private static readonly bool AutoRedirectsDirs = false;
private static Func<IHttpRequest, IHttpHandler>[] RawHttpHandlers;
[ThreadStatic]
public static string DebugLastHandlerArgs;
static ServiceStackHttpHandlerFactory()
{
//MONO doesn't implement this property
var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline");
if (pi != null)
{
IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]);
}
var config = EndpointHost.Config;
if (config == null)
{
throw new ConfigurationErrorsException(
"ServiceStack: AppHost does not exist or has not been initialized. "
+ "Make sure you have created an AppHost and started it with 'new AppHost().Init();' in your Global.asax Application_Start()",
new ArgumentNullException("EndpointHost.Config"));
}
var isAspNetHost = HttpListenerBase.Instance == null || HttpContext.Current != null;
WebHostPhysicalPath = config.WebHostPhysicalPath;
AutoRedirectsDirs = isAspNetHost && !Env.IsMono;
//Apache+mod_mono treats path="servicestack*" as path="*" so takes over root path, so we need to serve matching resources
var hostedAtRootPath = config.ServiceStackHandlerFactoryPath == null;
//DefaultHttpHandler not supported in IntegratedPipeline mode
if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono)
DefaultHttpHandler = new DefaultHttpHandler();
ServeDefaultHandler = hostedAtRootPath || Env.IsMono;
if (ServeDefaultHandler)
{
foreach (var filePath in Directory.GetFiles(WebHostPhysicalPath))
{
var fileNameLower = Path.GetFileName(filePath).ToLower();
if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower))
{
//Can't serve Default.aspx pages when hostedAtRootPath so ignore and allow for next default document
if (!(hostedAtRootPath && fileNameLower.EndsWith(".aspx")))
{
DefaultRootFileName = fileNameLower;
((StaticFileHandler)StaticFileHandler).SetDefaultFile(filePath);
if (DefaultHttpHandler == null)
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = DefaultRootFileName };
}
}
WebHostRootFileNames.Add(Path.GetFileName(fileNameLower));
}
foreach (var dirName in Directory.GetDirectories(WebHostPhysicalPath))
{
var dirNameLower = Path.GetFileName(dirName).ToLower();
WebHostRootFileNames.Add(Path.GetFileName(dirNameLower));
}
}
if (!string.IsNullOrEmpty(config.DefaultRedirectPath))
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.DefaultRedirectPath };
if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath))
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath };
if (!string.IsNullOrEmpty(config.MetadataRedirectPath))
NonRootModeDefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath };
if (DefaultHttpHandler == null)
DefaultHttpHandler = NotFoundHttpHandler;
var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler;
var debugDefaultHandler = defaultRedirectHanlder != null
? defaultRedirectHanlder.RelativeUrl
: typeof(DefaultHttpHandler).Name;
SetApplicationBaseUrl(config.WebHostUrl);
ForbiddenHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden);
if (ForbiddenHttpHandler == null)
{
ForbiddenHttpHandler = new ForbiddenHttpHandler
{
IsIntegratedPipeline = IsIntegratedPipeline,
WebHostPhysicalPath = WebHostPhysicalPath,
WebHostRootFileNames = WebHostRootFileNames,
ApplicationBaseUrl = ApplicationBaseUrl,
DefaultRootFileName = DefaultRootFileName,
DefaultHandler = debugDefaultHandler,
};
}
NotFoundHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.NotFound);
if (NotFoundHttpHandler == null)
{
NotFoundHttpHandler = new NotFoundHttpHandler
{
IsIntegratedPipeline = IsIntegratedPipeline,
WebHostPhysicalPath = WebHostPhysicalPath,
WebHostRootFileNames = WebHostRootFileNames,
ApplicationBaseUrl = ApplicationBaseUrl,
DefaultRootFileName = DefaultRootFileName,
DefaultHandler = debugDefaultHandler,
};
}
var rawHandlers = config.RawHttpHandlers;
rawHandlers.Add(ReturnRequestInfo);
rawHandlers.Add(MiniProfilerHandler.MatchesRequest);
RawHttpHandlers = rawHandlers.ToArray();
}
// Entry point for ASP.NET
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated;
var httpReq = new HttpRequestWrapper(pathTranslated, context.Request);
foreach (var rawHttpHandler in RawHttpHandlers)
{
var reqInfo = rawHttpHandler(httpReq);
if (reqInfo != null) return reqInfo;
}
var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath;
var pathInfo = context.Request.GetPathInfo();
//WebDev Server auto requests '/default.aspx' so recorrect path to different default document
if (mode == null && (url == "/default.aspx" || url == "/Default.aspx"))
pathInfo = "/";
//Default Request /
if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
{
//Exception calling context.Request.Url on Apache+mod_mono
if (ApplicationBaseUrl == null)
{
var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl();
SetApplicationBaseUrl(absoluteUrl);
}
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
if (catchAllHandler != null) return catchAllHandler;
return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler;
}
if (mode != null && pathInfo.EndsWith(mode))
{
var requestPath = context.Request.Path.ToLower();
if (requestPath == "/" + mode
|| requestPath == mode
|| requestPath == mode + "/")
{
if (context.Request.PhysicalPath != WebHostPhysicalPath
|| !File.Exists(Path.Combine(context.Request.PhysicalPath, DefaultRootFileName ?? "")))
{
return new IndexPageHttpHandler();
}
}
var okToServe = ShouldAllow(context.Request.FilePath);
return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler;
}
return GetHandlerForPathInfo(
httpReq.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated)
?? NotFoundHttpHandler;
}
private static void SetApplicationBaseUrl(string absoluteUrl)
{
if (absoluteUrl == null) return;
ApplicationBaseUrl = absoluteUrl;
var defaultRedirectUrl = DefaultHttpHandler as RedirectHttpHandler;
if (defaultRedirectUrl != null && defaultRedirectUrl.AbsoluteUrl == null)
defaultRedirectUrl.AbsoluteUrl = ApplicationBaseUrl.CombineWith(
defaultRedirectUrl.RelativeUrl);
if (NonRootModeDefaultHttpHandler != null && NonRootModeDefaultHttpHandler.AbsoluteUrl == null)
NonRootModeDefaultHttpHandler.AbsoluteUrl = ApplicationBaseUrl.CombineWith(
NonRootModeDefaultHttpHandler.RelativeUrl);
}
public static string GetBaseUrl()
{
return EndpointHost.Config.WebHostUrl ?? ApplicationBaseUrl;
}
// Entry point for HttpListener
public static IHttpHandler GetHandler(IHttpRequest httpReq)
{
foreach (var rawHttpHandler in RawHttpHandlers)
{
var reqInfo = rawHttpHandler(httpReq);
if (reqInfo != null) return reqInfo;
}
var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath;
var pathInfo = httpReq.PathInfo;
//Default Request /
if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
{
if (ApplicationBaseUrl == null)
SetApplicationBaseUrl(httpReq.GetPathUrl());
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
if (catchAllHandler != null) return catchAllHandler;
return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler;
}
if (mode != null && pathInfo.EndsWith(mode))
{
var requestPath = pathInfo;
if (requestPath == "/" + mode
|| requestPath == mode
|| requestPath == mode + "/")
{
//TODO: write test for this
if (httpReq.GetPhysicalPath() != WebHostPhysicalPath
|| !File.Exists(Path.Combine(httpReq.ApplicationFilePath, DefaultRootFileName ?? "")))
{
return new IndexPageHttpHandler();
}
}
var okToServe = ShouldAllow(httpReq.GetPhysicalPath());
return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler;
}
return GetHandlerForPathInfo(httpReq.HttpMethod, pathInfo, pathInfo, httpReq.GetPhysicalPath())
?? NotFoundHttpHandler;
}
/// <summary>
/// If enabled, just returns the Request Info as it understands
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private static IHttpHandler ReturnRequestInfo(HttpRequest httpReq)
{
if (EndpointHost.Config.DebugOnlyReturnRequestInfo
|| (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo")))
{
var reqInfo = RequestInfoHandler.GetRequestInfo(
new HttpRequestWrapper(typeof(RequestInfo).Name, httpReq));
reqInfo.Host = EndpointHost.Config.DebugAspNetHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName;
//reqInfo.FactoryUrl = url; //Just RawUrl without QueryString
//reqInfo.FactoryPathTranslated = pathTranslated; //Local path on filesystem
reqInfo.PathInfo = httpReq.PathInfo;
reqInfo.Path = httpReq.Path;
reqInfo.ApplicationPath = httpReq.ApplicationPath;
return new RequestInfoHandler { RequestInfo = reqInfo };
}
return null;
}
private static IHttpHandler ReturnRequestInfo(IHttpRequest httpReq)
{
if (EndpointHost.Config.DebugOnlyReturnRequestInfo
|| (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo")))
{
var reqInfo = RequestInfoHandler.GetRequestInfo(httpReq);
reqInfo.Host = EndpointHost.Config.DebugHttpListenerHostEnvironment + "_v" + Env.ServiceStackVersion + "_" + EndpointHost.Config.ServiceName;
reqInfo.PathInfo = httpReq.PathInfo;
reqInfo.Path = httpReq.GetPathUrl();
return new RequestInfoHandler { RequestInfo = reqInfo };
}
return null;
}
// no handler registered
// serve the file from the filesystem, restricting to a safelist of extensions
private static bool ShouldAllow(string filePath)
{
var fileExt = Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileExt)) return false;
return EndpointHost.Config.AllowFileExtensions.Contains(fileExt.Substring(1));
}
public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath)
{
var pathParts = pathInfo.TrimStart('/').Split('/');
if (pathParts.Length == 0) return NotFoundHttpHandler;
string contentType;
var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType);
if (restPath != null)
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType };
var existingFile = pathParts[0].ToLower();
if (WebHostRootFileNames.Contains(existingFile))
{
var fileExt = Path.GetExtension(filePath);
var isFileRequest = !string.IsNullOrEmpty(fileExt);
if (!isFileRequest && !AutoRedirectsDirs)
{
//If pathInfo is for Directory try again with redirect including '/' suffix
if (!pathInfo.EndsWith("/"))
{
var appFilePath = filePath.Substring(0, filePath.Length - requestPath.Length);
var redirect = Support.StaticFileHandler.DirectoryExists(filePath, appFilePath);
if (redirect)
{
return new RedirectHttpHandler
{
RelativeUrl = pathInfo + "/",
};
}
}
}
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
if (catchAllHandler != null) return catchAllHandler;
if (!isFileRequest) return NotFoundHttpHandler;
return ShouldAllow(requestPath) ? StaticFileHandler : ForbiddenHttpHandler;
}
var handler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
if (handler != null) return handler;
if (EndpointHost.Config.FallbackRestPath != null)
{
restPath = EndpointHost.Config.FallbackRestPath(httpMethod, pathInfo, filePath);
if (restPath != null)
{
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType };
}
}
return null;
}
private static IHttpHandler GetCatchAllHandlerIfAny(string httpMethod, string pathInfo, string filePath)
{
if (EndpointHost.CatchAllHandlers != null)
{
foreach (var httpHandlerResolver in EndpointHost.CatchAllHandlers)
{
var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath);
if (httpHandler != null)
return httpHandler;
}
}
return null;
}
public void ReleaseHandler(IHttpHandler handler)
{
}
}
}
| |
// 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.IO;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class OpenSsl
{
private static Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
#region internal methods
internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType)
{
SafeChannelBindingHandle bindingHandle;
switch (bindingType)
{
case ChannelBindingKind.Endpoint:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryEndPointChannelBinding(context, bindingHandle);
break;
case ChannelBindingKind.Unique:
bindingHandle = new SafeChannelBindingHandle(bindingType);
QueryUniqueChannelBinding(context, bindingHandle);
break;
default:
// Keeping parity with windows, we should return null in this case.
bindingHandle = null;
break;
}
return bindingHandle;
}
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
{
SafeSslHandle context = null;
IntPtr method = GetSslMethod(protocols);
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
Ssl.SetProtocolOptions(innerContext, protocols);
// The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet
// shutdown (we aren't negotating for session close to enable later session
// restoration).
//
// If you find yourself wanting to remove this line to enable bidirectional
// close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect().
// https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
Ssl.SslCtxSetQuietShutdown(innerContext);
if (!Ssl.SetEncryptionPolicy(innerContext, policy))
{
throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy));
}
if (certHandle != null && certKeyHandle != null)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (remoteCertRequired)
{
Debug.Assert(isServer, "isServer flag should be true");
Ssl.SslCtxSetVerify(innerContext,
s_verifyClientCertificate);
//update the client CA list
UpdateCAListFromRootStore(innerContext);
}
context = SafeSslHandle.Create(innerContext, isServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
BioWrite(context.InputBio, recvBuf, recvOffset, recvCount);
}
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
Exception innerError;
Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
sendBuf = null;
sendCount = 0;
}
}
}
bool stateOk = Ssl.IsSslStateOK(context);
if (stateOk)
{
context.MarkHandshakeCompleted();
}
return stateOk;
}
internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, out Ssl.SslErrorCode errorCode)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
unsafe
{
fixed (byte* fixedBuffer = buffer)
{
retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
Debug.Assert(buffer.Length >= capacityNeeded, "Input buffer of size " + buffer.Length +
" bytes is insufficient since encryption needs " + capacityNeeded + " bytes.");
retVal = BioRead(context.OutputBio, buffer, capacityNeeded);
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode)
{
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, 0, count);
if (retVal == count)
{
retVal = Ssl.SslRead(context, outBuffer, outBuffer.Length);
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
Exception innerError;
errorCode = GetSslError(context, retVal, out innerError);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
#endregion
#region private methods
private static void QueryEndPointChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
using (SafeX509Handle certSafeHandle = GetPeerCertificate(context))
{
if (certSafeHandle == null || certSafeHandle.IsInvalid)
{
throw CreateSslException(SR.net_ssl_invalid_certificate);
}
bool gotReference = false;
try
{
certSafeHandle.DangerousAddRef(ref gotReference);
using (X509Certificate2 cert = new X509Certificate2(certSafeHandle.DangerousGetHandle()))
using (HashAlgorithm hashAlgo = GetHashForChannelBinding(cert))
{
byte[] bindingHash = hashAlgo.ComputeHash(cert.RawData);
bindingHandle.SetCertHash(bindingHash);
}
}
finally
{
if (gotReference)
{
certSafeHandle.DangerousRelease();
}
}
}
}
private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle)
{
bool sessionReused = Ssl.SslSessionReused(context);
int certHashLength = context.IsServer ^ sessionReused ?
Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) :
Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length);
if (0 == certHashLength)
{
throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed);
}
bindingHandle.SetCertHashLength(certHashLength);
}
private static IntPtr GetSslMethod(SslProtocols protocols)
{
Debug.Assert(protocols != SslProtocols.None, "All protocols are disabled");
bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2;
bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3;
bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls;
bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11;
bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12;
IntPtr method = Ssl.SslMethods.SSLv23_method; // default
string methodName = "SSLv23_method";
if (!ssl2)
{
if (!ssl3)
{
if (!tls11 && !tls12)
{
method = Ssl.SslMethods.TLSv1_method;
methodName = "TLSv1_method";
}
else if (!tls10 && !tls12)
{
method = Ssl.SslMethods.TLSv1_1_method;
methodName = "TLSv1_1_method";
}
else if (!tls10 && !tls11)
{
method = Ssl.SslMethods.TLSv1_2_method;
methodName = "TLSv1_2_method";
}
}
else if (!tls10 && !tls11 && !tls12)
{
method = Ssl.SslMethods.SSLv3_method;
methodName = "SSLv3_method";
}
}
if (IntPtr.Zero == method)
{
throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName));
}
return method;
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
// Full validation is handled after the handshake in VerifyCertificateProperties and the
// user callback. It's also up to those handlers to decide if a null certificate
// is appropriate. So just return success to tell OpenSSL that the cert is acceptable,
// we'll process it after the handshake finishes.
const int OpenSslSuccess = 1;
return OpenSslSuccess;
}
private static void UpdateCAListFromRootStore(SafeSslContextHandle context)
{
using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack())
{
//maintaining the HashSet of Certificate's issuer name to keep track of duplicates
HashSet<string> issuerNameHashSet = new HashSet<string>();
//Enumerate Certificates from LocalMachine and CurrentUser root store
AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet);
AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet);
Ssl.SslCtxSetClientCAList(context, nameStack);
// The handle ownership has been transferred into the CTX.
nameStack.SetHandleAsInvalid();
}
}
private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet)
{
using (var store = new X509Store(StoreName.Root, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
//Check if issuer name is already present
//Avoiding duplicate names
if (!issuerNameHashSet.Add(certificate.Issuer))
{
continue;
}
using (SafeX509Handle certHandle = Crypto.X509Duplicate(certificate.Handle))
{
using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle)))
{
if (Crypto.PushX509NameStackField(nameStack, nameHandle))
{
// The handle ownership has been transferred into the STACK_OF(X509_NAME).
nameHandle.SetHandleAsInvalid();
}
else
{
throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error);
}
}
}
}
}
}
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError)
{
ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
switch (retVal)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
// Some I/O error occurred
innerError =
Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty
result == 0 ? new EndOfStreamException() : // end of file that violates protocol
result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error
null; // no additional info available
break;
case Ssl.SslErrorCode.SSL_ERROR_SSL:
// OpenSSL failure occurred. The error queue contains more details.
innerError = Interop.Crypto.CreateOpenSslCryptographicException();
break;
default:
// No additional info available.
innerError = null;
break;
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
ulong errorVal = Crypto.ErrGetError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.